1 # DB_File.pm -- Perl 5 interface to Berkeley DB
3 # written by Paul Marquess (pmarquess@bfsec.bt.co.uk)
4 # last modified 19th November 1998
7 # Copyright (c) 1995-8 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 $db_version) ;
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 ## import borrowed from IO::File
223 ## exports Fcntl constants if available.
226 # my $callpkg = caller;
227 # Exporter::export $pkg, $callpkg, @_;
230 # Exporter::export 'Fcntl', $callpkg, '/^O_/';
234 bootstrap DB_File $VERSION;
236 # Preloaded methods go here. Autoload methods go after __END__, and are
237 # processed by the autosplit program.
239 sub tie_hash_or_array
242 my $tieHASH = ( (caller(1))[3] =~ /TIEHASH/ ) ;
244 $arg[4] = tied %{ $arg[4] }
245 if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
247 # make recno in Berkeley DB version 2 work like recno in version 1.
248 if ($db_version > 1 and defined $arg[4] and $arg[4] =~ /RECNO/ and
249 $arg[1] and ! -e $arg[1]) {
250 open(FH, ">$arg[1]") or return undef ;
252 chmod $arg[3] ? $arg[3] : 0666 , $arg[1] ;
255 DoTie_($tieHASH, @arg) ;
260 tie_hash_or_array(@_) ;
265 tie_hash_or_array(@_) ;
273 my $status = $self->seq($key, $value, R_FIRST());
276 while ($status == 0) {
278 $status = $self->seq($key, $value, R_NEXT());
280 foreach $key (reverse @keys) {
281 my $s = $self->del($key);
291 my $current_length = $self->length() ;
293 if ($length < $current_length) {
295 for ($key = $current_length - 1 ; $key >= $length ; -- $key)
298 elsif ($length > $current_length) {
299 $self->put($length-1, "") ;
305 croak "Usage: \$db->get_dup(key [,flag])\n"
306 unless @_ == 2 or @_ == 3 ;
313 my $wantarray = wantarray ;
319 # iterate through the database until either EOF ($status == 0)
320 # or a different key is encountered ($key ne $origkey).
321 for ($status = $db->seq($key, $value, R_CURSOR()) ;
322 $status == 0 and $key eq $origkey ;
323 $status = $db->seq($key, $value, R_NEXT()) ) {
325 # save the value or count number of matches
328 { ++ $values{$value} }
330 { push (@values, $value) }
337 return ($wantarray ? ($flag ? %values : @values) : $counter) ;
346 DB_File - Perl5 access to Berkeley DB version 1.x
352 [$X =] tie %hash, 'DB_File', [$filename, $flags, $mode, $DB_HASH] ;
353 [$X =] tie %hash, 'DB_File', $filename, $flags, $mode, $DB_BTREE ;
354 [$X =] tie @array, 'DB_File', $filename, $flags, $mode, $DB_RECNO ;
356 $status = $X->del($key [, $flags]) ;
357 $status = $X->put($key, $value [, $flags]) ;
358 $status = $X->get($key, $value [, $flags]) ;
359 $status = $X->seq($key, $value, $flags) ;
360 $status = $X->sync([$flags]) ;
364 $count = $X->get_dup($key) ;
365 @list = $X->get_dup($key) ;
366 %list = $X->get_dup($key, 1) ;
380 B<DB_File> is a module which allows Perl programs to make use of the
381 facilities provided by Berkeley DB version 1.x (if you have a newer
382 version of DB, see L<Using DB_File with Berkeley DB version 2>). It is
383 assumed that you have a copy of the Berkeley DB manual pages at hand
384 when reading this documentation. The interface defined here mirrors the
385 Berkeley DB interface closely.
387 Berkeley DB is a C library which provides a consistent interface to a
388 number of database formats. B<DB_File> provides an interface to all
389 three of the database types currently supported by Berkeley DB.
397 This database type allows arbitrary key/value pairs to be stored in data
398 files. This is equivalent to the functionality provided by other
399 hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
400 the files created using DB_HASH are not compatible with any of the
401 other packages mentioned.
403 A default hashing algorithm, which will be adequate for most
404 applications, is built into Berkeley DB. If you do need to use your own
405 hashing algorithm it is possible to write your own in Perl and have
406 B<DB_File> use it instead.
410 The btree format allows arbitrary key/value pairs to be stored in a
411 sorted, balanced binary tree.
413 As with the DB_HASH format, it is possible to provide a user defined
414 Perl routine to perform the comparison of keys. By default, though, the
415 keys are stored in lexical order.
419 DB_RECNO allows both fixed-length and variable-length flat text files
420 to be manipulated using the same key/value pair interface as in DB_HASH
421 and DB_BTREE. In this case the key will consist of a record (line)
426 =head2 Using DB_File with Berkeley DB version 2
428 Although B<DB_File> is intended to be used with Berkeley DB version 1,
429 it can also be used with version 2. In this case the interface is
430 limited to the functionality provided by Berkeley DB 1.x. Anywhere the
431 version 2 interface differs, B<DB_File> arranges for it to work like
432 version 1. This feature allows B<DB_File> scripts that were built with
433 version 1 to be migrated to version 2 without any changes.
435 If you want to make use of the new features available in Berkeley DB
436 2.x, use the Perl module B<BerkeleyDB> instead.
438 At the time of writing this document the B<BerkeleyDB> module is still
439 alpha quality (the version number is < 1.0), and so unsuitable for use
440 in any serious development work. Once its version number is >= 1.0, it
441 is considered stable enough for real work.
443 B<Note:> The database file format has changed in Berkeley DB version 2.
444 If you cannot recreate your databases, you must dump any existing
445 databases with the C<db_dump185> utility that comes with Berkeley DB.
446 Once you have upgraded DB_File to use Berkeley DB version 2, your
447 databases can be recreated using C<db_load>. Refer to the Berkeley DB
448 documentation for further details.
450 Please read L<COPYRIGHT> before using version 2.x of Berkeley DB with
453 =head2 Interface to Berkeley DB
455 B<DB_File> allows access to Berkeley DB files using the tie() mechanism
456 in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
457 allows B<DB_File> to access Berkeley DB files using either an
458 associative array (for DB_HASH & DB_BTREE file types) or an ordinary
459 array (for the DB_RECNO file type).
461 In addition to the tie() interface, it is also possible to access most
462 of the functions provided in the Berkeley DB API directly.
463 See L<THE API INTERFACE>.
465 =head2 Opening a Berkeley DB Database File
467 Berkeley DB uses the function dbopen() to open or create a database.
468 Here is the C prototype for dbopen():
471 dbopen (const char * file, int flags, int mode,
472 DBTYPE type, const void * openinfo)
474 The parameter C<type> is an enumeration which specifies which of the 3
475 interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
476 Depending on which of these is actually chosen, the final parameter,
477 I<openinfo> points to a data structure which allows tailoring of the
478 specific interface method.
480 This interface is handled slightly differently in B<DB_File>. Here is
481 an equivalent call using B<DB_File>:
483 tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
485 The C<filename>, C<flags> and C<mode> parameters are the direct
486 equivalent of their dbopen() counterparts. The final parameter $DB_HASH
487 performs the function of both the C<type> and C<openinfo> parameters in
490 In the example above $DB_HASH is actually a pre-defined reference to a
491 hash object. B<DB_File> has three of these pre-defined references.
492 Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
494 The keys allowed in each of these pre-defined references is limited to
495 the names used in the equivalent C structure. So, for example, the
496 $DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
497 C<ffactor>, C<hash>, C<lorder> and C<nelem>.
499 To change one of these elements, just assign to it like this:
501 $DB_HASH->{'cachesize'} = 10000 ;
503 The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
504 usually adequate for most applications. If you do need to create extra
505 instances of these objects, constructors are available for each file
508 Here are examples of the constructors and the valid options available
509 for DB_HASH, DB_BTREE and DB_RECNO respectively.
511 $a = new DB_File::HASHINFO ;
519 $b = new DB_File::BTREEINFO ;
529 $c = new DB_File::RECNOINFO ;
538 The values stored in the hashes above are mostly the direct equivalent
539 of their C counterpart. Like their C counterparts, all are set to a
540 default values - that means you don't have to set I<all> of the
541 values when you only want to change one. Here is an example:
543 $a = new DB_File::HASHINFO ;
544 $a->{'cachesize'} = 12345 ;
545 tie %y, 'DB_File', "filename", $flags, 0777, $a ;
547 A few of the options need extra discussion here. When used, the C
548 equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
549 to C functions. In B<DB_File> these keys are used to store references
550 to Perl subs. Below are templates for each of the subs:
556 # return the hash value for $data
562 my ($key, $key2) = @_ ;
564 # return 0 if $key1 eq $key2
565 # -1 if $key1 lt $key2
566 # 1 if $key1 gt $key2
567 return (-1 , 0 or 1) ;
572 my ($key, $key2) = @_ ;
574 # return number of bytes of $key2 which are
575 # necessary to determine that it is greater than $key1
579 See L<Changing the BTREE sort order> for an example of using the
582 If you are using the DB_RECNO interface and you intend making use of
583 C<bval>, you should check out L<The 'bval' Option>.
585 =head2 Default Parameters
587 It is possible to omit some or all of the final 4 parameters in the
588 call to C<tie> and let them take default values. As DB_HASH is the most
589 common file format used, the call:
591 tie %A, "DB_File", "filename" ;
595 tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
597 It is also possible to omit the filename parameter as well, so the
604 tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
606 See L<In Memory Databases> for a discussion on the use of C<undef>
607 in place of a filename.
609 =head2 In Memory Databases
611 Berkeley DB allows the creation of in-memory databases by using NULL
612 (that is, a C<(char *)0> in C) in place of the filename. B<DB_File>
613 uses C<undef> instead of NULL to provide this functionality.
617 The DB_HASH file format is probably the most commonly used of the three
618 file formats that B<DB_File> supports. It is also very straightforward
621 =head2 A Simple Example
623 This example shows how to create a database, add key/value pairs to the
624 database, delete keys/value pairs and finally how to enumerate the
625 contents of the database.
629 use vars qw( %h $k $v ) ;
631 tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0640, $DB_HASH
632 or die "Cannot open file 'fruit': $!\n";
634 # Add a few key/value pairs to the file
635 $h{"apple"} = "red" ;
636 $h{"orange"} = "orange" ;
637 $h{"banana"} = "yellow" ;
638 $h{"tomato"} = "red" ;
640 # Check for existence of a key
641 print "Banana Exists\n\n" if $h{"banana"} ;
643 # Delete a key/value pair.
646 # print the contents of the file
647 while (($k, $v) = each %h)
648 { print "$k -> $v\n" }
660 Note that the like ordinary associative arrays, the order of the keys
661 retrieved is in an apparently random order.
665 The DB_BTREE format is useful when you want to store data in a given
666 order. By default the keys will be stored in lexical order, but as you
667 will see from the example shown in the next section, it is very easy to
668 define your own sorting function.
670 =head2 Changing the BTREE sort order
672 This script shows how to override the default sorting algorithm that
673 BTREE uses. Instead of using the normal lexical ordering, a case
674 insensitive compare function will be used.
683 my ($key1, $key2) = @_ ;
684 "\L$key1" cmp "\L$key2" ;
687 # specify the Perl sub that will do the comparison
688 $DB_BTREE->{'compare'} = \&Compare ;
690 tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE
691 or die "Cannot open file 'tree': $!\n" ;
693 # Add a key/value pair to the file
694 $h{'Wall'} = 'Larry' ;
695 $h{'Smith'} = 'John' ;
696 $h{'mouse'} = 'mickey' ;
697 $h{'duck'} = 'donald' ;
702 # Cycle through the keys printing them in order.
703 # Note it is not necessary to sort the keys as
704 # the btree will have kept them in order automatically.
710 Here is the output from the code above.
716 There are a few point to bear in mind if you want to change the
717 ordering in a BTREE database:
723 The new compare function must be specified when you create the database.
727 You cannot change the ordering once the database has been created. Thus
728 you must use the same compare function every time you access the
733 =head2 Handling Duplicate Keys
735 The BTREE file type optionally allows a single key to be associated
736 with an arbitrary number of values. This option is enabled by setting
737 the flags element of C<$DB_BTREE> to R_DUP when creating the database.
739 There are some difficulties in using the tied hash interface if you
740 want to manipulate a BTREE database with duplicate keys. Consider this
746 use vars qw($filename %h ) ;
751 # Enable duplicate records
752 $DB_BTREE->{'flags'} = R_DUP ;
754 tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
755 or die "Cannot open $filename: $!\n";
757 # Add some key/value pairs to the file
758 $h{'Wall'} = 'Larry' ;
759 $h{'Wall'} = 'Brick' ; # Note the duplicate key
760 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
761 $h{'Smith'} = 'John' ;
762 $h{'mouse'} = 'mickey' ;
764 # iterate through the associative array
765 # and print each key/value pair.
767 { print "$_ -> $h{$_}\n" }
779 As you can see 3 records have been successfully created with key C<Wall>
780 - the only thing is, when they are retrieved from the database they
781 I<seem> to have the same value, namely C<Larry>. The problem is caused
782 by the way that the associative array interface works. Basically, when
783 the associative array interface is used to fetch the value associated
784 with a given key, it will only ever retrieve the first value.
786 Although it may not be immediately obvious from the code above, the
787 associative array interface can be used to write values with duplicate
788 keys, but it cannot be used to read them back from the database.
790 The way to get around this problem is to use the Berkeley DB API method
791 called C<seq>. This method allows sequential access to key/value
792 pairs. See L<THE API INTERFACE> for details of both the C<seq> method
793 and the API in general.
795 Here is the script above rewritten using the C<seq> API method.
800 use vars qw($filename $x %h $status $key $value) ;
805 # Enable duplicate records
806 $DB_BTREE->{'flags'} = R_DUP ;
808 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
809 or die "Cannot open $filename: $!\n";
811 # Add some key/value pairs to the file
812 $h{'Wall'} = 'Larry' ;
813 $h{'Wall'} = 'Brick' ; # Note the duplicate key
814 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
815 $h{'Smith'} = 'John' ;
816 $h{'mouse'} = 'mickey' ;
818 # iterate through the btree using seq
819 # and print each key/value pair.
821 for ($status = $x->seq($key, $value, R_FIRST) ;
823 $status = $x->seq($key, $value, R_NEXT) )
824 { print "$key -> $value\n" }
837 This time we have got all the key/value pairs, including the multiple
838 values associated with the key C<Wall>.
840 =head2 The get_dup() Method
842 B<DB_File> comes with a utility method, called C<get_dup>, to assist in
843 reading duplicate values from BTREE databases. The method can take the
846 $count = $x->get_dup($key) ;
847 @list = $x->get_dup($key) ;
848 %list = $x->get_dup($key, 1) ;
850 In a scalar context the method returns the number of values associated
851 with the key, C<$key>.
853 In list context, it returns all the values which match C<$key>. Note
854 that the values will be returned in an apparently random order.
856 In list context, if the second parameter is present and evaluates
857 TRUE, the method returns an associative array. The keys of the
858 associative array correspond to the values that matched in the BTREE
859 and the values of the array are a count of the number of times that
860 particular value occurred in the BTREE.
862 So assuming the database created above, we can use C<get_dup> like
865 my $cnt = $x->get_dup("Wall") ;
866 print "Wall occurred $cnt times\n" ;
868 my %hash = $x->get_dup("Wall", 1) ;
869 print "Larry is there\n" if $hash{'Larry'} ;
870 print "There are $hash{'Brick'} Brick Walls\n" ;
872 my @list = $x->get_dup("Wall") ;
873 print "Wall => [@list]\n" ;
875 @list = $x->get_dup("Smith") ;
876 print "Smith => [@list]\n" ;
878 @list = $x->get_dup("Dog") ;
879 print "Dog => [@list]\n" ;
884 Wall occurred 3 times
886 There are 2 Brick Walls
887 Wall => [Brick Brick Larry]
891 =head2 Matching Partial Keys
893 The BTREE interface has a feature which allows partial keys to be
894 matched. This functionality is I<only> available when the C<seq> method
895 is used along with the R_CURSOR flag.
897 $x->seq($key, $value, R_CURSOR) ;
899 Here is the relevant quote from the dbopen man page where it defines
900 the use of the R_CURSOR flag with seq:
902 Note, for the DB_BTREE access method, the returned key is not
903 necessarily an exact match for the specified key. The returned key
904 is the smallest key greater than or equal to the specified key,
905 permitting partial key matches and range searches.
907 In the example script below, the C<match> sub uses this feature to find
908 and print the first matching key/value pair given a partial key.
914 use vars qw($filename $x %h $st $key $value) ;
920 my $orig_key = $key ;
921 $x->seq($key, $value, R_CURSOR) ;
922 print "$orig_key\t-> $key\t-> $value\n" ;
928 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
929 or die "Cannot open $filename: $!\n";
931 # Add some key/value pairs to the file
932 $h{'mouse'} = 'mickey' ;
933 $h{'Wall'} = 'Larry' ;
934 $h{'Walls'} = 'Brick' ;
935 $h{'Smith'} = 'John' ;
940 for ($st = $x->seq($key, $value, R_FIRST) ;
942 $st = $x->seq($key, $value, R_NEXT) )
944 { print "$key -> $value\n" }
946 print "\nPARTIAL MATCH\n" ;
970 DB_RECNO provides an interface to flat text files. Both variable and
971 fixed length records are supported.
973 In order to make RECNO more compatible with Perl the array offset for
974 all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
976 As with normal Perl arrays, a RECNO array can be accessed using
977 negative indexes. The index -1 refers to the last element of the array,
978 -2 the second last, and so on. Attempting to access an element before
979 the start of the array will raise a fatal run-time error.
981 =head2 The 'bval' Option
983 The operation of the bval option warrants some discussion. Here is the
984 definition of bval from the Berkeley DB 1.85 recno manual page:
986 The delimiting byte to be used to mark the end of a
987 record for variable-length records, and the pad charac-
988 ter for fixed-length records. If no value is speci-
989 fied, newlines (``\n'') are used to mark the end of
990 variable-length records and fixed-length records are
993 The second sentence is wrong. In actual fact bval will only default to
994 C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
995 openinfo parameter is used at all, the value that happens to be in bval
996 will be used. That means you always have to specify bval when making
997 use of any of the options in the openinfo parameter. This documentation
998 error will be fixed in the next release of Berkeley DB.
1000 That clarifies the situation with regards Berkeley DB itself. What
1001 about B<DB_File>? Well, the behavior defined in the quote above is
1002 quite useful, so B<DB_File> conforms it.
1004 That means that you can specify other options (e.g. cachesize) and
1005 still have bval default to C<"\n"> for variable length records, and
1006 space for fixed length records.
1008 =head2 A Simple Example
1010 Here is a simple example that uses RECNO.
1016 tie @h, "DB_File", "text", O_RDWR|O_CREAT, 0640, $DB_RECNO
1017 or die "Cannot open file 'text': $!\n" ;
1019 # Add a few key/value pairs to the file
1024 # Check for existence of a key
1025 print "Element 1 Exists with value $h[1]\n" if $h[1] ;
1027 # use a negative index
1028 print "The last element is $h[-1]\n" ;
1029 print "The 2nd last element is $h[-2]\n" ;
1033 Here is the output from the script:
1036 Element 1 Exists with value blue
1037 The last element is yellow
1038 The 2nd last element is blue
1040 =head2 Extra Methods
1042 If you are using a version of Perl earlier than 5.004_57, the tied
1043 array interface is quite limited. The example script above will work,
1044 but you won't be able to use C<push>, C<pop>, C<shift>, C<unshift>
1045 etc. with the tied array.
1047 To make the interface more useful for older versions of Perl, a number
1048 of methods are supplied with B<DB_File> to simulate the missing array
1049 operations. All these methods are accessed via the object returned from
1052 Here are the methods:
1056 =item B<$X-E<gt>push(list) ;>
1058 Pushes the elements of C<list> to the end of the array.
1060 =item B<$value = $X-E<gt>pop ;>
1062 Removes and returns the last element of the array.
1064 =item B<$X-E<gt>shift>
1066 Removes and returns the first element of the array.
1068 =item B<$X-E<gt>unshift(list) ;>
1070 Pushes the elements of C<list> to the start of the array.
1072 =item B<$X-E<gt>length>
1074 Returns the number of elements in the array.
1078 =head2 Another Example
1080 Here is a more complete example that makes use of some of the methods
1081 described above. It also makes use of the API interface directly (see
1082 L<THE API INTERFACE>).
1085 use vars qw(@h $H $file $i) ;
1093 $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0640, $DB_RECNO
1094 or die "Cannot open file $file: $!\n" ;
1096 # first create a text file to play with
1104 # Print the records in order.
1106 # The length method is needed here because evaluating a tied
1107 # array in a scalar context does not return the number of
1108 # elements in the array.
1110 print "\nORIGINAL\n" ;
1111 foreach $i (0 .. $H->length - 1) {
1112 print "$i: $h[$i]\n" ;
1115 # use the push & pop methods
1118 print "\nThe last record was [$a]\n" ;
1120 # and the shift & unshift methods
1122 $H->unshift("first") ;
1123 print "The first record was [$a]\n" ;
1125 # Use the API to add a new record after record 2.
1127 $H->put($i, "Newbie", R_IAFTER) ;
1129 # and a new record before record 1.
1131 $H->put($i, "New One", R_IBEFORE) ;
1136 # now print the records in reverse order
1137 print "\nREVERSE\n" ;
1138 for ($i = $H->length - 1 ; $i >= 0 ; -- $i)
1139 { print "$i: $h[$i]\n" }
1141 # same again, but use the API functions instead
1142 print "\nREVERSE again\n" ;
1143 my ($s, $k, $v) = (0, 0, 0) ;
1144 for ($s = $H->seq($k, $v, R_LAST) ;
1146 $s = $H->seq($k, $v, R_PREV))
1147 { print "$k: $v\n" }
1152 and this is what it outputs:
1161 The last record was [four]
1162 The first record was [zero]
1186 Rather than iterating through the array, C<@h> like this:
1190 it is necessary to use either this:
1192 foreach $i (0 .. $H->length - 1)
1196 for ($a = $H->get($k, $v, R_FIRST) ;
1198 $a = $H->get($k, $v, R_NEXT) )
1202 Notice that both times the C<put> method was used the record index was
1203 specified using a variable, C<$i>, rather than the literal value
1204 itself. This is because C<put> will return the record number of the
1205 inserted line via that parameter.
1209 =head1 THE API INTERFACE
1211 As well as accessing Berkeley DB using a tied hash or array, it is also
1212 possible to make direct use of most of the API functions defined in the
1213 Berkeley DB documentation.
1215 To do this you need to store a copy of the object returned from the tie.
1217 $db = tie %hash, "DB_File", "filename" ;
1219 Once you have done that, you can access the Berkeley DB API functions
1220 as B<DB_File> methods directly like this:
1222 $db->put($key, $value, R_NOOVERWRITE) ;
1224 B<Important:> If you have saved a copy of the object returned from
1225 C<tie>, the underlying database file will I<not> be closed until both
1226 the tied variable is untied and all copies of the saved object are
1230 $db = tie %hash, "DB_File", "filename"
1231 or die "Cannot tie filename: $!" ;
1236 See L<The untie() Gotcha> for more details.
1238 All the functions defined in L<dbopen> are available except for
1239 close() and dbopen() itself. The B<DB_File> method interface to the
1240 supported functions have been implemented to mirror the way Berkeley DB
1241 works whenever possible. In particular note that:
1247 The methods return a status value. All return 0 on success.
1248 All return -1 to signify an error and set C<$!> to the exact
1249 error code. The return code 1 generally (but not always) means that the
1250 key specified did not exist in the database.
1252 Other return codes are defined. See below and in the Berkeley DB
1253 documentation for details. The Berkeley DB documentation should be used
1254 as the definitive source.
1258 Whenever a Berkeley DB function returns data via one of its parameters,
1259 the equivalent B<DB_File> method does exactly the same.
1263 If you are careful, it is possible to mix API calls with the tied
1264 hash/array interface in the same piece of code. Although only a few of
1265 the methods used to implement the tied interface currently make use of
1266 the cursor, you should always assume that the cursor has been changed
1267 any time the tied hash/array interface is used. As an example, this
1268 code will probably not do what you expect:
1270 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1271 or die "Cannot tie $filename: $!" ;
1273 # Get the first key/value pair and set the cursor
1274 $X->seq($key, $value, R_FIRST) ;
1276 # this line will modify the cursor
1277 $count = scalar keys %x ;
1279 # Get the second key/value pair.
1280 # oops, it didn't, it got the last key/value pair!
1281 $X->seq($key, $value, R_NEXT) ;
1283 The code above can be rearranged to get around the problem, like this:
1285 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1286 or die "Cannot tie $filename: $!" ;
1288 # this line will modify the cursor
1289 $count = scalar keys %x ;
1291 # Get the first key/value pair and set the cursor
1292 $X->seq($key, $value, R_FIRST) ;
1294 # Get the second key/value pair.
1296 $X->seq($key, $value, R_NEXT) ;
1300 All the constants defined in L<dbopen> for use in the flags parameters
1301 in the methods defined below are also available. Refer to the Berkeley
1302 DB documentation for the precise meaning of the flags values.
1304 Below is a list of the methods available.
1308 =item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
1310 Given a key (C<$key>) this method reads the value associated with it
1311 from the database. The value read from the database is returned in the
1312 C<$value> parameter.
1314 If the key does not exist the method returns 1.
1316 No flags are currently defined for this method.
1318 =item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
1320 Stores the key/value pair in the database.
1322 If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
1323 will have the record number of the inserted key/value pair set.
1325 Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1328 =item B<$status = $X-E<gt>del($key [, $flags]) ;>
1330 Removes all key/value pairs with key C<$key> from the database.
1332 A return code of 1 means that the requested key was not in the
1335 R_CURSOR is the only valid flag at present.
1337 =item B<$status = $X-E<gt>fd ;>
1339 Returns the file descriptor for the underlying database.
1341 See L<Locking Databases> for an example of how to make use of the
1342 C<fd> method to lock your database.
1344 =item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
1346 This interface allows sequential retrieval from the database. See
1347 L<dbopen> for full details.
1349 Both the C<$key> and C<$value> parameters will be set to the key/value
1350 pair read from the database.
1352 The flags parameter is mandatory. The valid flag values are R_CURSOR,
1353 R_FIRST, R_LAST, R_NEXT and R_PREV.
1355 =item B<$status = $X-E<gt>sync([$flags]) ;>
1357 Flushes any cached buffers to disk.
1359 R_RECNOSYNC is the only valid flag at present.
1363 =head1 HINTS AND TIPS
1366 =head2 Locking Databases
1368 Concurrent access of a read-write database by several parties requires
1369 them all to use some kind of locking. Here's an example of Tom's that
1370 uses the I<fd> method to get the file descriptor, and then a careful
1371 open() to give something Perl will flock() for you. Run this repeatedly
1372 in the background to watch the locks granted in proper order.
1383 my($oldval, $fd, $db, %db, $value, $key);
1385 $key = shift || 'default';
1386 $value = shift || 'magic';
1390 $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0644)
1391 || die "dbcreat /tmp/foo.db $!";
1393 print "$$: db fd is $fd\n";
1394 open(DB_FH, "+<&=$fd") || die "dup $!";
1397 unless (flock (DB_FH, LOCK_SH | LOCK_NB)) {
1398 print "$$: CONTENTION; can't read during write update!
1399 Waiting for read lock ($!) ....";
1400 unless (flock (DB_FH, LOCK_SH)) { die "flock: $!" }
1402 print "$$: Read lock granted\n";
1404 $oldval = $db{$key};
1405 print "$$: Old value was $oldval\n";
1406 flock(DB_FH, LOCK_UN);
1408 unless (flock (DB_FH, LOCK_EX | LOCK_NB)) {
1409 print "$$: CONTENTION; must have exclusive lock!
1410 Waiting for write lock ($!) ....";
1411 unless (flock (DB_FH, LOCK_EX)) { die "flock: $!" }
1414 print "$$: Write lock granted\n";
1416 $db->sync; # to flush
1419 flock(DB_FH, LOCK_UN);
1423 print "$$: Updated db to $key=$value\n";
1425 =head2 Sharing Databases With C Applications
1427 There is no technical reason why a Berkeley DB database cannot be
1428 shared by both a Perl and a C application.
1430 The vast majority of problems that are reported in this area boil down
1431 to the fact that C strings are NULL terminated, whilst Perl strings are
1434 Here is a real example. Netscape 2.0 keeps a record of the locations you
1435 visit along with the time you last visited them in a DB_HASH database.
1436 This is usually stored in the file F<~/.netscape/history.db>. The key
1437 field in the database is the location string and the value field is the
1438 time the location was last visited stored as a 4 byte binary value.
1440 If you haven't already guessed, the location string is stored with a
1441 terminating NULL. This means you need to be careful when accessing the
1444 Here is a snippet of code that is loosely based on Tom Christiansen's
1445 I<ggh> script (available from your nearest CPAN archive in
1446 F<authors/id/TOMC/scripts/nshist.gz>).
1452 use vars qw( $dotdir $HISTORY %hist_db $href $binary_time $date ) ;
1453 $dotdir = $ENV{HOME} || $ENV{LOGNAME};
1455 $HISTORY = "$dotdir/.netscape/history.db";
1457 tie %hist_db, 'DB_File', $HISTORY
1458 or die "Cannot open $HISTORY: $!\n" ;;
1460 # Dump the complete database
1461 while ( ($href, $binary_time) = each %hist_db ) {
1463 # remove the terminating NULL
1464 $href =~ s/\x00$// ;
1466 # convert the binary time into a user friendly string
1467 $date = localtime unpack("V", $binary_time);
1468 print "$date $href\n" ;
1471 # check for the existence of a specific key
1472 # remember to add the NULL
1473 if ( $binary_time = $hist_db{"http://mox.perl.com/\x00"} ) {
1474 $date = localtime unpack("V", $binary_time) ;
1475 print "Last visited mox.perl.com on $date\n" ;
1478 print "Never visited mox.perl.com\n"
1483 =head2 The untie() Gotcha
1485 If you make use of the Berkeley DB API, it is I<very> strongly
1486 recommended that you read L<perltie/The untie Gotcha>.
1488 Even if you don't currently make use of the API interface, it is still
1491 Here is an example which illustrates the problem from a B<DB_File>
1500 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
1501 or die "Cannot tie first time: $!" ;
1507 tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1508 or die "Cannot tie second time: $!" ;
1512 When run, the script will produce this error message:
1514 Cannot tie second time: Invalid argument at bad.file line 14.
1516 Although the error message above refers to the second tie() statement
1517 in the script, the source of the problem is really with the untie()
1518 statement that precedes it.
1520 Having read L<perltie> you will probably have already guessed that the
1521 error is caused by the extra copy of the tied object stored in C<$X>.
1522 If you haven't, then the problem boils down to the fact that the
1523 B<DB_File> destructor, DESTROY, will not be called until I<all>
1524 references to the tied object are destroyed. Both the tied variable,
1525 C<%x>, and C<$X> above hold a reference to the object. The call to
1526 untie() will destroy the first, but C<$X> still holds a valid
1527 reference, so the destructor will not get called and the database file
1528 F<tst.fil> will remain open. The fact that Berkeley DB then reports the
1529 attempt to open a database that is alreday open via the catch-all
1530 "Invalid argument" doesn't help.
1532 If you run the script with the C<-w> flag the error message becomes:
1534 untie attempted while 1 inner references still exist at bad.file line 12.
1535 Cannot tie second time: Invalid argument at bad.file line 14.
1537 which pinpoints the real problem. Finally the script can now be
1538 modified to fix the original problem by destroying the API object
1547 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1551 =head1 COMMON QUESTIONS
1553 =head2 Why is there Perl source in my database?
1555 If you look at the contents of a database file created by DB_File,
1556 there can sometimes be part of a Perl script included in it.
1558 This happens because Berkeley DB uses dynamic memory to allocate
1559 buffers which will subsequently be written to the database file. Being
1560 dynamic, the memory could have been used for anything before DB
1561 malloced it. As Berkeley DB doesn't clear the memory once it has been
1562 allocated, the unused portions will contain random junk. In the case
1563 where a Perl script gets written to the database, the random junk will
1564 correspond to an area of dynamic memory that happened to be used during
1565 the compilation of the script.
1567 Unless you don't like the possibility of there being part of your Perl
1568 scripts embedded in a database file, this is nothing to worry about.
1570 =head2 How do I store complex data structures with DB_File?
1572 Although B<DB_File> cannot do this directly, there is a module which
1573 can layer transparently over B<DB_File> to accomplish this feat.
1575 Check out the MLDBM module, available on CPAN in the directory
1576 F<modules/by-module/MLDBM>.
1578 =head2 What does "Invalid Argument" mean?
1580 You will get this error message when one of the parameters in the
1581 C<tie> call is wrong. Unfortunately there are quite a few parameters to
1582 get wrong, so it can be difficult to figure out which one it is.
1584 Here are a couple of possibilities:
1590 Attempting to reopen a database without closing it.
1594 Using the O_WRONLY flag.
1598 =head2 What does "Bareword 'DB_File' not allowed" mean?
1600 You will encounter this particular error message when you have the
1601 C<strict 'subs'> pragma (or the full strict pragma) in your script.
1602 Consider this script:
1607 tie %x, DB_File, "filename" ;
1609 Running it produces the error in question:
1611 Bareword "DB_File" not allowed while "strict subs" in use
1613 To get around the error, place the word C<DB_File> in either single or
1614 double quotes, like this:
1616 tie %x, "DB_File", "filename" ;
1618 Although it might seem like a real pain, it is really worth the effort
1619 of having a C<use strict> in all your scripts.
1623 Moved to the Changes file.
1627 Some older versions of Berkeley DB had problems with fixed length
1628 records using the RECNO file format. This problem has been fixed since
1629 version 1.85 of Berkeley DB.
1631 I am sure there are bugs in the code. If you do find any, or can
1632 suggest any enhancements, I would welcome your comments.
1636 B<DB_File> comes with the standard Perl source distribution. Look in
1637 the directory F<ext/DB_File>. Given the amount of time between releases
1638 of Perl the version that ships with Perl is quite likely to be out of
1639 date, so the most recent version can always be found on CPAN (see
1640 L<perlmod/CPAN> for details), in the directory
1641 F<modules/by-module/DB_File>.
1643 This version of B<DB_File> will work with either version 1.x or 2.x of
1644 Berkeley DB, but is limited to the functionality provided by version 1.
1646 The official web site for Berkeley DB is
1647 F<http://www.sleepycat.com/db>. The ftp equivalent is
1648 F<ftp.sleepycat.com:/pub>. Both versions 1 and 2 of Berkeley DB are
1651 Alternatively, Berkeley DB version 1 is available at your nearest CPAN
1652 archive in F<src/misc/db.1.85.tar.gz>.
1654 If you are running IRIX, then get Berkeley DB version 1 from
1655 F<http://reality.sgi.com/ariel>. It has the patches necessary to
1656 compile properly on IRIX 5.3.
1660 Copyright (c) 1995-8 Paul Marquess. All rights reserved. This program
1661 is free software; you can redistribute it and/or modify it under the
1662 same terms as Perl itself.
1664 Although B<DB_File> is covered by the Perl license, the library it
1665 makes use of, namely Berkeley DB, is not. Berkeley DB has its own
1666 copyright and its own license. Please take the time to read it.
1668 Here are are few words taken from the Berkeley DB FAQ (at
1669 http://www.sleepycat.com) regarding the license:
1671 Do I have to license DB to use it in Perl scripts?
1673 No. The Berkeley DB license requires that software that uses
1674 Berkeley DB be freely redistributable. In the case of Perl, that
1675 software is Perl, and not your scripts. Any Perl scripts that you
1676 write are your property, including scripts that make use of
1677 Berkeley DB. Neither the Perl license nor the Berkeley DB license
1678 place any restriction on what you may do with them.
1680 If you are in any doubt about the license situation, contact either the
1681 Berkeley DB authors or the author of DB_File. See L<"AUTHOR"> for details.
1686 L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>
1690 The DB_File interface was written by Paul Marquess
1691 E<lt>pmarquess@bfsec.bt.co.ukE<gt>.
1692 Questions about the DB system itself may be addressed to
1693 E<lt>db@sleepycat.com<gt>.