1 # DB_File.pm -- Perl 5 interface to Berkeley DB
3 # written by Paul Marquess (pmarquess@bfsec.bt.co.uk)
4 # last modified 6th Feb 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 DESTROY { undef %{$_[0]} }
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 ;
110 @DB_File::RECNOINFO::ISA = qw(DB_File::HASHINFO) ;
116 bless { VALID => { map {$_, 1}
117 qw( bval cachesize psize flags lorder reclen bfname )
123 package DB_File::BTREEINFO ;
127 @DB_File::BTREEINFO::ISA = qw(DB_File::HASHINFO) ;
133 bless { VALID => { map {$_, 1}
134 qw( flags cachesize maxkeypage minkeypage psize
135 compare prefix lorder )
145 use vars qw($VERSION @ISA @EXPORT $AUTOLOAD $DB_BTREE $DB_HASH $DB_RECNO) ;
151 #typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
152 $DB_BTREE = new DB_File::BTREEINFO ;
153 $DB_HASH = new DB_File::HASHINFO ;
154 $DB_RECNO = new DB_File::RECNOINFO ;
160 @ISA = qw(Tie::Hash Exporter DynaLoader);
162 $DB_BTREE $DB_HASH $DB_RECNO
197 ($constname = $AUTOLOAD) =~ s/.*:://;
198 my $val = constant($constname, @_ ? $_[0] : 0);
200 if ($! =~ /Invalid/) {
201 $AutoLoader::AUTOLOAD = $AUTOLOAD;
202 goto &AutoLoader::AUTOLOAD;
205 my($pack,$file,$line) = caller;
206 croak "Your vendor has not defined DB macro $constname, used at $file line $line.
210 eval "sub $AUTOLOAD { $val }";
215 # import borrowed from IO::File
216 # exports Fcntl constants if available.
219 my $callpkg = caller;
220 Exporter::export $pkg, $callpkg, @_;
223 Exporter::export 'Fcntl', $callpkg, '/^O_/';
227 bootstrap DB_File $VERSION;
229 # Preloaded methods go here. Autoload methods go after __END__, and are
230 # processed by the autosplit program.
236 $arg[4] = tied %{ $arg[4] }
237 if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
242 *TIEARRAY = \&TIEHASH ;
246 croak "Usage: \$db->get_dup(key [,flag])\n"
247 unless @_ == 2 or @_ == 3 ;
254 my $wantarray = wantarray ;
260 # iterate through the database until either EOF ($status == 0)
261 # or a different key is encountered ($key ne $origkey).
262 for ($status = $db->seq($key, $value, R_CURSOR()) ;
263 $status == 0 and $key eq $origkey ;
264 $status = $db->seq($key, $value, R_NEXT()) ) {
266 # save the value or count number of matches
269 { ++ $values{$value} }
271 { push (@values, $value) }
278 return ($wantarray ? ($flag ? %values : @values) : $counter) ;
289 DB_File - Perl5 access to Berkeley DB
295 [$X =] tie %hash, 'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
296 [$X =] tie %hash, 'DB_File', $filename, $flags, $mode, $DB_BTREE ;
297 [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;
299 $status = $X->del($key [, $flags]) ;
300 $status = $X->put($key, $value [, $flags]) ;
301 $status = $X->get($key, $value [, $flags]) ;
302 $status = $X->seq($key, $value, $flags) ;
303 $status = $X->sync([$flags]) ;
307 $count = $X->get_dup($key) ;
308 @list = $X->get_dup($key) ;
309 %list = $X->get_dup($key, 1) ;
323 B<DB_File> is a module which allows Perl programs to make use of the
324 facilities provided by Berkeley DB. If you intend to use this
325 module you should really have a copy of the Berkeley DB manual pages at
326 hand. The interface defined here mirrors the Berkeley DB interface
329 Berkeley DB is a C library which provides a consistent interface to a
330 number of database formats. B<DB_File> provides an interface to all
331 three of the database types currently supported by Berkeley DB.
339 This database type allows arbitrary key/value pairs to be stored in data
340 files. This is equivalent to the functionality provided by other
341 hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
342 the files created using DB_HASH are not compatible with any of the
343 other packages mentioned.
345 A default hashing algorithm, which will be adequate for most
346 applications, is built into Berkeley DB. If you do need to use your own
347 hashing algorithm it is possible to write your own in Perl and have
348 B<DB_File> use it instead.
352 The btree format allows arbitrary key/value pairs to be stored in a
353 sorted, balanced binary tree.
355 As with the DB_HASH format, it is possible to provide a user defined
356 Perl routine to perform the comparison of keys. By default, though, the
357 keys are stored in lexical order.
361 DB_RECNO allows both fixed-length and variable-length flat text files
362 to be manipulated using the same key/value pair interface as in DB_HASH
363 and DB_BTREE. In this case the key will consist of a record (line)
368 =head2 How does DB_File interface to Berkeley DB?
370 B<DB_File> allows access to Berkeley DB files using the tie() mechanism
371 in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
372 allows B<DB_File> to access Berkeley DB files using either an
373 associative array (for DB_HASH & DB_BTREE file types) or an ordinary
374 array (for the DB_RECNO file type).
376 In addition to the tie() interface, it is also possible to access most
377 of the functions provided in the Berkeley DB API directly.
378 See L<THE API INTERFACE>.
380 =head2 Opening a Berkeley DB Database File
382 Berkeley DB uses the function dbopen() to open or create a database.
383 Here is the C prototype for dbopen():
386 dbopen (const char * file, int flags, int mode,
387 DBTYPE type, const void * openinfo)
389 The parameter C<type> is an enumeration which specifies which of the 3
390 interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
391 Depending on which of these is actually chosen, the final parameter,
392 I<openinfo> points to a data structure which allows tailoring of the
393 specific interface method.
395 This interface is handled slightly differently in B<DB_File>. Here is
396 an equivalent call using B<DB_File>:
398 tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
400 The C<filename>, C<flags> and C<mode> parameters are the direct
401 equivalent of their dbopen() counterparts. The final parameter $DB_HASH
402 performs the function of both the C<type> and C<openinfo> parameters in
405 In the example above $DB_HASH is actually a pre-defined reference to a
406 hash object. B<DB_File> has three of these pre-defined references.
407 Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
409 The keys allowed in each of these pre-defined references is limited to
410 the names used in the equivalent C structure. So, for example, the
411 $DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
412 C<ffactor>, C<hash>, C<lorder> and C<nelem>.
414 To change one of these elements, just assign to it like this:
416 $DB_HASH->{'cachesize'} = 10000 ;
418 The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
419 usually adequate for most applications. If you do need to create extra
420 instances of these objects, constructors are available for each file
423 Here are examples of the constructors and the valid options available
424 for DB_HASH, DB_BTREE and DB_RECNO respectively.
426 $a = new DB_File::HASHINFO ;
434 $b = new DB_File::BTREEINFO ;
444 $c = new DB_File::RECNOINFO ;
453 The values stored in the hashes above are mostly the direct equivalent
454 of their C counterpart. Like their C counterparts, all are set to a
455 default values - that means you don't have to set I<all> of the
456 values when you only want to change one. Here is an example:
458 $a = new DB_File::HASHINFO ;
459 $a->{'cachesize'} = 12345 ;
460 tie %y, 'DB_File', "filename", $flags, 0777, $a ;
462 A few of the options need extra discussion here. When used, the C
463 equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
464 to C functions. In B<DB_File> these keys are used to store references
465 to Perl subs. Below are templates for each of the subs:
471 # return the hash value for $data
477 my ($key, $key2) = @_ ;
479 # return 0 if $key1 eq $key2
480 # -1 if $key1 lt $key2
481 # 1 if $key1 gt $key2
482 return (-1 , 0 or 1) ;
487 my ($key, $key2) = @_ ;
489 # return number of bytes of $key2 which are
490 # necessary to determine that it is greater than $key1
494 See L<Changing the BTREE sort order> for an example of using the
497 If you are using the DB_RECNO interface and you intend making use of
498 C<bval>, you should check out L<The bval option>.
500 =head2 Default Parameters
502 It is possible to omit some or all of the final 4 parameters in the
503 call to C<tie> and let them take default values. As DB_HASH is the most
504 common file format used, the call:
506 tie %A, "DB_File", "filename" ;
510 tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
512 It is also possible to omit the filename parameter as well, so the
519 tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
521 See L<In Memory Databases> for a discussion on the use of C<undef>
522 in place of a filename.
524 =head2 In Memory Databases
526 Berkeley DB allows the creation of in-memory databases by using NULL
527 (that is, a C<(char *)0> in C) in place of the filename. B<DB_File>
528 uses C<undef> instead of NULL to provide this functionality.
532 The DB_HASH file format is probably the most commonly used of the three
533 file formats that B<DB_File> supports. It is also very straightforward
536 =head2 A Simple Example.
538 This example shows how to create a database, add key/value pairs to the
539 database, delete keys/value pairs and finally how to enumerate the
540 contents of the database.
544 use vars qw( %h $k $v ) ;
546 tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0640, $DB_HASH
547 or die "Cannot open file 'fruit': $!\n";
549 # Add a few key/value pairs to the file
550 $h{"apple"} = "red" ;
551 $h{"orange"} = "orange" ;
552 $h{"banana"} = "yellow" ;
553 $h{"tomato"} = "red" ;
555 # Check for existence of a key
556 print "Banana Exists\n\n" if $h{"banana"} ;
558 # Delete a key/value pair.
561 # print the contents of the file
562 while (($k, $v) = each %h)
563 { print "$k -> $v\n" }
575 Note that the like ordinary associative arrays, the order of the keys
576 retrieved is in an apparently random order.
580 The DB_BTREE format is useful when you want to store data in a given
581 order. By default the keys will be stored in lexical order, but as you
582 will see from the example shown in the next section, it is very easy to
583 define your own sorting function.
585 =head2 Changing the BTREE sort order
587 This script shows how to override the default sorting algorithm that
588 BTREE uses. Instead of using the normal lexical ordering, a case
589 insensitive compare function will be used.
598 my ($key1, $key2) = @_ ;
599 "\L$key1" cmp "\L$key2" ;
602 # specify the Perl sub that will do the comparison
603 $DB_BTREE->{'compare'} = \&Compare ;
605 tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE
606 or die "Cannot open file 'tree': $!\n" ;
608 # Add a key/value pair to the file
609 $h{'Wall'} = 'Larry' ;
610 $h{'Smith'} = 'John' ;
611 $h{'mouse'} = 'mickey' ;
612 $h{'duck'} = 'donald' ;
617 # Cycle through the keys printing them in order.
618 # Note it is not necessary to sort the keys as
619 # the btree will have kept them in order automatically.
625 Here is the output from the code above.
631 There are a few point to bear in mind if you want to change the
632 ordering in a BTREE database:
638 The new compare function must be specified when you create the database.
642 You cannot change the ordering once the database has been created. Thus
643 you must use the same compare function every time you access the
648 =head2 Handling duplicate keys
650 The BTREE file type optionally allows a single key to be associated
651 with an arbitrary number of values. This option is enabled by setting
652 the flags element of C<$DB_BTREE> to R_DUP when creating the database.
654 There are some difficulties in using the tied hash interface if you
655 want to manipulate a BTREE database with duplicate keys. Consider this
661 use vars qw($filename %h ) ;
666 # Enable duplicate records
667 $DB_BTREE->{'flags'} = R_DUP ;
669 tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
670 or die "Cannot open $filename: $!\n";
672 # Add some key/value pairs to the file
673 $h{'Wall'} = 'Larry' ;
674 $h{'Wall'} = 'Brick' ; # Note the duplicate key
675 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
676 $h{'Smith'} = 'John' ;
677 $h{'mouse'} = 'mickey' ;
679 # iterate through the associative array
680 # and print each key/value pair.
682 { print "$_ -> $h{$_}\n" }
694 As you can see 3 records have been successfully created with key C<Wall>
695 - the only thing is, when they are retrieved from the database they
696 I<seem> to have the same value, namely C<Larry>. The problem is caused
697 by the way that the associative array interface works. Basically, when
698 the associative array interface is used to fetch the value associated
699 with a given key, it will only ever retrieve the first value.
701 Although it may not be immediately obvious from the code above, the
702 associative array interface can be used to write values with duplicate
703 keys, but it cannot be used to read them back from the database.
705 The way to get around this problem is to use the Berkeley DB API method
706 called C<seq>. This method allows sequential access to key/value
707 pairs. See L<THE API INTERFACE> for details of both the C<seq> method
708 and the API in general.
710 Here is the script above rewritten using the C<seq> API method.
715 use vars qw($filename $x %h $status $key $value) ;
720 # Enable duplicate records
721 $DB_BTREE->{'flags'} = R_DUP ;
723 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
724 or die "Cannot open $filename: $!\n";
726 # Add some key/value pairs to the file
727 $h{'Wall'} = 'Larry' ;
728 $h{'Wall'} = 'Brick' ; # Note the duplicate key
729 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
730 $h{'Smith'} = 'John' ;
731 $h{'mouse'} = 'mickey' ;
733 # iterate through the btree using seq
734 # and print each key/value pair.
736 for ($status = $x->seq($key, $value, R_FIRST) ;
738 $status = $x->seq($key, $value, R_NEXT) )
739 { print "$key -> $value\n" }
752 This time we have got all the key/value pairs, including the multiple
753 values associated with the key C<Wall>.
755 =head2 The get_dup method.
757 B<DB_File> comes with a utility method, called C<get_dup>, to assist in
758 reading duplicate values from BTREE databases. The method can take the
761 $count = $x->get_dup($key) ;
762 @list = $x->get_dup($key) ;
763 %list = $x->get_dup($key, 1) ;
765 In a scalar context the method returns the number of values associated
766 with the key, C<$key>.
768 In list context, it returns all the values which match C<$key>. Note
769 that the values will be returned in an apparently random order.
771 In list context, if the second parameter is present and evaluates TRUE,
772 the method returns an associative array. The keys of the associative
773 array correspond to the the values that matched in the BTREE and the
774 values of the array are a count of the number of times that particular
775 value occurred in the BTREE.
777 So assuming the database created above, we can use C<get_dup> like
780 my $cnt = $x->get_dup("Wall") ;
781 print "Wall occurred $cnt times\n" ;
783 my %hash = $x->get_dup("Wall", 1) ;
784 print "Larry is there\n" if $hash{'Larry'} ;
785 print "There are $hash{'Brick'} Brick Walls\n" ;
787 my @list = $x->get_dup("Wall") ;
788 print "Wall => [@list]\n" ;
790 @list = $x->get_dup("Smith") ;
791 print "Smith => [@list]\n" ;
793 @list = $x->get_dup("Dog") ;
794 print "Dog => [@list]\n" ;
799 Wall occurred 3 times
801 There are 2 Brick Walls
802 Wall => [Brick Brick Larry]
806 =head2 Matching Partial Keys
808 The BTREE interface has a feature which allows partial keys to be
809 matched. This functionality is I<only> available when the C<seq> method
810 is used along with the R_CURSOR flag.
812 $x->seq($key, $value, R_CURSOR) ;
814 Here is the relevant quote from the dbopen man page where it defines
815 the use of the R_CURSOR flag with seq:
817 Note, for the DB_BTREE access method, the returned key is not
818 necessarily an exact match for the specified key. The returned key
819 is the smallest key greater than or equal to the specified key,
820 permitting partial key matches and range searches.
822 In the example script below, the C<match> sub uses this feature to find
823 and print the first matching key/value pair given a partial key.
829 use vars qw($filename $x %h $st $key $value) ;
835 my $orig_key = $key ;
836 $x->seq($key, $value, R_CURSOR) ;
837 print "$orig_key\t-> $key\t-> $value\n" ;
843 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
844 or die "Cannot open $filename: $!\n";
846 # Add some key/value pairs to the file
847 $h{'mouse'} = 'mickey' ;
848 $h{'Wall'} = 'Larry' ;
849 $h{'Walls'} = 'Brick' ;
850 $h{'Smith'} = 'John' ;
855 for ($st = $x->seq($key, $value, R_FIRST) ;
857 $st = $x->seq($key, $value, R_NEXT) )
859 { print "$key -> $value\n" }
861 print "\nPARTIAL MATCH\n" ;
885 DB_RECNO provides an interface to flat text files. Both variable and
886 fixed length records are supported.
888 In order to make RECNO more compatible with Perl the array offset for
889 all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
891 As with normal Perl arrays, a RECNO array can be accessed using
892 negative indexes. The index -1 refers to the last element of the array,
893 -2 the second last, and so on. Attempting to access an element before
894 the start of the array will raise a fatal run-time error.
896 =head2 The bval option
898 The operation of the bval option warrants some discussion. Here is the
899 definition of bval from the Berkeley DB 1.85 recno manual page:
901 The delimiting byte to be used to mark the end of a
902 record for variable-length records, and the pad charac-
903 ter for fixed-length records. If no value is speci-
904 fied, newlines (``\n'') are used to mark the end of
905 variable-length records and fixed-length records are
908 The second sentence is wrong. In actual fact bval will only default to
909 C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
910 openinfo parameter is used at all, the value that happens to be in bval
911 will be used. That means you always have to specify bval when making
912 use of any of the options in the openinfo parameter. This documentation
913 error will be fixed in the next release of Berkeley DB.
915 That clarifies the situation with regards Berkeley DB itself. What
916 about B<DB_File>? Well, the behavior defined in the quote above is
917 quite useful, so B<DB_File> conforms it.
919 That means that you can specify other options (e.g. cachesize) and
920 still have bval default to C<"\n"> for variable length records, and
921 space for fixed length records.
923 =head2 A Simple Example
925 Here is a simple example that uses RECNO.
931 tie @h, "DB_File", "text", O_RDWR|O_CREAT, 0640, $DB_RECNO
932 or die "Cannot open file 'text': $!\n" ;
934 # Add a few key/value pairs to the file
939 # Check for existence of a key
940 print "Element 1 Exists with value $h[1]\n" if $h[1] ;
942 # use a negative index
943 print "The last element is $h[-1]\n" ;
944 print "The 2nd last element is $h[-2]\n" ;
948 Here is the output from the script:
951 Element 1 Exists with value blue
952 The last element is yellow
953 The 2nd last element is blue
957 As you can see from the example above, the tied array interface is
958 quite limited. To make the interface more useful, a number of methods
959 are supplied with B<DB_File> to simulate the standard array operations
960 that are not currently implemented in Perl's tied array interface. All
961 these methods are accessed via the object returned from the tie call.
963 Here are the methods:
967 =item B<$X-E<gt>push(list) ;>
969 Pushes the elements of C<list> to the end of the array.
971 =item B<$value = $X-E<gt>pop ;>
973 Removes and returns the last element of the array.
975 =item B<$X-E<gt>shift>
977 Removes and returns the first element of the array.
979 =item B<$X-E<gt>unshift(list) ;>
981 Pushes the elements of C<list> to the start of the array.
983 =item B<$X-E<gt>length>
985 Returns the number of elements in the array.
989 =head2 Another Example
991 Here is a more complete example that makes use of some of the methods
992 described above. It also makes use of the API interface directly (see
993 L<THE API INTERFACE>).
996 use vars qw(@h $H $file $i) ;
1004 $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0640, $DB_RECNO
1005 or die "Cannot open file $file: $!\n" ;
1007 # first create a text file to play with
1015 # Print the records in order.
1017 # The length method is needed here because evaluating a tied
1018 # array in a scalar context does not return the number of
1019 # elements in the array.
1021 print "\nORIGINAL\n" ;
1022 foreach $i (0 .. $H->length - 1) {
1023 print "$i: $h[$i]\n" ;
1026 # use the push & pop methods
1029 print "\nThe last record was [$a]\n" ;
1031 # and the shift & unshift methods
1033 $H->unshift("first") ;
1034 print "The first record was [$a]\n" ;
1036 # Use the API to add a new record after record 2.
1038 $H->put($i, "Newbie", R_IAFTER) ;
1040 # and a new record before record 1.
1042 $H->put($i, "New One", R_IBEFORE) ;
1047 # now print the records in reverse order
1048 print "\nREVERSE\n" ;
1049 for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
1050 { print "$i: $h[$i]\n" }
1052 # same again, but use the API functions instead
1053 print "\nREVERSE again\n" ;
1054 my ($s, $k, $v) = (0, 0, 0) ;
1055 for ($s = $H->seq($k, $v, R_LAST) ;
1057 $s = $H->seq($k, $v, R_PREV))
1058 { print "$k: $v\n" }
1063 and this is what it outputs:
1072 The last record was [four]
1073 The first record was [zero]
1097 Rather than iterating through the array, C<@h> like this:
1101 it is necessary to use either this:
1103 foreach $i (0 .. $H->length - 1)
1107 for ($a = $H->get($k, $v, R_FIRST) ;
1109 $a = $H->get($k, $v, R_NEXT) )
1113 Notice that both times the C<put> method was used the record index was
1114 specified using a variable, C<$i>, rather than the literal value
1115 itself. This is because C<put> will return the record number of the
1116 inserted line via that parameter.
1120 =head1 THE API INTERFACE
1122 As well as accessing Berkeley DB using a tied hash or array, it is also
1123 possible to make direct use of most of the API functions defined in the
1124 Berkeley DB documentation.
1126 To do this you need to store a copy of the object returned from the tie.
1128 $db = tie %hash, "DB_File", "filename" ;
1130 Once you have done that, you can access the Berkeley DB API functions
1131 as B<DB_File> methods directly like this:
1133 $db->put($key, $value, R_NOOVERWRITE) ;
1135 B<Important:> If you have saved a copy of the object returned from
1136 C<tie>, the underlying database file will I<not> be closed until both
1137 the tied variable is untied and all copies of the saved object are
1141 $db = tie %hash, "DB_File", "filename"
1142 or die "Cannot tie filename: $!" ;
1147 See L<The untie Gotcha> for more details.
1149 All the functions defined in L<dbopen> are available except for
1150 close() and dbopen() itself. The B<DB_File> method interface to the
1151 supported functions have been implemented to mirror the way Berkeley DB
1152 works whenever possible. In particular note that:
1158 The methods return a status value. All return 0 on success.
1159 All return -1 to signify an error and set C<$!> to the exact
1160 error code. The return code 1 generally (but not always) means that the
1161 key specified did not exist in the database.
1163 Other return codes are defined. See below and in the Berkeley DB
1164 documentation for details. The Berkeley DB documentation should be used
1165 as the definitive source.
1169 Whenever a Berkeley DB function returns data via one of its parameters,
1170 the equivalent B<DB_File> method does exactly the same.
1174 If you are careful, it is possible to mix API calls with the tied
1175 hash/array interface in the same piece of code. Although only a few of
1176 the methods used to implement the tied interface currently make use of
1177 the cursor, you should always assume that the cursor has been changed
1178 any time the tied hash/array interface is used. As an example, this
1179 code will probably not do what you expect:
1181 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1182 or die "Cannot tie $filename: $!" ;
1184 # Get the first key/value pair and set the cursor
1185 $X->seq($key, $value, R_FIRST) ;
1187 # this line will modify the cursor
1188 $count = scalar keys %x ;
1190 # Get the second key/value pair.
1191 # oops, it didn't, it got the last key/value pair!
1192 $X->seq($key, $value, R_NEXT) ;
1194 The code above can be rearranged to get around the problem, like this:
1196 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1197 or die "Cannot tie $filename: $!" ;
1199 # this line will modify the cursor
1200 $count = scalar keys %x ;
1202 # Get the first key/value pair and set the cursor
1203 $X->seq($key, $value, R_FIRST) ;
1205 # Get the second key/value pair.
1207 $X->seq($key, $value, R_NEXT) ;
1211 All the constants defined in L<dbopen> for use in the flags parameters
1212 in the methods defined below are also available. Refer to the Berkeley
1213 DB documentation for the precise meaning of the flags values.
1215 Below is a list of the methods available.
1219 =item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
1221 Given a key (C<$key>) this method reads the value associated with it
1222 from the database. The value read from the database is returned in the
1223 C<$value> parameter.
1225 If the key does not exist the method returns 1.
1227 No flags are currently defined for this method.
1229 =item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
1231 Stores the key/value pair in the database.
1233 If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
1234 will have the record number of the inserted key/value pair set.
1236 Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1239 =item B<$status = $X-E<gt>del($key [, $flags]) ;>
1241 Removes all key/value pairs with key C<$key> from the database.
1243 A return code of 1 means that the requested key was not in the
1246 R_CURSOR is the only valid flag at present.
1248 =item B<$status = $X-E<gt>fd ;>
1250 Returns the file descriptor for the underlying database.
1252 See L<Locking Databases> for an example of how to make use of the
1253 C<fd> method to lock your database.
1255 =item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
1257 This interface allows sequential retrieval from the database. See
1258 L<dbopen> for full details.
1260 Both the C<$key> and C<$value> parameters will be set to the key/value
1261 pair read from the database.
1263 The flags parameter is mandatory. The valid flag values are R_CURSOR,
1264 R_FIRST, R_LAST, R_NEXT and R_PREV.
1266 =item B<$status = $X-E<gt>sync([$flags]) ;>
1268 Flushes any cached buffers to disk.
1270 R_RECNOSYNC is the only valid flag at present.
1274 =head1 HINTS AND TIPS
1277 =head2 Locking Databases
1279 Concurrent access of a read-write database by several parties requires
1280 them all to use some kind of locking. Here's an example of Tom's that
1281 uses the I<fd> method to get the file descriptor, and then a careful
1282 open() to give something Perl will flock() for you. Run this repeatedly
1283 in the background to watch the locks granted in proper order.
1294 my($oldval, $fd, $db, %db, $value, $key);
1296 $key = shift || 'default';
1297 $value = shift || 'magic';
1301 $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0644)
1302 || die "dbcreat /tmp/foo.db $!";
1304 print "$$: db fd is $fd\n";
1305 open(DB_FH, "+<&=$fd") || die "dup $!";
1308 unless (flock (DB_FH, LOCK_SH | LOCK_NB)) {
1309 print "$$: CONTENTION; can't read during write update!
1310 Waiting for read lock ($!) ....";
1311 unless (flock (DB_FH, LOCK_SH)) { die "flock: $!" }
1313 print "$$: Read lock granted\n";
1315 $oldval = $db{$key};
1316 print "$$: Old value was $oldval\n";
1317 flock(DB_FH, LOCK_UN);
1319 unless (flock (DB_FH, LOCK_EX | LOCK_NB)) {
1320 print "$$: CONTENTION; must have exclusive lock!
1321 Waiting for write lock ($!) ....";
1322 unless (flock (DB_FH, LOCK_EX)) { die "flock: $!" }
1325 print "$$: Write lock granted\n";
1327 $db->sync; # to flush
1330 flock(DB_FH, LOCK_UN);
1334 print "$$: Updated db to $key=$value\n";
1336 =head2 Sharing databases with C applications
1338 There is no technical reason why a Berkeley DB database cannot be
1339 shared by both a Perl and a C application.
1341 The vast majority of problems that are reported in this area boil down
1342 to the fact that C strings are NULL terminated, whilst Perl strings are
1345 Here is a real example. Netscape 2.0 keeps a record of the locations you
1346 visit along with the time you last visited them in a DB_HASH database.
1347 This is usually stored in the file F<~/.netscape/history.db>. The key
1348 field in the database is the location string and the value field is the
1349 time the location was last visited stored as a 4 byte binary value.
1351 If you haven't already guessed, the location string is stored with a
1352 terminating NULL. This means you need to be careful when accessing the
1355 Here is a snippet of code that is loosely based on Tom Christiansen's
1356 I<ggh> script (available from your nearest CPAN archive in
1357 F<authors/id/TOMC/scripts/nshist.gz>).
1363 use vars qw( $dotdir $HISTORY %hist_db $href $binary_time $date ) ;
1364 $dotdir = $ENV{HOME} || $ENV{LOGNAME};
1366 $HISTORY = "$dotdir/.netscape/history.db";
1368 tie %hist_db, 'DB_File', $HISTORY
1369 or die "Cannot open $HISTORY: $!\n" ;;
1371 # Dump the complete database
1372 while ( ($href, $binary_time) = each %hist_db ) {
1374 # remove the terminating NULL
1375 $href =~ s/\x00$// ;
1377 # convert the binary time into a user friendly string
1378 $date = localtime unpack("V", $binary_time);
1379 print "$date $href\n" ;
1382 # check for the existence of a specific key
1383 # remember to add the NULL
1384 if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
1385 $date = localtime unpack("V", $binary_time) ;
1386 print "Last visited mox.perl.com on $date\n" ;
1389 print "Never visited mox.perl.com\n"
1394 =head2 The untie gotcha
1396 If you make use of the Berkeley DB API, it is is I<very> strongly
1397 recommended that you read L<perltie/The untie gotcha>.
1399 Even if you don't currently make use of the API interface, it is still
1402 Here is an example which illustrates the problem from a B<DB_File>
1411 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
1412 or die "Cannot tie first time: $!" ;
1418 tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1419 or die "Cannot tie second time: $!" ;
1423 When run, the script will produce this error message:
1425 Cannot tie second time: Invalid argument at bad.file line 14.
1427 Although the error message above refers to the second tie() statement
1428 in the script, the source of the problem is really with the untie()
1429 statement that precedes it.
1431 Having read L<perltie> you will probably have already guessed that the
1432 error is caused by the extra copy of the tied object stored in C<$X>.
1433 If you haven't, then the problem boils down to the fact that the
1434 B<DB_File> destructor, DESTROY, will not be called until I<all>
1435 references to the tied object are destroyed. Both the tied variable,
1436 C<%x>, and C<$X> above hold a reference to the object. The call to
1437 untie() will destroy the first, but C<$X> still holds a valid
1438 reference, so the destructor will not get called and the database file
1439 F<tst.fil> will remain open. The fact that Berkeley DB then reports the
1440 attempt to open a database that is alreday open via the catch-all
1441 "Invalid argument" doesn't help.
1443 If you run the script with the C<-w> flag the error message becomes:
1445 untie attempted while 1 inner references still exist at bad.file line 12.
1446 Cannot tie second time: Invalid argument at bad.file line 14.
1448 which pinpoints the real problem. Finally the script can now be
1449 modified to fix the original problem by destroying the API object
1458 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1462 =head1 COMMON QUESTIONS
1464 =head2 Why is there Perl source in my database?
1466 If you look at the contents of a database file created by DB_File,
1467 there can sometimes be part of a Perl script included in it.
1469 This happens because Berkeley DB uses dynamic memory to allocate
1470 buffers which will subsequently be written to the database file. Being
1471 dynamic, the memory could have been used for anything before DB
1472 malloced it. As Berkeley DB doesn't clear the memory once it has been
1473 allocated, the unused portions will contain random junk. In the case
1474 where a Perl script gets written to the database, the random junk will
1475 correspond to an area of dynamic memory that happened to be used during
1476 the compilation of the script.
1478 Unless you don't like the possibility of there being part of your Perl
1479 scripts embedded in a database file, this is nothing to worry about.
1481 =head2 How do I store complex data structures with DB_File?
1483 Although B<DB_File> cannot do this directly, there is a module which
1484 can layer transparently over B<DB_File> to accomplish this feat.
1486 Check out the MLDBM module, available on CPAN in the directory
1487 F<modules/by-module/MLDBM>.
1489 =head2 What does "Invalid Argument" mean?
1491 You will get this error message when one of the parameters in the
1492 C<tie> call is wrong. Unfortunately there are quite a few parameters to
1493 get wrong, so it can be difficult to figure out which one it is.
1495 Here are a couple of possibilities:
1501 Attempting to reopen a database without closing it.
1505 Using the O_WRONLY flag.
1509 =head2 What does "Bareword 'DB_File' not allowed" mean?
1511 You will encounter this particular error message when you have the
1512 C<strict 'subs'> pragma (or the full strict pragma) in your script.
1513 Consider this script:
1518 tie %x, DB_File, "filename" ;
1520 Running it produces the error in question:
1522 Bareword "DB_File" not allowed while "strict subs" in use
1524 To get around the error, place the word C<DB_File> in either single or
1525 double quotes, like this:
1527 tie %x, "DB_File", "filename" ;
1529 Although it might seem like a real pain, it is really worth the effort
1530 of having a C<use strict> in all your scripts.
1542 When B<DB_File> is opening a database file it no longer terminates the
1543 process if I<dbopen> returned an error. This allows file protection
1544 errors to be caught at run time. Thanks to Judith Grass
1545 E<lt>grass@cybercash.comE<gt> for spotting the bug.
1549 Added prototype support for multiple btree compare callbacks.
1553 B<DB_File> has been in use for over a year. To reflect that, the
1554 version number has been incremented to 1.0.
1556 Added complete support for multiple concurrent callbacks.
1558 Using the I<push> method on an empty list didn't work properly. This
1563 Fixed a core dump problem with SunOS.
1565 The return value from TIEHASH wasn't set to NULL when dbopen returned
1570 Merged OS/2 specific code into DB_File.xs
1572 Removed some redundant code in DB_File.xs.
1574 Documentation update.
1576 Allow negative subscripts with RECNO interface.
1578 Changed the default flags from O_RDWR to O_CREAT|O_RDWR.
1580 The example code which showed how to lock a database needed a call to
1581 C<sync> added. Without it the resultant database file was empty.
1583 Added get_dup method.
1587 Documentation update.
1589 B<DB_File> now imports the constants (O_RDWR, O_CREAT etc.) from Fcntl
1592 The standard hash function C<exists> is now supported.
1594 Modified the behavior of get_dup. When it returns an associative
1595 array, the value is the count of the number of matching BTREE values.
1599 Minor documentation changes.
1601 Fixed a bug in hash_cb. Patches supplied by Dave Hammen,
1602 E<lt>hammen@gothamcity.jsc.nasa.govE<gt>.
1604 Fixed a bug with the constructors for DB_File::HASHINFO,
1605 DB_File::BTREEINFO and DB_File::RECNOINFO. Also tidied up the
1606 constructors to make them C<-w> clean.
1608 Reworked part of the test harness to be more locale friendly.
1612 Made all scripts in the documentation C<strict> and C<-w> clean.
1614 Added logic to F<DB_File.xs> to allow the module to be built after Perl
1619 Minor namespace cleanup: Localized C<PrintBtree>.
1623 Fixed bug with RECNO, where bval wasn't defaulting to "\n".
1627 Documented operation of bval.
1631 Minor bug fix in DB_File::HASHINFO, DB_File::RECNOINFO and
1634 Changed default mode to 0666.
1638 Fixed fd method so that it still returns -1 for in-memory files when db
1643 Documented the untie gotcha.
1649 Some older versions of Berkeley DB had problems with fixed length
1650 records using the RECNO file format. The newest version at the time of
1651 writing was 1.85 - this seems to have fixed the problems with RECNO.
1653 I am sure there are bugs in the code. If you do find any, or can
1654 suggest any enhancements, I would welcome your comments.
1658 B<DB_File> comes with the standard Perl source distribution. Look in
1659 the directory F<ext/DB_File>.
1661 Berkeley DB is available at your nearest CPAN archive (see
1662 L<perlmod/"CPAN"> for a list) in F<src/misc/db.1.85.tar.gz>, or via the
1663 host F<ftp.cs.berkeley.edu> in F</ucb/4bsd/db.tar.gz>. Alternatively,
1664 check out the Berkeley DB home page at F<http://www.bostic.com/db>. It
1665 is I<not> under the GPL.
1667 If you are running IRIX, then get Berkeley DB from
1668 F<http://reality.sgi.com/ariel>. It has the patches necessary to
1669 compile properly on IRIX 5.3.
1671 As of January 1997, version 1.86 of Berkeley DB is available from the
1672 Berkeley DB home page. Although this release does fix a number of bugs
1673 that were present in 1.85 you should be aware of the following
1674 information (taken from the Berkeley DB home page) before you consider
1677 DB version 1.86 includes a new implementation of the hash access
1678 method that fixes a variety of hashing problems found in DB version
1679 1.85. We are making it available as an interim solution until DB
1682 PLEASE NOTE: the underlying file format for the hash access method
1683 changed between version 1.85 and version 1.86, so you will have to
1684 dump and reload all of your databases to convert from version 1.85
1685 to version 1.86. If you do not absolutely require the fixes from
1686 version 1.86, we strongly urge you to wait until DB 2.0 is released
1687 before upgrading from 1.85.
1692 L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>
1696 The DB_File interface was written by Paul Marquess
1697 E<lt>pmarquess@bfsec.bt.co.ukE<gt>.
1698 Questions about the DB system itself may be addressed to Keith Bostic
1699 E<lt>bostic@cs.berkeley.eduE<gt>.