1 # DB_File.pm -- Perl 5 interface to Berkeley DB
3 # written by Paul Marquess (pmarquess@bfsec.bt.co.uk)
4 # last modified 8th Oct 1997
7 # Copyright (c) 1995, 1996, 1997 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 ;
19 @DB_File::HASHINFO::ISA = qw(Tie::Hash);
34 bless { VALID => { map {$_, 1}
35 qw( bsize ffactor nelem cachesize hash lorder)
47 return $self->{GOT}{$key} if exists $self->{VALID}{$key} ;
50 croak "${pkg}::FETCH - Unknown element '$key'" ;
60 if ( exists $self->{VALID}{$key} )
62 $self->{GOT}{$key} = $value ;
67 croak "${pkg}::STORE - Unknown element '$key'" ;
75 if ( exists $self->{VALID}{$key} )
77 delete $self->{GOT}{$key} ;
82 croak "DB_File::HASHINFO::DELETE - Unknown element '$key'" ;
90 exists $self->{VALID}{$key} ;
98 croak ref($self) . " does not define the method ${method}" ;
101 sub FIRSTKEY { my $self = shift ; $self->NotHere("FIRSTKEY") }
102 sub NEXTKEY { my $self = shift ; $self->NotHere("NEXTKEY") }
103 sub CLEAR { my $self = shift ; $self->NotHere("CLEAR") }
105 package DB_File::RECNOINFO ;
109 @DB_File::RECNOINFO::ISA = qw(DB_File::HASHINFO) ;
115 bless { VALID => { map {$_, 1}
116 qw( bval cachesize psize flags lorder reclen bfname )
122 package DB_File::BTREEINFO ;
126 @DB_File::BTREEINFO::ISA = qw(DB_File::HASHINFO) ;
132 bless { VALID => { map {$_, 1}
133 qw( flags cachesize maxkeypage minkeypage psize
134 compare prefix lorder )
144 use vars qw($VERSION @ISA @EXPORT $AUTOLOAD $DB_BTREE $DB_HASH $DB_RECNO) ;
150 #typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
151 $DB_BTREE = new DB_File::BTREEINFO ;
152 $DB_HASH = new DB_File::HASHINFO ;
153 $DB_RECNO = new DB_File::RECNOINFO ;
159 @ISA = qw(Tie::Hash Exporter DynaLoader);
161 $DB_BTREE $DB_HASH $DB_RECNO
196 ($constname = $AUTOLOAD) =~ s/.*:://;
197 my $val = constant($constname, @_ ? $_[0] : 0);
199 if ($! =~ /Invalid/) {
200 $AutoLoader::AUTOLOAD = $AUTOLOAD;
201 goto &AutoLoader::AUTOLOAD;
204 my($pack,$file,$line) = caller;
205 croak "Your vendor has not defined DB macro $constname, used at $file line $line.
209 eval "sub $AUTOLOAD { $val }";
215 # Make all Fcntl O_XXX constants available for importing
217 my @O = grep /^O_/, @Fcntl::EXPORT;
218 Fcntl->import(@O); # first we import what we want to export
222 bootstrap DB_File $VERSION;
224 # Preloaded methods go here. Autoload methods go after __END__, and are
225 # processed by the autosplit program.
227 sub tie_hash_or_array
230 my $tieHASH = ( (caller(1))[3] =~ /TIEHASH/ ) ;
232 $arg[4] = tied %{ $arg[4] }
233 if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
235 DoTie_($tieHASH, @arg) ;
240 tie_hash_or_array(@_) ;
245 tie_hash_or_array(@_) ;
250 croak "Usage: \$db->get_dup(key [,flag])\n"
251 unless @_ == 2 or @_ == 3 ;
258 my $wantarray = wantarray ;
264 # iterate through the database until either EOF ($status == 0)
265 # or a different key is encountered ($key ne $origkey).
266 for ($status = $db->seq($key, $value, R_CURSOR()) ;
267 $status == 0 and $key eq $origkey ;
268 $status = $db->seq($key, $value, R_NEXT()) ) {
270 # save the value or count number of matches
273 { ++ $values{$value} }
275 { push (@values, $value) }
282 return ($wantarray ? ($flag ? %values : @values) : $counter) ;
291 DB_File - Perl5 access to Berkeley DB
297 [$X =] tie %hash, 'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
298 [$X =] tie %hash, 'DB_File', $filename, $flags, $mode, $DB_BTREE ;
299 [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;
301 $status = $X->del($key [, $flags]) ;
302 $status = $X->put($key, $value [, $flags]) ;
303 $status = $X->get($key, $value [, $flags]) ;
304 $status = $X->seq($key, $value, $flags) ;
305 $status = $X->sync([$flags]) ;
309 $count = $X->get_dup($key) ;
310 @list = $X->get_dup($key) ;
311 %list = $X->get_dup($key, 1) ;
325 B<DB_File> is a module which allows Perl programs to make use of the
326 facilities provided by Berkeley DB. If you intend to use this
327 module you should really have a copy of the Berkeley DB manual pages at
328 hand. The interface defined here mirrors the Berkeley DB interface
331 Please note that this module will only work with version 1.x of
332 Berkeley DB. Once Berkeley DB version 2 is released, B<DB_File> will be
333 upgraded to work with it.
335 Berkeley DB is a C library which provides a consistent interface to a
336 number of database formats. B<DB_File> provides an interface to all
337 three of the database types currently supported by Berkeley DB.
345 This database type allows arbitrary key/value pairs to be stored in data
346 files. This is equivalent to the functionality provided by other
347 hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
348 the files created using DB_HASH are not compatible with any of the
349 other packages mentioned.
351 A default hashing algorithm, which will be adequate for most
352 applications, is built into Berkeley DB. If you do need to use your own
353 hashing algorithm it is possible to write your own in Perl and have
354 B<DB_File> use it instead.
358 The btree format allows arbitrary key/value pairs to be stored in a
359 sorted, balanced binary tree.
361 As with the DB_HASH format, it is possible to provide a user defined
362 Perl routine to perform the comparison of keys. By default, though, the
363 keys are stored in lexical order.
367 DB_RECNO allows both fixed-length and variable-length flat text files
368 to be manipulated using the same key/value pair interface as in DB_HASH
369 and DB_BTREE. In this case the key will consist of a record (line)
374 =head2 Interface to Berkeley DB
376 B<DB_File> allows access to Berkeley DB files using the tie() mechanism
377 in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
378 allows B<DB_File> to access Berkeley DB files using either an
379 associative array (for DB_HASH & DB_BTREE file types) or an ordinary
380 array (for the DB_RECNO file type).
382 In addition to the tie() interface, it is also possible to access most
383 of the functions provided in the Berkeley DB API directly.
384 See L<THE API INTERFACE>.
386 =head2 Opening a Berkeley DB Database File
388 Berkeley DB uses the function dbopen() to open or create a database.
389 Here is the C prototype for dbopen():
392 dbopen (const char * file, int flags, int mode,
393 DBTYPE type, const void * openinfo)
395 The parameter C<type> is an enumeration which specifies which of the 3
396 interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
397 Depending on which of these is actually chosen, the final parameter,
398 I<openinfo> points to a data structure which allows tailoring of the
399 specific interface method.
401 This interface is handled slightly differently in B<DB_File>. Here is
402 an equivalent call using B<DB_File>:
404 tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
406 The C<filename>, C<flags> and C<mode> parameters are the direct
407 equivalent of their dbopen() counterparts. The final parameter $DB_HASH
408 performs the function of both the C<type> and C<openinfo> parameters in
411 In the example above $DB_HASH is actually a pre-defined reference to a
412 hash object. B<DB_File> has three of these pre-defined references.
413 Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
415 The keys allowed in each of these pre-defined references is limited to
416 the names used in the equivalent C structure. So, for example, the
417 $DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
418 C<ffactor>, C<hash>, C<lorder> and C<nelem>.
420 To change one of these elements, just assign to it like this:
422 $DB_HASH->{'cachesize'} = 10000 ;
424 The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
425 usually adequate for most applications. If you do need to create extra
426 instances of these objects, constructors are available for each file
429 Here are examples of the constructors and the valid options available
430 for DB_HASH, DB_BTREE and DB_RECNO respectively.
432 $a = new DB_File::HASHINFO ;
440 $b = new DB_File::BTREEINFO ;
450 $c = new DB_File::RECNOINFO ;
459 The values stored in the hashes above are mostly the direct equivalent
460 of their C counterpart. Like their C counterparts, all are set to a
461 default values - that means you don't have to set I<all> of the
462 values when you only want to change one. Here is an example:
464 $a = new DB_File::HASHINFO ;
465 $a->{'cachesize'} = 12345 ;
466 tie %y, 'DB_File', "filename", $flags, 0777, $a ;
468 A few of the options need extra discussion here. When used, the C
469 equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
470 to C functions. In B<DB_File> these keys are used to store references
471 to Perl subs. Below are templates for each of the subs:
477 # return the hash value for $data
483 my ($key, $key2) = @_ ;
485 # return 0 if $key1 eq $key2
486 # -1 if $key1 lt $key2
487 # 1 if $key1 gt $key2
488 return (-1 , 0 or 1) ;
493 my ($key, $key2) = @_ ;
495 # return number of bytes of $key2 which are
496 # necessary to determine that it is greater than $key1
500 See L<Changing the BTREE sort order> for an example of using the
503 If you are using the DB_RECNO interface and you intend making use of
504 C<bval>, you should check out L<The 'bval' Option>.
506 =head2 Default Parameters
508 It is possible to omit some or all of the final 4 parameters in the
509 call to C<tie> and let them take default values. As DB_HASH is the most
510 common file format used, the call:
512 tie %A, "DB_File", "filename" ;
516 tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
518 It is also possible to omit the filename parameter as well, so the
525 tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
527 See L<In Memory Databases> for a discussion on the use of C<undef>
528 in place of a filename.
530 =head2 In Memory Databases
532 Berkeley DB allows the creation of in-memory databases by using NULL
533 (that is, a C<(char *)0> in C) in place of the filename. B<DB_File>
534 uses C<undef> instead of NULL to provide this functionality.
538 The DB_HASH file format is probably the most commonly used of the three
539 file formats that B<DB_File> supports. It is also very straightforward
542 =head2 A Simple Example
544 This example shows how to create a database, add key/value pairs to the
545 database, delete keys/value pairs and finally how to enumerate the
546 contents of the database.
550 use vars qw( %h $k $v ) ;
552 tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0640, $DB_HASH
553 or die "Cannot open file 'fruit': $!\n";
555 # Add a few key/value pairs to the file
556 $h{"apple"} = "red" ;
557 $h{"orange"} = "orange" ;
558 $h{"banana"} = "yellow" ;
559 $h{"tomato"} = "red" ;
561 # Check for existence of a key
562 print "Banana Exists\n\n" if $h{"banana"} ;
564 # Delete a key/value pair.
567 # print the contents of the file
568 while (($k, $v) = each %h)
569 { print "$k -> $v\n" }
581 Note that the like ordinary associative arrays, the order of the keys
582 retrieved is in an apparently random order.
586 The DB_BTREE format is useful when you want to store data in a given
587 order. By default the keys will be stored in lexical order, but as you
588 will see from the example shown in the next section, it is very easy to
589 define your own sorting function.
591 =head2 Changing the BTREE sort order
593 This script shows how to override the default sorting algorithm that
594 BTREE uses. Instead of using the normal lexical ordering, a case
595 insensitive compare function will be used.
604 my ($key1, $key2) = @_ ;
605 "\L$key1" cmp "\L$key2" ;
608 # specify the Perl sub that will do the comparison
609 $DB_BTREE->{'compare'} = \&Compare ;
611 tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE
612 or die "Cannot open file 'tree': $!\n" ;
614 # Add a key/value pair to the file
615 $h{'Wall'} = 'Larry' ;
616 $h{'Smith'} = 'John' ;
617 $h{'mouse'} = 'mickey' ;
618 $h{'duck'} = 'donald' ;
623 # Cycle through the keys printing them in order.
624 # Note it is not necessary to sort the keys as
625 # the btree will have kept them in order automatically.
631 Here is the output from the code above.
637 There are a few point to bear in mind if you want to change the
638 ordering in a BTREE database:
644 The new compare function must be specified when you create the database.
648 You cannot change the ordering once the database has been created. Thus
649 you must use the same compare function every time you access the
654 =head2 Handling Duplicate Keys
656 The BTREE file type optionally allows a single key to be associated
657 with an arbitrary number of values. This option is enabled by setting
658 the flags element of C<$DB_BTREE> to R_DUP when creating the database.
660 There are some difficulties in using the tied hash interface if you
661 want to manipulate a BTREE database with duplicate keys. Consider this
667 use vars qw($filename %h ) ;
672 # Enable duplicate records
673 $DB_BTREE->{'flags'} = R_DUP ;
675 tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
676 or die "Cannot open $filename: $!\n";
678 # Add some key/value pairs to the file
679 $h{'Wall'} = 'Larry' ;
680 $h{'Wall'} = 'Brick' ; # Note the duplicate key
681 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
682 $h{'Smith'} = 'John' ;
683 $h{'mouse'} = 'mickey' ;
685 # iterate through the associative array
686 # and print each key/value pair.
688 { print "$_ -> $h{$_}\n" }
700 As you can see 3 records have been successfully created with key C<Wall>
701 - the only thing is, when they are retrieved from the database they
702 I<seem> to have the same value, namely C<Larry>. The problem is caused
703 by the way that the associative array interface works. Basically, when
704 the associative array interface is used to fetch the value associated
705 with a given key, it will only ever retrieve the first value.
707 Although it may not be immediately obvious from the code above, the
708 associative array interface can be used to write values with duplicate
709 keys, but it cannot be used to read them back from the database.
711 The way to get around this problem is to use the Berkeley DB API method
712 called C<seq>. This method allows sequential access to key/value
713 pairs. See L<THE API INTERFACE> for details of both the C<seq> method
714 and the API in general.
716 Here is the script above rewritten using the C<seq> API method.
721 use vars qw($filename $x %h $status $key $value) ;
726 # Enable duplicate records
727 $DB_BTREE->{'flags'} = R_DUP ;
729 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
730 or die "Cannot open $filename: $!\n";
732 # Add some key/value pairs to the file
733 $h{'Wall'} = 'Larry' ;
734 $h{'Wall'} = 'Brick' ; # Note the duplicate key
735 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
736 $h{'Smith'} = 'John' ;
737 $h{'mouse'} = 'mickey' ;
739 # iterate through the btree using seq
740 # and print each key/value pair.
742 for ($status = $x->seq($key, $value, R_FIRST) ;
744 $status = $x->seq($key, $value, R_NEXT) )
745 { print "$key -> $value\n" }
758 This time we have got all the key/value pairs, including the multiple
759 values associated with the key C<Wall>.
761 =head2 The get_dup() Method
763 B<DB_File> comes with a utility method, called C<get_dup>, to assist in
764 reading duplicate values from BTREE databases. The method can take the
767 $count = $x->get_dup($key) ;
768 @list = $x->get_dup($key) ;
769 %list = $x->get_dup($key, 1) ;
771 In a scalar context the method returns the number of values associated
772 with the key, C<$key>.
774 In list context, it returns all the values which match C<$key>. Note
775 that the values will be returned in an apparently random order.
777 In list context, if the second parameter is present and evaluates
778 TRUE, the method returns an associative array. The keys of the
779 associative array correspond to the values that matched in the BTREE
780 and the values of the array are a count of the number of times that
781 particular value occurred in the BTREE.
783 So assuming the database created above, we can use C<get_dup> like
786 my $cnt = $x->get_dup("Wall") ;
787 print "Wall occurred $cnt times\n" ;
789 my %hash = $x->get_dup("Wall", 1) ;
790 print "Larry is there\n" if $hash{'Larry'} ;
791 print "There are $hash{'Brick'} Brick Walls\n" ;
793 my @list = $x->get_dup("Wall") ;
794 print "Wall => [@list]\n" ;
796 @list = $x->get_dup("Smith") ;
797 print "Smith => [@list]\n" ;
799 @list = $x->get_dup("Dog") ;
800 print "Dog => [@list]\n" ;
805 Wall occurred 3 times
807 There are 2 Brick Walls
808 Wall => [Brick Brick Larry]
812 =head2 Matching Partial Keys
814 The BTREE interface has a feature which allows partial keys to be
815 matched. This functionality is I<only> available when the C<seq> method
816 is used along with the R_CURSOR flag.
818 $x->seq($key, $value, R_CURSOR) ;
820 Here is the relevant quote from the dbopen man page where it defines
821 the use of the R_CURSOR flag with seq:
823 Note, for the DB_BTREE access method, the returned key is not
824 necessarily an exact match for the specified key. The returned key
825 is the smallest key greater than or equal to the specified key,
826 permitting partial key matches and range searches.
828 In the example script below, the C<match> sub uses this feature to find
829 and print the first matching key/value pair given a partial key.
835 use vars qw($filename $x %h $st $key $value) ;
841 my $orig_key = $key ;
842 $x->seq($key, $value, R_CURSOR) ;
843 print "$orig_key\t-> $key\t-> $value\n" ;
849 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
850 or die "Cannot open $filename: $!\n";
852 # Add some key/value pairs to the file
853 $h{'mouse'} = 'mickey' ;
854 $h{'Wall'} = 'Larry' ;
855 $h{'Walls'} = 'Brick' ;
856 $h{'Smith'} = 'John' ;
861 for ($st = $x->seq($key, $value, R_FIRST) ;
863 $st = $x->seq($key, $value, R_NEXT) )
865 { print "$key -> $value\n" }
867 print "\nPARTIAL MATCH\n" ;
891 DB_RECNO provides an interface to flat text files. Both variable and
892 fixed length records are supported.
894 In order to make RECNO more compatible with Perl the array offset for
895 all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
897 As with normal Perl arrays, a RECNO array can be accessed using
898 negative indexes. The index -1 refers to the last element of the array,
899 -2 the second last, and so on. Attempting to access an element before
900 the start of the array will raise a fatal run-time error.
902 =head2 The 'bval' Option
904 The operation of the bval option warrants some discussion. Here is the
905 definition of bval from the Berkeley DB 1.85 recno manual page:
907 The delimiting byte to be used to mark the end of a
908 record for variable-length records, and the pad charac-
909 ter for fixed-length records. If no value is speci-
910 fied, newlines (``\n'') are used to mark the end of
911 variable-length records and fixed-length records are
914 The second sentence is wrong. In actual fact bval will only default to
915 C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
916 openinfo parameter is used at all, the value that happens to be in bval
917 will be used. That means you always have to specify bval when making
918 use of any of the options in the openinfo parameter. This documentation
919 error will be fixed in the next release of Berkeley DB.
921 That clarifies the situation with regards Berkeley DB itself. What
922 about B<DB_File>? Well, the behavior defined in the quote above is
923 quite useful, so B<DB_File> conforms it.
925 That means that you can specify other options (e.g. cachesize) and
926 still have bval default to C<"\n"> for variable length records, and
927 space for fixed length records.
929 =head2 A Simple Example
931 Here is a simple example that uses RECNO.
937 tie @h, "DB_File", "text", O_RDWR|O_CREAT, 0640, $DB_RECNO
938 or die "Cannot open file 'text': $!\n" ;
940 # Add a few key/value pairs to the file
945 # Check for existence of a key
946 print "Element 1 Exists with value $h[1]\n" if $h[1] ;
948 # use a negative index
949 print "The last element is $h[-1]\n" ;
950 print "The 2nd last element is $h[-2]\n" ;
954 Here is the output from the script:
957 Element 1 Exists with value blue
958 The last element is yellow
959 The 2nd last element is blue
963 As you can see from the example above, the tied array interface is
964 quite limited. To make the interface more useful, a number of methods
965 are supplied with B<DB_File> to simulate the standard array operations
966 that are not currently implemented in Perl's tied array interface. All
967 these methods are accessed via the object returned from the tie call.
969 Here are the methods:
973 =item B<$X-E<gt>push(list) ;>
975 Pushes the elements of C<list> to the end of the array.
977 =item B<$value = $X-E<gt>pop ;>
979 Removes and returns the last element of the array.
981 =item B<$X-E<gt>shift>
983 Removes and returns the first element of the array.
985 =item B<$X-E<gt>unshift(list) ;>
987 Pushes the elements of C<list> to the start of the array.
989 =item B<$X-E<gt>length>
991 Returns the number of elements in the array.
995 =head2 Another Example
997 Here is a more complete example that makes use of some of the methods
998 described above. It also makes use of the API interface directly (see
999 L<THE API INTERFACE>).
1002 use vars qw(@h $H $file $i) ;
1010 $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0640, $DB_RECNO
1011 or die "Cannot open file $file: $!\n" ;
1013 # first create a text file to play with
1021 # Print the records in order.
1023 # The length method is needed here because evaluating a tied
1024 # array in a scalar context does not return the number of
1025 # elements in the array.
1027 print "\nORIGINAL\n" ;
1028 foreach $i (0 .. $H->length - 1) {
1029 print "$i: $h[$i]\n" ;
1032 # use the push & pop methods
1035 print "\nThe last record was [$a]\n" ;
1037 # and the shift & unshift methods
1039 $H->unshift("first") ;
1040 print "The first record was [$a]\n" ;
1042 # Use the API to add a new record after record 2.
1044 $H->put($i, "Newbie", R_IAFTER) ;
1046 # and a new record before record 1.
1048 $H->put($i, "New One", R_IBEFORE) ;
1053 # now print the records in reverse order
1054 print "\nREVERSE\n" ;
1055 for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
1056 { print "$i: $h[$i]\n" }
1058 # same again, but use the API functions instead
1059 print "\nREVERSE again\n" ;
1060 my ($s, $k, $v) = (0, 0, 0) ;
1061 for ($s = $H->seq($k, $v, R_LAST) ;
1063 $s = $H->seq($k, $v, R_PREV))
1064 { print "$k: $v\n" }
1069 and this is what it outputs:
1078 The last record was [four]
1079 The first record was [zero]
1103 Rather than iterating through the array, C<@h> like this:
1107 it is necessary to use either this:
1109 foreach $i (0 .. $H->length - 1)
1113 for ($a = $H->get($k, $v, R_FIRST) ;
1115 $a = $H->get($k, $v, R_NEXT) )
1119 Notice that both times the C<put> method was used the record index was
1120 specified using a variable, C<$i>, rather than the literal value
1121 itself. This is because C<put> will return the record number of the
1122 inserted line via that parameter.
1126 =head1 THE API INTERFACE
1128 As well as accessing Berkeley DB using a tied hash or array, it is also
1129 possible to make direct use of most of the API functions defined in the
1130 Berkeley DB documentation.
1132 To do this you need to store a copy of the object returned from the tie.
1134 $db = tie %hash, "DB_File", "filename" ;
1136 Once you have done that, you can access the Berkeley DB API functions
1137 as B<DB_File> methods directly like this:
1139 $db->put($key, $value, R_NOOVERWRITE) ;
1141 B<Important:> If you have saved a copy of the object returned from
1142 C<tie>, the underlying database file will I<not> be closed until both
1143 the tied variable is untied and all copies of the saved object are
1147 $db = tie %hash, "DB_File", "filename"
1148 or die "Cannot tie filename: $!" ;
1153 See L<The untie() Gotcha> for more details.
1155 All the functions defined in L<dbopen> are available except for
1156 close() and dbopen() itself. The B<DB_File> method interface to the
1157 supported functions have been implemented to mirror the way Berkeley DB
1158 works whenever possible. In particular note that:
1164 The methods return a status value. All return 0 on success.
1165 All return -1 to signify an error and set C<$!> to the exact
1166 error code. The return code 1 generally (but not always) means that the
1167 key specified did not exist in the database.
1169 Other return codes are defined. See below and in the Berkeley DB
1170 documentation for details. The Berkeley DB documentation should be used
1171 as the definitive source.
1175 Whenever a Berkeley DB function returns data via one of its parameters,
1176 the equivalent B<DB_File> method does exactly the same.
1180 If you are careful, it is possible to mix API calls with the tied
1181 hash/array interface in the same piece of code. Although only a few of
1182 the methods used to implement the tied interface currently make use of
1183 the cursor, you should always assume that the cursor has been changed
1184 any time the tied hash/array interface is used. As an example, this
1185 code will probably not do what you expect:
1187 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1188 or die "Cannot tie $filename: $!" ;
1190 # Get the first key/value pair and set the cursor
1191 $X->seq($key, $value, R_FIRST) ;
1193 # this line will modify the cursor
1194 $count = scalar keys %x ;
1196 # Get the second key/value pair.
1197 # oops, it didn't, it got the last key/value pair!
1198 $X->seq($key, $value, R_NEXT) ;
1200 The code above can be rearranged to get around the problem, like this:
1202 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1203 or die "Cannot tie $filename: $!" ;
1205 # this line will modify the cursor
1206 $count = scalar keys %x ;
1208 # Get the first key/value pair and set the cursor
1209 $X->seq($key, $value, R_FIRST) ;
1211 # Get the second key/value pair.
1213 $X->seq($key, $value, R_NEXT) ;
1217 All the constants defined in L<dbopen> for use in the flags parameters
1218 in the methods defined below are also available. Refer to the Berkeley
1219 DB documentation for the precise meaning of the flags values.
1221 Below is a list of the methods available.
1225 =item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
1227 Given a key (C<$key>) this method reads the value associated with it
1228 from the database. The value read from the database is returned in the
1229 C<$value> parameter.
1231 If the key does not exist the method returns 1.
1233 No flags are currently defined for this method.
1235 =item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
1237 Stores the key/value pair in the database.
1239 If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
1240 will have the record number of the inserted key/value pair set.
1242 Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1245 =item B<$status = $X-E<gt>del($key [, $flags]) ;>
1247 Removes all key/value pairs with key C<$key> from the database.
1249 A return code of 1 means that the requested key was not in the
1252 R_CURSOR is the only valid flag at present.
1254 =item B<$status = $X-E<gt>fd ;>
1256 Returns the file descriptor for the underlying database.
1258 See L<Locking Databases> for an example of how to make use of the
1259 C<fd> method to lock your database.
1261 =item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
1263 This interface allows sequential retrieval from the database. See
1264 L<dbopen> for full details.
1266 Both the C<$key> and C<$value> parameters will be set to the key/value
1267 pair read from the database.
1269 The flags parameter is mandatory. The valid flag values are R_CURSOR,
1270 R_FIRST, R_LAST, R_NEXT and R_PREV.
1272 =item B<$status = $X-E<gt>sync([$flags]) ;>
1274 Flushes any cached buffers to disk.
1276 R_RECNOSYNC is the only valid flag at present.
1280 =head1 HINTS AND TIPS
1283 =head2 Locking Databases
1285 Concurrent access of a read-write database by several parties requires
1286 them all to use some kind of locking. Here's an example of Tom's that
1287 uses the I<fd> method to get the file descriptor, and then a careful
1288 open() to give something Perl will flock() for you. Run this repeatedly
1289 in the background to watch the locks granted in proper order.
1300 my($oldval, $fd, $db, %db, $value, $key);
1302 $key = shift || 'default';
1303 $value = shift || 'magic';
1307 $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0644)
1308 || die "dbcreat /tmp/foo.db $!";
1310 print "$$: db fd is $fd\n";
1311 open(DB_FH, "+<&=$fd") || die "dup $!";
1314 unless (flock (DB_FH, LOCK_SH | LOCK_NB)) {
1315 print "$$: CONTENTION; can't read during write update!
1316 Waiting for read lock ($!) ....";
1317 unless (flock (DB_FH, LOCK_SH)) { die "flock: $!" }
1319 print "$$: Read lock granted\n";
1321 $oldval = $db{$key};
1322 print "$$: Old value was $oldval\n";
1323 flock(DB_FH, LOCK_UN);
1325 unless (flock (DB_FH, LOCK_EX | LOCK_NB)) {
1326 print "$$: CONTENTION; must have exclusive lock!
1327 Waiting for write lock ($!) ....";
1328 unless (flock (DB_FH, LOCK_EX)) { die "flock: $!" }
1331 print "$$: Write lock granted\n";
1333 $db->sync; # to flush
1336 flock(DB_FH, LOCK_UN);
1340 print "$$: Updated db to $key=$value\n";
1342 =head2 Sharing Databases With C Applications
1344 There is no technical reason why a Berkeley DB database cannot be
1345 shared by both a Perl and a C application.
1347 The vast majority of problems that are reported in this area boil down
1348 to the fact that C strings are NULL terminated, whilst Perl strings are
1351 Here is a real example. Netscape 2.0 keeps a record of the locations you
1352 visit along with the time you last visited them in a DB_HASH database.
1353 This is usually stored in the file F<~/.netscape/history.db>. The key
1354 field in the database is the location string and the value field is the
1355 time the location was last visited stored as a 4 byte binary value.
1357 If you haven't already guessed, the location string is stored with a
1358 terminating NULL. This means you need to be careful when accessing the
1361 Here is a snippet of code that is loosely based on Tom Christiansen's
1362 I<ggh> script (available from your nearest CPAN archive in
1363 F<authors/id/TOMC/scripts/nshist.gz>).
1369 use vars qw( $dotdir $HISTORY %hist_db $href $binary_time $date ) ;
1370 $dotdir = $ENV{HOME} || $ENV{LOGNAME};
1372 $HISTORY = "$dotdir/.netscape/history.db";
1374 tie %hist_db, 'DB_File', $HISTORY
1375 or die "Cannot open $HISTORY: $!\n" ;;
1377 # Dump the complete database
1378 while ( ($href, $binary_time) = each %hist_db ) {
1380 # remove the terminating NULL
1381 $href =~ s/\x00$// ;
1383 # convert the binary time into a user friendly string
1384 $date = localtime unpack("V", $binary_time);
1385 print "$date $href\n" ;
1388 # check for the existence of a specific key
1389 # remember to add the NULL
1390 if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
1391 $date = localtime unpack("V", $binary_time) ;
1392 print "Last visited mox.perl.com on $date\n" ;
1395 print "Never visited mox.perl.com\n"
1400 =head2 The untie() Gotcha
1402 If you make use of the Berkeley DB API, it is I<very> strongly
1403 recommended that you read L<perltie/The untie Gotcha>.
1405 Even if you don't currently make use of the API interface, it is still
1408 Here is an example which illustrates the problem from a B<DB_File>
1417 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
1418 or die "Cannot tie first time: $!" ;
1424 tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1425 or die "Cannot tie second time: $!" ;
1429 When run, the script will produce this error message:
1431 Cannot tie second time: Invalid argument at bad.file line 14.
1433 Although the error message above refers to the second tie() statement
1434 in the script, the source of the problem is really with the untie()
1435 statement that precedes it.
1437 Having read L<perltie> you will probably have already guessed that the
1438 error is caused by the extra copy of the tied object stored in C<$X>.
1439 If you haven't, then the problem boils down to the fact that the
1440 B<DB_File> destructor, DESTROY, will not be called until I<all>
1441 references to the tied object are destroyed. Both the tied variable,
1442 C<%x>, and C<$X> above hold a reference to the object. The call to
1443 untie() will destroy the first, but C<$X> still holds a valid
1444 reference, so the destructor will not get called and the database file
1445 F<tst.fil> will remain open. The fact that Berkeley DB then reports the
1446 attempt to open a database that is alreday open via the catch-all
1447 "Invalid argument" doesn't help.
1449 If you run the script with the C<-w> flag the error message becomes:
1451 untie attempted while 1 inner references still exist at bad.file line 12.
1452 Cannot tie second time: Invalid argument at bad.file line 14.
1454 which pinpoints the real problem. Finally the script can now be
1455 modified to fix the original problem by destroying the API object
1464 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1468 =head1 COMMON QUESTIONS
1470 =head2 Why is there Perl source in my database?
1472 If you look at the contents of a database file created by DB_File,
1473 there can sometimes be part of a Perl script included in it.
1475 This happens because Berkeley DB uses dynamic memory to allocate
1476 buffers which will subsequently be written to the database file. Being
1477 dynamic, the memory could have been used for anything before DB
1478 malloced it. As Berkeley DB doesn't clear the memory once it has been
1479 allocated, the unused portions will contain random junk. In the case
1480 where a Perl script gets written to the database, the random junk will
1481 correspond to an area of dynamic memory that happened to be used during
1482 the compilation of the script.
1484 Unless you don't like the possibility of there being part of your Perl
1485 scripts embedded in a database file, this is nothing to worry about.
1487 =head2 How do I store complex data structures with DB_File?
1489 Although B<DB_File> cannot do this directly, there is a module which
1490 can layer transparently over B<DB_File> to accomplish this feat.
1492 Check out the MLDBM module, available on CPAN in the directory
1493 F<modules/by-module/MLDBM>.
1495 =head2 What does "Invalid Argument" mean?
1497 You will get this error message when one of the parameters in the
1498 C<tie> call is wrong. Unfortunately there are quite a few parameters to
1499 get wrong, so it can be difficult to figure out which one it is.
1501 Here are a couple of possibilities:
1507 Attempting to reopen a database without closing it.
1511 Using the O_WRONLY flag.
1515 =head2 What does "Bareword 'DB_File' not allowed" mean?
1517 You will encounter this particular error message when you have the
1518 C<strict 'subs'> pragma (or the full strict pragma) in your script.
1519 Consider this script:
1524 tie %x, DB_File, "filename" ;
1526 Running it produces the error in question:
1528 Bareword "DB_File" not allowed while "strict subs" in use
1530 To get around the error, place the word C<DB_File> in either single or
1531 double quotes, like this:
1533 tie %x, "DB_File", "filename" ;
1535 Although it might seem like a real pain, it is really worth the effort
1536 of having a C<use strict> in all your scripts.
1548 When B<DB_File> is opening a database file it no longer terminates the
1549 process if I<dbopen> returned an error. This allows file protection
1550 errors to be caught at run time. Thanks to Judith Grass
1551 E<lt>grass@cybercash.comE<gt> for spotting the bug.
1555 Added prototype support for multiple btree compare callbacks.
1559 B<DB_File> has been in use for over a year. To reflect that, the
1560 version number has been incremented to 1.0.
1562 Added complete support for multiple concurrent callbacks.
1564 Using the I<push> method on an empty list didn't work properly. This
1569 Fixed a core dump problem with SunOS.
1571 The return value from TIEHASH wasn't set to NULL when dbopen returned
1576 Merged OS/2 specific code into DB_File.xs
1578 Removed some redundant code in DB_File.xs.
1580 Documentation update.
1582 Allow negative subscripts with RECNO interface.
1584 Changed the default flags from O_RDWR to O_CREAT|O_RDWR.
1586 The example code which showed how to lock a database needed a call to
1587 C<sync> added. Without it the resultant database file was empty.
1589 Added get_dup method.
1593 Documentation update.
1595 B<DB_File> now imports the constants (O_RDWR, O_CREAT etc.) from Fcntl
1598 The standard hash function C<exists> is now supported.
1600 Modified the behavior of get_dup. When it returns an associative
1601 array, the value is the count of the number of matching BTREE values.
1605 Minor documentation changes.
1607 Fixed a bug in hash_cb. Patches supplied by Dave Hammen,
1608 E<lt>hammen@gothamcity.jsc.nasa.govE<gt>.
1610 Fixed a bug with the constructors for DB_File::HASHINFO,
1611 DB_File::BTREEINFO and DB_File::RECNOINFO. Also tidied up the
1612 constructors to make them C<-w> clean.
1614 Reworked part of the test harness to be more locale friendly.
1618 Made all scripts in the documentation C<strict> and C<-w> clean.
1620 Added logic to F<DB_File.xs> to allow the module to be built after Perl
1625 Minor namespace cleanup: Localized C<PrintBtree>.
1629 Fixed bug with RECNO, where bval wasn't defaulting to "\n".
1633 Documented operation of bval.
1637 Minor bug fix in DB_File::HASHINFO, DB_File::RECNOINFO and
1640 Changed default mode to 0666.
1644 Fixed fd method so that it still returns -1 for in-memory files when db
1649 Documented the untie gotcha.
1653 Documented the incompatibility with version 2 of Berkeley DB.
1657 Minor changes to DB_FIle.xs and DB_File.pm
1661 Made it illegal to tie an associative array to a RECNO database and an
1662 ordinary array to a HASH or BTREE database.
1666 Patch from Gisle Aas <gisle@aas.no> to suppress "use of undefined
1667 value" warning with db_get and db_seq.
1669 Patch from Gisle Aas <gisle@aas.no> to make DB_File export only the O_*
1670 constants from Fcntl.
1672 Removed the DESTROY method from the DB_File::HASHINFO module.
1674 Previously DB_File hard-wired the class name of any object that it
1675 created to "DB_File". This makes sub-classing difficult. Now DB_File
1676 creats objects in the namespace of the package it has been inherited
1681 Minor changes to DB_File.xs to support multithreaded perl.
1687 Some older versions of Berkeley DB had problems with fixed length
1688 records using the RECNO file format. The newest version at the time of
1689 writing was 1.85 - this seems to have fixed the problems with RECNO.
1691 I am sure there are bugs in the code. If you do find any, or can
1692 suggest any enhancements, I would welcome your comments.
1696 B<DB_File> comes with the standard Perl source distribution. Look in
1697 the directory F<ext/DB_File>.
1699 This version of B<DB_File> will only work with version 1.x of Berkeley
1700 DB. It is I<not> yet compatible with version 2.
1702 Version 1 of Berkeley DB is available at your nearest CPAN archive (see
1703 L<perlmod/"CPAN"> for a list) in F<src/misc/db.1.85.tar.gz>, or via the
1704 host F<ftp.cs.berkeley.edu> in F</ucb/4bsd/db.tar.gz>. Alternatively,
1705 check out the Berkeley DB home page at F<http://www.bostic.com/db>. It
1706 is I<not> under the GPL.
1708 If you are running IRIX, then get Berkeley DB from
1709 F<http://reality.sgi.com/ariel>. It has the patches necessary to
1710 compile properly on IRIX 5.3.
1712 As of January 1997, version 1.86 of Berkeley DB is available from the
1713 Berkeley DB home page. Although this release does fix a number of bugs
1714 that were present in 1.85 you should be aware of the following
1715 information (taken from the Berkeley DB home page) before you consider
1718 DB version 1.86 includes a new implementation of the hash access
1719 method that fixes a variety of hashing problems found in DB version
1720 1.85. We are making it available as an interim solution until DB
1723 PLEASE NOTE: the underlying file format for the hash access method
1724 changed between version 1.85 and version 1.86, so you will have to
1725 dump and reload all of your databases to convert from version 1.85
1726 to version 1.86. If you do not absolutely require the fixes from
1727 version 1.86, we strongly urge you to wait until DB 2.0 is released
1728 before upgrading from 1.85.
1733 L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>
1737 The DB_File interface was written by Paul Marquess
1738 E<lt>pmarquess@bfsec.bt.co.ukE<gt>.
1739 Questions about the DB system itself may be addressed to
1740 E<lt>db@sleepycat.com<gt>.