[inseparable changes from match from perl-5.003_92 to perl-5.003_93]
[p5sagit/p5-mst-13.2.git] / ext / DB_File / DB_File.pm
CommitLineData
a0d0e21e 1# DB_File.pm -- Perl 5 interface to Berkeley DB
2#
3# written by Paul Marquess (pmarquess@bfsec.bt.co.uk)
778183f3 4# last modified 6th Feb 1997
5# version 1.11
36477c24 6#
a0b8c8c1 7# Copyright (c) 1995, 1996, 1997 Paul Marquess. All rights reserved.
36477c24 8# This program is free software; you can redistribute it and/or
9# modify it under the same terms as Perl itself.
10
8e07c86e 11
12package DB_File::HASHINFO ;
785da04d 13
610ab055 14require 5.003 ;
15
785da04d 16use strict;
8e07c86e 17use Carp;
88108326 18require Tie::Hash;
19@DB_File::HASHINFO::ISA = qw(Tie::Hash);
8e07c86e 20
88108326 21sub new
8e07c86e 22{
88108326 23 my $pkg = shift ;
24 my %x ;
25 tie %x, $pkg ;
26 bless \%x, $pkg ;
8e07c86e 27}
28
610ab055 29
88108326 30sub TIEHASH
31{
32 my $pkg = shift ;
33
36477c24 34 bless { VALID => { map {$_, 1}
35 qw( bsize ffactor nelem cachesize hash lorder)
36 },
37 GOT => {}
38 }, $pkg ;
88108326 39}
8e07c86e 40
610ab055 41
8e07c86e 42sub FETCH
43{
88108326 44 my $self = shift ;
45 my $key = shift ;
8e07c86e 46
36477c24 47 return $self->{GOT}{$key} if exists $self->{VALID}{$key} ;
88108326 48
49 my $pkg = ref $self ;
50 croak "${pkg}::FETCH - Unknown element '$key'" ;
8e07c86e 51}
52
53
54sub STORE
55{
88108326 56 my $self = shift ;
57 my $key = shift ;
58 my $value = shift ;
59
36477c24 60 if ( exists $self->{VALID}{$key} )
8e07c86e 61 {
36477c24 62 $self->{GOT}{$key} = $value ;
8e07c86e 63 return ;
64 }
65
88108326 66 my $pkg = ref $self ;
67 croak "${pkg}::STORE - Unknown element '$key'" ;
8e07c86e 68}
69
70sub DELETE
71{
88108326 72 my $self = shift ;
73 my $key = shift ;
74
36477c24 75 if ( exists $self->{VALID}{$key} )
8e07c86e 76 {
36477c24 77 delete $self->{GOT}{$key} ;
8e07c86e 78 return ;
79 }
80
88108326 81 my $pkg = ref $self ;
82 croak "DB_File::HASHINFO::DELETE - Unknown element '$key'" ;
8e07c86e 83}
84
88108326 85sub EXISTS
8e07c86e 86{
88108326 87 my $self = shift ;
88 my $key = shift ;
8e07c86e 89
36477c24 90 exists $self->{VALID}{$key} ;
8e07c86e 91}
92
88108326 93sub NotHere
8e07c86e 94{
18d2dc8c 95 my $self = shift ;
88108326 96 my $method = shift ;
8e07c86e 97
18d2dc8c 98 croak ref($self) . " does not define the method ${method}" ;
8e07c86e 99}
100
88108326 101sub DESTROY { undef %{$_[0]} }
18d2dc8c 102sub FIRSTKEY { my $self = shift ; $self->NotHere("FIRSTKEY") }
103sub NEXTKEY { my $self = shift ; $self->NotHere("NEXTKEY") }
104sub CLEAR { my $self = shift ; $self->NotHere("CLEAR") }
8e07c86e 105
106package DB_File::RECNOINFO ;
785da04d 107
88108326 108use strict ;
109
110@DB_File::RECNOINFO::ISA = qw(DB_File::HASHINFO) ;
8e07c86e 111
112sub TIEHASH
113{
88108326 114 my $pkg = shift ;
115
36477c24 116 bless { VALID => { map {$_, 1}
117 qw( bval cachesize psize flags lorder reclen bfname )
118 },
119 GOT => {},
120 }, $pkg ;
8e07c86e 121}
122
88108326 123package DB_File::BTREEINFO ;
8e07c86e 124
88108326 125use strict ;
8e07c86e 126
88108326 127@DB_File::BTREEINFO::ISA = qw(DB_File::HASHINFO) ;
8e07c86e 128
88108326 129sub TIEHASH
8e07c86e 130{
88108326 131 my $pkg = shift ;
132
36477c24 133 bless { VALID => { map {$_, 1}
134 qw( flags cachesize maxkeypage minkeypage psize
135 compare prefix lorder )
136 },
137 GOT => {},
138 }, $pkg ;
8e07c86e 139}
140
141
8e07c86e 142package DB_File ;
785da04d 143
144use strict;
145use vars qw($VERSION @ISA @EXPORT $AUTOLOAD $DB_BTREE $DB_HASH $DB_RECNO) ;
8e07c86e 146use Carp;
147
785da04d 148
778183f3 149$VERSION = "1.11" ;
8e07c86e 150
151#typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
88108326 152$DB_BTREE = new DB_File::BTREEINFO ;
153$DB_HASH = new DB_File::HASHINFO ;
154$DB_RECNO = new DB_File::RECNOINFO ;
8e07c86e 155
785da04d 156require Tie::Hash;
8e07c86e 157require Exporter;
158use AutoLoader;
159require DynaLoader;
785da04d 160@ISA = qw(Tie::Hash Exporter DynaLoader);
8e07c86e 161@EXPORT = qw(
162 $DB_BTREE $DB_HASH $DB_RECNO
88108326 163
8e07c86e 164 BTREEMAGIC
165 BTREEVERSION
166 DB_LOCK
167 DB_SHMEM
168 DB_TXN
169 HASHMAGIC
170 HASHVERSION
171 MAX_PAGE_NUMBER
172 MAX_PAGE_OFFSET
173 MAX_REC_NUMBER
174 RET_ERROR
175 RET_SPECIAL
176 RET_SUCCESS
177 R_CURSOR
178 R_DUP
179 R_FIRST
180 R_FIXEDLEN
181 R_IAFTER
182 R_IBEFORE
183 R_LAST
184 R_NEXT
185 R_NOKEY
186 R_NOOVERWRITE
187 R_PREV
188 R_RECNOSYNC
189 R_SETCURSOR
190 R_SNAPSHOT
191 __R_UNUSED
88108326 192
8e07c86e 193);
194
195sub AUTOLOAD {
785da04d 196 my($constname);
8e07c86e 197 ($constname = $AUTOLOAD) =~ s/.*:://;
785da04d 198 my $val = constant($constname, @_ ? $_[0] : 0);
8e07c86e 199 if ($! != 0) {
200 if ($! =~ /Invalid/) {
201 $AutoLoader::AUTOLOAD = $AUTOLOAD;
202 goto &AutoLoader::AUTOLOAD;
203 }
204 else {
785da04d 205 my($pack,$file,$line) = caller;
8e07c86e 206 croak "Your vendor has not defined DB macro $constname, used at $file line $line.
207";
208 }
209 }
210 eval "sub $AUTOLOAD { $val }";
211 goto &$AUTOLOAD;
212}
213
f6b705ef 214
215# import borrowed from IO::File
216# exports Fcntl constants if available.
217sub import {
218 my $pkg = shift;
219 my $callpkg = caller;
18d2dc8c 220 Exporter::export $pkg, $callpkg, @_;
f6b705ef 221 eval {
222 require Fcntl;
18d2dc8c 223 Exporter::export 'Fcntl', $callpkg, '/^O_/';
f6b705ef 224 };
225}
226
785da04d 227bootstrap DB_File $VERSION;
8e07c86e 228
229# Preloaded methods go here. Autoload methods go after __END__, and are
230# processed by the autosplit program.
231
610ab055 232sub TIEHASH
233{
234 my (@arg) = @_ ;
235
236 $arg[4] = tied %{ $arg[4] }
237 if @arg >= 5 && ref $arg[4] && $arg[4] =~ /=HASH/ && tied %{ $arg[4] } ;
238
239 DoTie_(@arg) ;
240}
241
242*TIEARRAY = \&TIEHASH ;
88108326 243
244sub get_dup
245{
246 croak "Usage: \$db->get_dup(key [,flag])\n"
247 unless @_ == 2 or @_ == 3 ;
248
249 my $db = shift ;
250 my $key = shift ;
251 my $flag = shift ;
f6b705ef 252 my $value = 0 ;
88108326 253 my $origkey = $key ;
254 my $wantarray = wantarray ;
f6b705ef 255 my %values = () ;
88108326 256 my @values = () ;
257 my $counter = 0 ;
f6b705ef 258 my $status = 0 ;
88108326 259
f6b705ef 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()) ) {
88108326 265
f6b705ef 266 # save the value or count number of matches
267 if ($wantarray) {
268 if ($flag)
269 { ++ $values{$value} }
270 else
271 { push (@values, $value) }
272 }
273 else
274 { ++ $counter }
88108326 275
88108326 276 }
277
f6b705ef 278 return ($wantarray ? ($flag ? %values : @values) : $counter) ;
88108326 279}
280
281
8e07c86e 2821;
283__END__
284
285=cut
3b35bae3 286
287=head1 NAME
288
289DB_File - Perl5 access to Berkeley DB
290
291=head1 SYNOPSIS
292
293 use DB_File ;
88108326 294
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 ;
760ac839 298
3b35bae3 299 $status = $X->del($key [, $flags]) ;
300 $status = $X->put($key, $value [, $flags]) ;
301 $status = $X->get($key, $value [, $flags]) ;
760ac839 302 $status = $X->seq($key, $value, $flags) ;
3b35bae3 303 $status = $X->sync([$flags]) ;
304 $status = $X->fd ;
760ac839 305
f6b705ef 306 # BTREE only
88108326 307 $count = $X->get_dup($key) ;
308 @list = $X->get_dup($key) ;
309 %list = $X->get_dup($key, 1) ;
310
f6b705ef 311 # RECNO only
312 $a = $X->length;
313 $a = $X->pop ;
314 $X->push(list);
315 $a = $X->shift;
316 $X->unshift(list);
317
3b35bae3 318 untie %hash ;
319 untie @array ;
320
321=head1 DESCRIPTION
322
8e07c86e 323B<DB_File> is a module which allows Perl programs to make use of the
324facilities provided by Berkeley DB. If you intend to use this
f6b705ef 325module you should really have a copy of the Berkeley DB manual pages at
8e07c86e 326hand. The interface defined here mirrors the Berkeley DB interface
327closely.
3b35bae3 328
8e07c86e 329Berkeley DB is a C library which provides a consistent interface to a
330number of database formats. B<DB_File> provides an interface to all
331three of the database types currently supported by Berkeley DB.
3b35bae3 332
333The file types are:
334
335=over 5
336
88108326 337=item B<DB_HASH>
3b35bae3 338
88108326 339This database type allows arbitrary key/value pairs to be stored in data
8e07c86e 340files. This is equivalent to the functionality provided by other
341hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
342the files created using DB_HASH are not compatible with any of the
343other packages mentioned.
3b35bae3 344
8e07c86e 345A default hashing algorithm, which will be adequate for most
346applications, is built into Berkeley DB. If you do need to use your own
347hashing algorithm it is possible to write your own in Perl and have
348B<DB_File> use it instead.
3b35bae3 349
88108326 350=item B<DB_BTREE>
351
352The btree format allows arbitrary key/value pairs to be stored in a
8e07c86e 353sorted, balanced binary tree.
3b35bae3 354
8e07c86e 355As with the DB_HASH format, it is possible to provide a user defined
356Perl routine to perform the comparison of keys. By default, though, the
357keys are stored in lexical order.
3b35bae3 358
88108326 359=item B<DB_RECNO>
3b35bae3 360
8e07c86e 361DB_RECNO allows both fixed-length and variable-length flat text files
362to be manipulated using the same key/value pair interface as in DB_HASH
363and DB_BTREE. In this case the key will consist of a record (line)
364number.
3b35bae3 365
366=back
367
368=head2 How does DB_File interface to Berkeley DB?
369
370B<DB_File> allows access to Berkeley DB files using the tie() mechanism
8e07c86e 371in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
372allows B<DB_File> to access Berkeley DB files using either an
373associative array (for DB_HASH & DB_BTREE file types) or an ordinary
374array (for the DB_RECNO file type).
3b35bae3 375
88108326 376In addition to the tie() interface, it is also possible to access most
377of the functions provided in the Berkeley DB API directly.
f6b705ef 378See L<THE API INTERFACE>.
3b35bae3 379
88108326 380=head2 Opening a Berkeley DB Database File
3b35bae3 381
8e07c86e 382Berkeley DB uses the function dbopen() to open or create a database.
f6b705ef 383Here is the C prototype for dbopen():
3b35bae3 384
385 DB*
386 dbopen (const char * file, int flags, int mode,
387 DBTYPE type, const void * openinfo)
388
389The parameter C<type> is an enumeration which specifies which of the 3
390interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
391Depending on which of these is actually chosen, the final parameter,
392I<openinfo> points to a data structure which allows tailoring of the
393specific interface method.
394
8e07c86e 395This interface is handled slightly differently in B<DB_File>. Here is
88108326 396an equivalent call using B<DB_File>:
3b35bae3 397
88108326 398 tie %array, 'DB_File', $filename, $flags, $mode, $DB_HASH ;
3b35bae3 399
8e07c86e 400The C<filename>, C<flags> and C<mode> parameters are the direct
401equivalent of their dbopen() counterparts. The final parameter $DB_HASH
402performs the function of both the C<type> and C<openinfo> parameters in
403dbopen().
3b35bae3 404
88108326 405In the example above $DB_HASH is actually a pre-defined reference to a
406hash object. B<DB_File> has three of these pre-defined references.
407Apart from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
3b35bae3 408
8e07c86e 409The keys allowed in each of these pre-defined references is limited to
410the names used in the equivalent C structure. So, for example, the
411$DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
88108326 412C<ffactor>, C<hash>, C<lorder> and C<nelem>.
413
414To change one of these elements, just assign to it like this:
415
416 $DB_HASH->{'cachesize'} = 10000 ;
417
418The three predefined variables $DB_HASH, $DB_BTREE and $DB_RECNO are
419usually adequate for most applications. If you do need to create extra
420instances of these objects, constructors are available for each file
421type.
422
423Here are examples of the constructors and the valid options available
424for DB_HASH, DB_BTREE and DB_RECNO respectively.
425
426 $a = new DB_File::HASHINFO ;
427 $a->{'bsize'} ;
428 $a->{'cachesize'} ;
429 $a->{'ffactor'};
430 $a->{'hash'} ;
431 $a->{'lorder'} ;
432 $a->{'nelem'} ;
433
434 $b = new DB_File::BTREEINFO ;
435 $b->{'flags'} ;
436 $b->{'cachesize'} ;
437 $b->{'maxkeypage'} ;
438 $b->{'minkeypage'} ;
439 $b->{'psize'} ;
440 $b->{'compare'} ;
441 $b->{'prefix'} ;
442 $b->{'lorder'} ;
443
444 $c = new DB_File::RECNOINFO ;
445 $c->{'bval'} ;
446 $c->{'cachesize'} ;
447 $c->{'psize'} ;
448 $c->{'flags'} ;
449 $c->{'lorder'} ;
450 $c->{'reclen'} ;
451 $c->{'bfname'} ;
452
453The values stored in the hashes above are mostly the direct equivalent
454of their C counterpart. Like their C counterparts, all are set to a
f6b705ef 455default values - that means you don't have to set I<all> of the
88108326 456values when you only want to change one. Here is an example:
457
458 $a = new DB_File::HASHINFO ;
459 $a->{'cachesize'} = 12345 ;
460 tie %y, 'DB_File', "filename", $flags, 0777, $a ;
461
36477c24 462A few of the options need extra discussion here. When used, the C
88108326 463equivalent of the keys C<hash>, C<compare> and C<prefix> store pointers
464to C functions. In B<DB_File> these keys are used to store references
465to Perl subs. Below are templates for each of the subs:
466
467 sub hash
468 {
469 my ($data) = @_ ;
470 ...
471 # return the hash value for $data
472 return $hash ;
473 }
3b35bae3 474
88108326 475 sub compare
476 {
477 my ($key, $key2) = @_ ;
478 ...
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) ;
483 }
3b35bae3 484
88108326 485 sub prefix
486 {
487 my ($key, $key2) = @_ ;
488 ...
489 # return number of bytes of $key2 which are
490 # necessary to determine that it is greater than $key1
491 return $bytes ;
492 }
3b35bae3 493
f6b705ef 494See L<Changing the BTREE sort order> for an example of using the
495C<compare> template.
88108326 496
36477c24 497If you are using the DB_RECNO interface and you intend making use of
498C<bval>, you should check out L<The bval option>.
499
88108326 500=head2 Default Parameters
501
502It is possible to omit some or all of the final 4 parameters in the
503call to C<tie> and let them take default values. As DB_HASH is the most
504common file format used, the call:
505
506 tie %A, "DB_File", "filename" ;
507
508is equivalent to:
509
18d2dc8c 510 tie %A, "DB_File", "filename", O_CREAT|O_RDWR, 0666, $DB_HASH ;
88108326 511
512It is also possible to omit the filename parameter as well, so the
513call:
514
515 tie %A, "DB_File" ;
516
517is equivalent to:
518
18d2dc8c 519 tie %A, "DB_File", undef, O_CREAT|O_RDWR, 0666, $DB_HASH ;
88108326 520
f6b705ef 521See L<In Memory Databases> for a discussion on the use of C<undef>
88108326 522in place of a filename.
523
f6b705ef 524=head2 In Memory Databases
525
526Berkeley 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>
528uses C<undef> instead of NULL to provide this functionality.
529
530=head1 DB_HASH
531
532The DB_HASH file format is probably the most commonly used of the three
533file formats that B<DB_File> supports. It is also very straightforward
534to use.
535
536=head2 A Simple Example.
537
538This example shows how to create a database, add key/value pairs to the
539database, delete keys/value pairs and finally how to enumerate the
540contents of the database.
541
610ab055 542 use strict ;
f6b705ef 543 use DB_File ;
610ab055 544 use vars qw( %h $k $v ) ;
f6b705ef 545
546 tie %h, "DB_File", "fruit", O_RDWR|O_CREAT, 0640, $DB_HASH
547 or die "Cannot open file 'fruit': $!\n";
548
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" ;
554
555 # Check for existence of a key
556 print "Banana Exists\n\n" if $h{"banana"} ;
557
558 # Delete a key/value pair.
559 delete $h{"apple"} ;
560
561 # print the contents of the file
562 while (($k, $v) = each %h)
563 { print "$k -> $v\n" }
564
565 untie %h ;
566
567here is the output:
568
569 Banana Exists
570
571 orange -> orange
572 tomato -> red
573 banana -> yellow
574
575Note that the like ordinary associative arrays, the order of the keys
576retrieved is in an apparently random order.
577
578=head1 DB_BTREE
579
580The DB_BTREE format is useful when you want to store data in a given
581order. By default the keys will be stored in lexical order, but as you
582will see from the example shown in the next section, it is very easy to
583define your own sorting function.
584
585=head2 Changing the BTREE sort order
586
587This script shows how to override the default sorting algorithm that
588BTREE uses. Instead of using the normal lexical ordering, a case
589insensitive compare function will be used.
88108326 590
610ab055 591 use strict ;
f6b705ef 592 use DB_File ;
610ab055 593
594 my %h ;
f6b705ef 595
596 sub Compare
597 {
598 my ($key1, $key2) = @_ ;
599 "\L$key1" cmp "\L$key2" ;
600 }
601
602 # specify the Perl sub that will do the comparison
603 $DB_BTREE->{'compare'} = \&Compare ;
604
605 tie %h, "DB_File", "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE
606 or die "Cannot open file 'tree': $!\n" ;
607
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' ;
613
614 # Delete
615 delete $h{"duck"} ;
616
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.
620 foreach (keys %h)
621 { print "$_\n" }
622
623 untie %h ;
624
625Here is the output from the code above.
626
627 mouse
628 Smith
629 Wall
630
631There are a few point to bear in mind if you want to change the
632ordering in a BTREE database:
633
634=over 5
635
636=item 1.
637
638The new compare function must be specified when you create the database.
639
640=item 2.
641
642You cannot change the ordering once the database has been created. Thus
643you must use the same compare function every time you access the
88108326 644database.
645
f6b705ef 646=back
647
648=head2 Handling duplicate keys
649
650The BTREE file type optionally allows a single key to be associated
651with an arbitrary number of values. This option is enabled by setting
652the flags element of C<$DB_BTREE> to R_DUP when creating the database.
653
88108326 654There are some difficulties in using the tied hash interface if you
655want to manipulate a BTREE database with duplicate keys. Consider this
656code:
657
610ab055 658 use strict ;
88108326 659 use DB_File ;
610ab055 660
661 use vars qw($filename %h ) ;
662
88108326 663 $filename = "tree" ;
664 unlink $filename ;
665
666 # Enable duplicate records
667 $DB_BTREE->{'flags'} = R_DUP ;
668
669 tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
670 or die "Cannot open $filename: $!\n";
671
672 # Add some key/value pairs to the file
673 $h{'Wall'} = 'Larry' ;
674 $h{'Wall'} = 'Brick' ; # Note the duplicate key
f6b705ef 675 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
88108326 676 $h{'Smith'} = 'John' ;
677 $h{'mouse'} = 'mickey' ;
678
679 # iterate through the associative array
680 # and print each key/value pair.
681 foreach (keys %h)
682 { print "$_ -> $h{$_}\n" }
683
f6b705ef 684 untie %h ;
685
88108326 686Here is the output:
687
688 Smith -> John
689 Wall -> Larry
690 Wall -> Larry
f6b705ef 691 Wall -> Larry
88108326 692 mouse -> mickey
693
f6b705ef 694As you can see 3 records have been successfully created with key C<Wall>
88108326 695- the only thing is, when they are retrieved from the database they
f6b705ef 696I<seem> to have the same value, namely C<Larry>. The problem is caused
697by the way that the associative array interface works. Basically, when
698the associative array interface is used to fetch the value associated
699with a given key, it will only ever retrieve the first value.
88108326 700
701Although it may not be immediately obvious from the code above, the
702associative array interface can be used to write values with duplicate
703keys, but it cannot be used to read them back from the database.
704
705The way to get around this problem is to use the Berkeley DB API method
706called C<seq>. This method allows sequential access to key/value
f6b705ef 707pairs. See L<THE API INTERFACE> for details of both the C<seq> method
708and the API in general.
88108326 709
710Here is the script above rewritten using the C<seq> API method.
711
610ab055 712 use strict ;
88108326 713 use DB_File ;
88108326 714
610ab055 715 use vars qw($filename $x %h $status $key $value) ;
716
88108326 717 $filename = "tree" ;
718 unlink $filename ;
719
720 # Enable duplicate records
721 $DB_BTREE->{'flags'} = R_DUP ;
722
723 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
724 or die "Cannot open $filename: $!\n";
725
726 # Add some key/value pairs to the file
727 $h{'Wall'} = 'Larry' ;
728 $h{'Wall'} = 'Brick' ; # Note the duplicate key
f6b705ef 729 $h{'Wall'} = 'Brick' ; # Note the duplicate key and value
88108326 730 $h{'Smith'} = 'John' ;
731 $h{'mouse'} = 'mickey' ;
732
f6b705ef 733 # iterate through the btree using seq
88108326 734 # and print each key/value pair.
610ab055 735 $key = $value = 0 ;
f6b705ef 736 for ($status = $x->seq($key, $value, R_FIRST) ;
737 $status == 0 ;
738 $status = $x->seq($key, $value, R_NEXT) )
88108326 739 { print "$key -> $value\n" }
740
741 undef $x ;
742 untie %h ;
743
744that prints:
745
746 Smith -> John
747 Wall -> Brick
f6b705ef 748 Wall -> Brick
88108326 749 Wall -> Larry
750 mouse -> mickey
751
f6b705ef 752This time we have got all the key/value pairs, including the multiple
88108326 753values associated with the key C<Wall>.
754
f6b705ef 755=head2 The get_dup method.
756
757B<DB_File> comes with a utility method, called C<get_dup>, to assist in
88108326 758reading duplicate values from BTREE databases. The method can take the
759following forms:
760
761 $count = $x->get_dup($key) ;
762 @list = $x->get_dup($key) ;
763 %list = $x->get_dup($key, 1) ;
764
765In a scalar context the method returns the number of values associated
766with the key, C<$key>.
767
768In list context, it returns all the values which match C<$key>. Note
f6b705ef 769that the values will be returned in an apparently random order.
88108326 770
f6b705ef 771In list context, if the second parameter is present and evaluates TRUE,
772the method returns an associative array. The keys of the associative
773array correspond to the the values that matched in the BTREE and the
774values of the array are a count of the number of times that particular
775value occurred in the BTREE.
88108326 776
f6b705ef 777So assuming the database created above, we can use C<get_dup> like
88108326 778this:
779
610ab055 780 my $cnt = $x->get_dup("Wall") ;
88108326 781 print "Wall occurred $cnt times\n" ;
782
610ab055 783 my %hash = $x->get_dup("Wall", 1) ;
88108326 784 print "Larry is there\n" if $hash{'Larry'} ;
f6b705ef 785 print "There are $hash{'Brick'} Brick Walls\n" ;
88108326 786
610ab055 787 my @list = $x->get_dup("Wall") ;
88108326 788 print "Wall => [@list]\n" ;
789
f6b705ef 790 @list = $x->get_dup("Smith") ;
88108326 791 print "Smith => [@list]\n" ;
792
f6b705ef 793 @list = $x->get_dup("Dog") ;
88108326 794 print "Dog => [@list]\n" ;
795
796
797and it will print:
798
f6b705ef 799 Wall occurred 3 times
88108326 800 Larry is there
f6b705ef 801 There are 2 Brick Walls
802 Wall => [Brick Brick Larry]
88108326 803 Smith => [John]
804 Dog => []
3b35bae3 805
f6b705ef 806=head2 Matching Partial Keys
807
808The BTREE interface has a feature which allows partial keys to be
809matched. This functionality is I<only> available when the C<seq> method
810is used along with the R_CURSOR flag.
811
812 $x->seq($key, $value, R_CURSOR) ;
813
814Here is the relevant quote from the dbopen man page where it defines
815the use of the R_CURSOR flag with seq:
816
f6b705ef 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.
821
f6b705ef 822In the example script below, the C<match> sub uses this feature to find
823and print the first matching key/value pair given a partial key.
824
610ab055 825 use strict ;
f6b705ef 826 use DB_File ;
827 use Fcntl ;
610ab055 828
829 use vars qw($filename $x %h $st $key $value) ;
f6b705ef 830
831 sub match
832 {
833 my $key = shift ;
610ab055 834 my $value = 0;
f6b705ef 835 my $orig_key = $key ;
836 $x->seq($key, $value, R_CURSOR) ;
837 print "$orig_key\t-> $key\t-> $value\n" ;
838 }
839
840 $filename = "tree" ;
841 unlink $filename ;
842
843 $x = tie %h, "DB_File", $filename, O_RDWR|O_CREAT, 0640, $DB_BTREE
844 or die "Cannot open $filename: $!\n";
845
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' ;
851
852
610ab055 853 $key = $value = 0 ;
f6b705ef 854 print "IN ORDER\n" ;
855 for ($st = $x->seq($key, $value, R_FIRST) ;
856 $st == 0 ;
857 $st = $x->seq($key, $value, R_NEXT) )
858
859 { print "$key -> $value\n" }
860
861 print "\nPARTIAL MATCH\n" ;
862
863 match "Wa" ;
864 match "A" ;
865 match "a" ;
866
867 undef $x ;
868 untie %h ;
869
870Here is the output:
871
872 IN ORDER
873 Smith -> John
874 Wall -> Larry
875 Walls -> Brick
876 mouse -> mickey
877
878 PARTIAL MATCH
879 Wa -> Wall -> Larry
880 A -> Smith -> John
881 a -> mouse -> mickey
882
883=head1 DB_RECNO
884
885DB_RECNO provides an interface to flat text files. Both variable and
886fixed length records are supported.
3b35bae3 887
88108326 888In order to make RECNO more compatible with Perl the array offset for
889all RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
3b35bae3 890
88108326 891As with normal Perl arrays, a RECNO array can be accessed using
892negative 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
894the start of the array will raise a fatal run-time error.
3b35bae3 895
36477c24 896=head2 The bval option
897
898The operation of the bval option warrants some discussion. Here is the
899definition of bval from the Berkeley DB 1.85 recno manual page:
900
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
906 padded with spaces.
907
908The second sentence is wrong. In actual fact bval will only default to
909C<"\n"> when the openinfo parameter in dbopen is NULL. If a non-NULL
910openinfo parameter is used at all, the value that happens to be in bval
911will be used. That means you always have to specify bval when making
912use of any of the options in the openinfo parameter. This documentation
913error will be fixed in the next release of Berkeley DB.
914
915That clarifies the situation with regards Berkeley DB itself. What
916about B<DB_File>? Well, the behavior defined in the quote above is
917quite useful, so B<DB_File> conforms it.
918
919That means that you can specify other options (e.g. cachesize) and
920still have bval default to C<"\n"> for variable length records, and
921space for fixed length records.
922
f6b705ef 923=head2 A Simple Example
3b35bae3 924
f6b705ef 925Here is a simple example that uses RECNO.
926
610ab055 927 use strict ;
f6b705ef 928 use DB_File ;
f6b705ef 929
610ab055 930 my @h ;
f6b705ef 931 tie @h, "DB_File", "text", O_RDWR|O_CREAT, 0640, $DB_RECNO
932 or die "Cannot open file 'text': $!\n" ;
933
934 # Add a few key/value pairs to the file
935 $h[0] = "orange" ;
936 $h[1] = "blue" ;
937 $h[2] = "yellow" ;
938
939 # Check for existence of a key
940 print "Element 1 Exists with value $h[1]\n" if $h[1] ;
941
942 # use a negative index
943 print "The last element is $h[-1]\n" ;
944 print "The 2nd last element is $h[-2]\n" ;
945
946 untie @h ;
3b35bae3 947
f6b705ef 948Here is the output from the script:
949
950
951 Element 1 Exists with value blue
952 The last element is yellow
953 The 2nd last element is blue
954
955=head2 Extra Methods
956
957As you can see from the example above, the tied array interface is
958quite limited. To make the interface more useful, a number of methods
959are supplied with B<DB_File> to simulate the standard array operations
960that are not currently implemented in Perl's tied array interface. All
961these methods are accessed via the object returned from the tie call.
962
963Here are the methods:
964
965=over 5
3b35bae3 966
f6b705ef 967=item B<$X-E<gt>push(list) ;>
968
969Pushes the elements of C<list> to the end of the array.
970
971=item B<$value = $X-E<gt>pop ;>
972
973Removes and returns the last element of the array.
974
975=item B<$X-E<gt>shift>
976
977Removes and returns the first element of the array.
978
979=item B<$X-E<gt>unshift(list) ;>
980
981Pushes the elements of C<list> to the start of the array.
982
983=item B<$X-E<gt>length>
984
985Returns the number of elements in the array.
986
987=back
988
989=head2 Another Example
990
991Here is a more complete example that makes use of some of the methods
992described above. It also makes use of the API interface directly (see
993L<THE API INTERFACE>).
994
995 use strict ;
996 use vars qw(@h $H $file $i) ;
997 use DB_File ;
998 use Fcntl ;
999
1000 $file = "text" ;
1001
1002 unlink $file ;
1003
1004 $H = tie @h, "DB_File", $file, O_RDWR|O_CREAT, 0640, $DB_RECNO
1005 or die "Cannot open file $file: $!\n" ;
1006
1007 # first create a text file to play with
1008 $h[0] = "zero" ;
1009 $h[1] = "one" ;
1010 $h[2] = "two" ;
1011 $h[3] = "three" ;
1012 $h[4] = "four" ;
1013
1014
1015 # Print the records in order.
1016 #
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.
1020
1021 print "\nORIGINAL\n" ;
1022 foreach $i (0 .. $H->length - 1) {
1023 print "$i: $h[$i]\n" ;
1024 }
1025
1026 # use the push & pop methods
1027 $a = $H->pop ;
1028 $H->push("last") ;
1029 print "\nThe last record was [$a]\n" ;
1030
1031 # and the shift & unshift methods
1032 $a = $H->shift ;
1033 $H->unshift("first") ;
1034 print "The first record was [$a]\n" ;
1035
1036 # Use the API to add a new record after record 2.
1037 $i = 2 ;
1038 $H->put($i, "Newbie", R_IAFTER) ;
1039
1040 # and a new record before record 1.
1041 $i = 1 ;
1042 $H->put($i, "New One", R_IBEFORE) ;
1043
1044 # delete record 3
1045 $H->del(3) ;
1046
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" }
1051
1052 # same again, but use the API functions instead
1053 print "\nREVERSE again\n" ;
610ab055 1054 my ($s, $k, $v) = (0, 0, 0) ;
f6b705ef 1055 for ($s = $H->seq($k, $v, R_LAST) ;
1056 $s == 0 ;
1057 $s = $H->seq($k, $v, R_PREV))
1058 { print "$k: $v\n" }
1059
1060 undef $H ;
1061 untie @h ;
1062
1063and this is what it outputs:
1064
1065 ORIGINAL
1066 0: zero
1067 1: one
1068 2: two
1069 3: three
1070 4: four
1071
1072 The last record was [four]
1073 The first record was [zero]
1074
1075 REVERSE
1076 5: last
1077 4: three
1078 3: Newbie
1079 2: one
1080 1: New One
1081 0: first
1082
1083 REVERSE again
1084 5: last
1085 4: three
1086 3: Newbie
1087 2: one
1088 1: New One
1089 0: first
1090
1091Notes:
1092
1093=over 5
1094
1095=item 1.
1096
1097Rather than iterating through the array, C<@h> like this:
1098
1099 foreach $i (@h)
1100
1101it is necessary to use either this:
1102
1103 foreach $i (0 .. $H->length - 1)
1104
1105or this:
1106
1107 for ($a = $H->get($k, $v, R_FIRST) ;
1108 $a == 0 ;
1109 $a = $H->get($k, $v, R_NEXT) )
1110
1111=item 2.
1112
1113Notice that both times the C<put> method was used the record index was
1114specified using a variable, C<$i>, rather than the literal value
1115itself. This is because C<put> will return the record number of the
1116inserted line via that parameter.
1117
1118=back
1119
1120=head1 THE API INTERFACE
3b35bae3 1121
1122As well as accessing Berkeley DB using a tied hash or array, it is also
88108326 1123possible to make direct use of most of the API functions defined in the
8e07c86e 1124Berkeley DB documentation.
3b35bae3 1125
88108326 1126To do this you need to store a copy of the object returned from the tie.
3b35bae3 1127
88108326 1128 $db = tie %hash, "DB_File", "filename" ;
3b35bae3 1129
8e07c86e 1130Once you have done that, you can access the Berkeley DB API functions
88108326 1131as B<DB_File> methods directly like this:
3b35bae3 1132
1133 $db->put($key, $value, R_NOOVERWRITE) ;
1134
88108326 1135B<Important:> If you have saved a copy of the object returned from
1136C<tie>, the underlying database file will I<not> be closed until both
1137the tied variable is untied and all copies of the saved object are
610ab055 1138destroyed.
88108326 1139
1140 use DB_File ;
1141 $db = tie %hash, "DB_File", "filename"
1142 or die "Cannot tie filename: $!" ;
1143 ...
1144 undef $db ;
1145 untie %hash ;
1146
2ae324a7 1147See L<The untie Gotcha> for more details.
778183f3 1148
88108326 1149All the functions defined in L<dbopen> are available except for
1150close() and dbopen() itself. The B<DB_File> method interface to the
1151supported functions have been implemented to mirror the way Berkeley DB
1152works whenever possible. In particular note that:
1153
1154=over 5
1155
1156=item *
1157
1158The methods return a status value. All return 0 on success.
1159All return -1 to signify an error and set C<$!> to the exact
1160error code. The return code 1 generally (but not always) means that the
1161key specified did not exist in the database.
1162
1163Other return codes are defined. See below and in the Berkeley DB
1164documentation for details. The Berkeley DB documentation should be used
1165as the definitive source.
1166
1167=item *
3b35bae3 1168
88108326 1169Whenever a Berkeley DB function returns data via one of its parameters,
1170the equivalent B<DB_File> method does exactly the same.
3b35bae3 1171
88108326 1172=item *
1173
1174If you are careful, it is possible to mix API calls with the tied
1175hash/array interface in the same piece of code. Although only a few of
1176the methods used to implement the tied interface currently make use of
1177the cursor, you should always assume that the cursor has been changed
1178any time the tied hash/array interface is used. As an example, this
1179code will probably not do what you expect:
1180
1181 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1182 or die "Cannot tie $filename: $!" ;
1183
1184 # Get the first key/value pair and set the cursor
1185 $X->seq($key, $value, R_FIRST) ;
1186
1187 # this line will modify the cursor
1188 $count = scalar keys %x ;
1189
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) ;
1193
1194The code above can be rearranged to get around the problem, like this:
1195
1196 $X = tie %x, 'DB_File', $filename, O_RDWR|O_CREAT, 0777, $DB_BTREE
1197 or die "Cannot tie $filename: $!" ;
1198
1199 # this line will modify the cursor
1200 $count = scalar keys %x ;
1201
1202 # Get the first key/value pair and set the cursor
1203 $X->seq($key, $value, R_FIRST) ;
1204
1205 # Get the second key/value pair.
1206 # worked this time.
1207 $X->seq($key, $value, R_NEXT) ;
1208
1209=back
1210
1211All the constants defined in L<dbopen> for use in the flags parameters
1212in the methods defined below are also available. Refer to the Berkeley
1213DB documentation for the precise meaning of the flags values.
1214
1215Below is a list of the methods available.
3b35bae3 1216
1217=over 5
1218
f6b705ef 1219=item B<$status = $X-E<gt>get($key, $value [, $flags]) ;>
88108326 1220
1221Given a key (C<$key>) this method reads the value associated with it
1222from the database. The value read from the database is returned in the
1223C<$value> parameter.
3b35bae3 1224
88108326 1225If the key does not exist the method returns 1.
3b35bae3 1226
88108326 1227No flags are currently defined for this method.
3b35bae3 1228
f6b705ef 1229=item B<$status = $X-E<gt>put($key, $value [, $flags]) ;>
3b35bae3 1230
88108326 1231Stores the key/value pair in the database.
1232
1233If you use either the R_IAFTER or R_IBEFORE flags, the C<$key> parameter
8e07c86e 1234will have the record number of the inserted key/value pair set.
3b35bae3 1235
88108326 1236Valid flags are R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE and
1237R_SETCURSOR.
1238
f6b705ef 1239=item B<$status = $X-E<gt>del($key [, $flags]) ;>
3b35bae3 1240
88108326 1241Removes all key/value pairs with key C<$key> from the database.
3b35bae3 1242
88108326 1243A return code of 1 means that the requested key was not in the
1244database.
3b35bae3 1245
88108326 1246R_CURSOR is the only valid flag at present.
3b35bae3 1247
f6b705ef 1248=item B<$status = $X-E<gt>fd ;>
3b35bae3 1249
88108326 1250Returns the file descriptor for the underlying database.
3b35bae3 1251
f6b705ef 1252See L<Locking Databases> for an example of how to make use of the
88108326 1253C<fd> method to lock your database.
3b35bae3 1254
f6b705ef 1255=item B<$status = $X-E<gt>seq($key, $value, $flags) ;>
3b35bae3 1256
88108326 1257This interface allows sequential retrieval from the database. See
1258L<dbopen> for full details.
1259
1260Both the C<$key> and C<$value> parameters will be set to the key/value
1261pair read from the database.
1262
1263The flags parameter is mandatory. The valid flag values are R_CURSOR,
1264R_FIRST, R_LAST, R_NEXT and R_PREV.
1265
f6b705ef 1266=item B<$status = $X-E<gt>sync([$flags]) ;>
88108326 1267
1268Flushes any cached buffers to disk.
1269
1270R_RECNOSYNC is the only valid flag at present.
3b35bae3 1271
1272=back
1273
f6b705ef 1274=head1 HINTS AND TIPS
3b35bae3 1275
3b35bae3 1276
cb1a09d0 1277=head2 Locking Databases
3b35bae3 1278
cb1a09d0 1279Concurrent access of a read-write database by several parties requires
1280them all to use some kind of locking. Here's an example of Tom's that
1281uses the I<fd> method to get the file descriptor, and then a careful
1282open() to give something Perl will flock() for you. Run this repeatedly
1283in the background to watch the locks granted in proper order.
3b35bae3 1284
cb1a09d0 1285 use DB_File;
1286
1287 use strict;
1288
1289 sub LOCK_SH { 1 }
1290 sub LOCK_EX { 2 }
1291 sub LOCK_NB { 4 }
1292 sub LOCK_UN { 8 }
1293
1294 my($oldval, $fd, $db, %db, $value, $key);
1295
1296 $key = shift || 'default';
1297 $value = shift || 'magic';
1298
1299 $value .= " $$";
1300
1301 $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0644)
1302 || die "dbcreat /tmp/foo.db $!";
1303 $fd = $db->fd;
1304 print "$$: db fd is $fd\n";
1305 open(DB_FH, "+<&=$fd") || die "dup $!";
1306
1307
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: $!" }
1312 }
1313 print "$$: Read lock granted\n";
1314
1315 $oldval = $db{$key};
1316 print "$$: Old value was $oldval\n";
1317 flock(DB_FH, LOCK_UN);
1318
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: $!" }
1323 }
1324
1325 print "$$: Write lock granted\n";
1326 $db{$key} = $value;
610ab055 1327 $db->sync; # to flush
cb1a09d0 1328 sleep 10;
1329
1330 flock(DB_FH, LOCK_UN);
88108326 1331 undef $db;
cb1a09d0 1332 untie %db;
1333 close(DB_FH);
1334 print "$$: Updated db to $key=$value\n";
1335
f6b705ef 1336=head2 Sharing databases with C applications
1337
1338There is no technical reason why a Berkeley DB database cannot be
1339shared by both a Perl and a C application.
1340
1341The vast majority of problems that are reported in this area boil down
1342to the fact that C strings are NULL terminated, whilst Perl strings are
1343not.
1344
1345Here is a real example. Netscape 2.0 keeps a record of the locations you
1346visit along with the time you last visited them in a DB_HASH database.
1347This is usually stored in the file F<~/.netscape/history.db>. The key
1348field in the database is the location string and the value field is the
1349time the location was last visited stored as a 4 byte binary value.
1350
1351If you haven't already guessed, the location string is stored with a
1352terminating NULL. This means you need to be careful when accessing the
1353database.
1354
1355Here is a snippet of code that is loosely based on Tom Christiansen's
1356I<ggh> script (available from your nearest CPAN archive in
1357F<authors/id/TOMC/scripts/nshist.gz>).
1358
610ab055 1359 use strict ;
f6b705ef 1360 use DB_File ;
1361 use Fcntl ;
f6b705ef 1362
610ab055 1363 use vars qw( $dotdir $HISTORY %hist_db $href $binary_time $date ) ;
f6b705ef 1364 $dotdir = $ENV{HOME} || $ENV{LOGNAME};
1365
1366 $HISTORY = "$dotdir/.netscape/history.db";
1367
1368 tie %hist_db, 'DB_File', $HISTORY
1369 or die "Cannot open $HISTORY: $!\n" ;;
1370
1371 # Dump the complete database
1372 while ( ($href, $binary_time) = each %hist_db ) {
1373
1374 # remove the terminating NULL
1375 $href =~ s/\x00$// ;
1376
1377 # convert the binary time into a user friendly string
1378 $date = localtime unpack("V", $binary_time);
1379 print "$date $href\n" ;
1380 }
1381
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" ;
1387 }
1388 else {
1389 print "Never visited mox.perl.com\n"
1390 }
1391
1392 untie %hist_db ;
1393
778183f3 1394=head2 The untie gotcha
1395
1396If you make use of the Berkeley DB API, it is is I<very> strongly
1397recommended that you read L<perltie/The untie gotcha>.
1398
1399Even if you don't currently make use of the API interface, it is still
1400worth reading it.
1401
1402Here is an example which illustrates the problem from a B<DB_File>
1403perspective:
1404
1405 use DB_File ;
1406 use Fcntl ;
1407
1408 my %x ;
1409 my $X ;
1410
1411 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_TRUNC
1412 or die "Cannot tie first time: $!" ;
1413
1414 $x{123} = 456 ;
1415
1416 untie %x ;
1417
1418 tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1419 or die "Cannot tie second time: $!" ;
1420
1421 untie %x ;
1422
1423When run, the script will produce this error message:
1424
1425 Cannot tie second time: Invalid argument at bad.file line 14.
1426
1427Although the error message above refers to the second tie() statement
1428in the script, the source of the problem is really with the untie()
1429statement that precedes it.
1430
1431Having read L<perltie> you will probably have already guessed that the
1432error is caused by the extra copy of the tied object stored in C<$X>.
1433If you haven't, then the problem boils down to the fact that the
1434B<DB_File> destructor, DESTROY, will not be called until I<all>
1435references to the tied object are destroyed. Both the tied variable,
1436C<%x>, and C<$X> above hold a reference to the object. The call to
1437untie() will destroy the first, but C<$X> still holds a valid
1438reference, so the destructor will not get called and the database file
1439F<tst.fil> will remain open. The fact that Berkeley DB then reports the
1440attempt to open a database that is alreday open via the catch-all
1441"Invalid argument" doesn't help.
1442
1443If you run the script with the C<-w> flag the error message becomes:
1444
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.
1447
1448which pinpoints the real problem. Finally the script can now be
1449modified to fix the original problem by destroying the API object
1450before the untie:
1451
1452 ...
1453 $x{123} = 456 ;
1454
1455 undef $X ;
1456 untie %x ;
1457
1458 $X = tie %x, 'DB_File', 'tst.fil' , O_RDWR|O_CREAT
1459 ...
1460
f6b705ef 1461
1462=head1 COMMON QUESTIONS
1463
1464=head2 Why is there Perl source in my database?
1465
1466If you look at the contents of a database file created by DB_File,
1467there can sometimes be part of a Perl script included in it.
1468
1469This happens because Berkeley DB uses dynamic memory to allocate
1470buffers which will subsequently be written to the database file. Being
1471dynamic, the memory could have been used for anything before DB
1472malloced it. As Berkeley DB doesn't clear the memory once it has been
1473allocated, the unused portions will contain random junk. In the case
1474where a Perl script gets written to the database, the random junk will
1475correspond to an area of dynamic memory that happened to be used during
1476the compilation of the script.
1477
1478Unless you don't like the possibility of there being part of your Perl
1479scripts embedded in a database file, this is nothing to worry about.
1480
1481=head2 How do I store complex data structures with DB_File?
1482
1483Although B<DB_File> cannot do this directly, there is a module which
1484can layer transparently over B<DB_File> to accomplish this feat.
1485
1486Check out the MLDBM module, available on CPAN in the directory
1487F<modules/by-module/MLDBM>.
1488
1489=head2 What does "Invalid Argument" mean?
1490
1491You will get this error message when one of the parameters in the
1492C<tie> call is wrong. Unfortunately there are quite a few parameters to
1493get wrong, so it can be difficult to figure out which one it is.
1494
1495Here are a couple of possibilities:
1496
1497=over 5
1498
1499=item 1.
1500
610ab055 1501Attempting to reopen a database without closing it.
f6b705ef 1502
1503=item 2.
1504
1505Using the O_WRONLY flag.
1506
1507=back
1508
1509=head2 What does "Bareword 'DB_File' not allowed" mean?
1510
1511You will encounter this particular error message when you have the
1512C<strict 'subs'> pragma (or the full strict pragma) in your script.
1513Consider this script:
1514
1515 use strict ;
1516 use DB_File ;
1517 use vars qw(%x) ;
1518 tie %x, DB_File, "filename" ;
1519
1520Running it produces the error in question:
1521
1522 Bareword "DB_File" not allowed while "strict subs" in use
1523
1524To get around the error, place the word C<DB_File> in either single or
1525double quotes, like this:
1526
1527 tie %x, "DB_File", "filename" ;
1528
1529Although it might seem like a real pain, it is really worth the effort
1530of having a C<use strict> in all your scripts.
1531
cb1a09d0 1532=head1 HISTORY
1533
1534=over
1535
1536=item 0.1
3b35bae3 1537
1538First Release.
1539
cb1a09d0 1540=item 0.2
3b35bae3 1541
1542When B<DB_File> is opening a database file it no longer terminates the
1543process if I<dbopen> returned an error. This allows file protection
1544errors to be caught at run time. Thanks to Judith Grass
cb1a09d0 1545E<lt>grass@cybercash.comE<gt> for spotting the bug.
3b35bae3 1546
cb1a09d0 1547=item 0.3
8e07c86e 1548
1549Added prototype support for multiple btree compare callbacks.
1550
cb1a09d0 1551=item 1.0
8e07c86e 1552
1553B<DB_File> has been in use for over a year. To reflect that, the
1554version number has been incremented to 1.0.
1555
1556Added complete support for multiple concurrent callbacks.
1557
1558Using the I<push> method on an empty list didn't work properly. This
1559has been fixed.
1560
cb1a09d0 1561=item 1.01
4633a7c4 1562
1563Fixed a core dump problem with SunOS.
1564
1565The return value from TIEHASH wasn't set to NULL when dbopen returned
1566an error.
1567
88108326 1568=item 1.02
1569
f6b705ef 1570Merged OS/2 specific code into DB_File.xs
88108326 1571
1572Removed some redundant code in DB_File.xs.
1573
1574Documentation update.
1575
1576Allow negative subscripts with RECNO interface.
1577
1578Changed the default flags from O_RDWR to O_CREAT|O_RDWR.
1579
1580The example code which showed how to lock a database needed a call to
1581C<sync> added. Without it the resultant database file was empty.
1582
f6b705ef 1583Added get_dup method.
88108326 1584
f6b705ef 1585=item 1.03
1586
1587Documentation update.
3b35bae3 1588
f6b705ef 1589B<DB_File> now imports the constants (O_RDWR, O_CREAT etc.) from Fcntl
1590automatically.
3b35bae3 1591
f6b705ef 1592The standard hash function C<exists> is now supported.
1593
1594Modified the behavior of get_dup. When it returns an associative
1595array, the value is the count of the number of matching BTREE values.
3b35bae3 1596
610ab055 1597=item 1.04
1598
1599Minor documentation changes.
1600
1601Fixed a bug in hash_cb. Patches supplied by Dave Hammen,
1602E<lt>hammen@gothamcity.jsc.nasa.govE<gt>.
1603
1604Fixed a bug with the constructors for DB_File::HASHINFO,
1605DB_File::BTREEINFO and DB_File::RECNOINFO. Also tidied up the
1606constructors to make them C<-w> clean.
1607
1608Reworked part of the test harness to be more locale friendly.
1609
1610=item 1.05
1611
1612Made all scripts in the documentation C<strict> and C<-w> clean.
1613
1614Added logic to F<DB_File.xs> to allow the module to be built after Perl
1615is installed.
1616
ff68c719 1617=item 1.06
1618
1619Minor namespace cleanup: Localized C<PrintBtree>.
1620
36477c24 1621=item 1.07
1622
1623Fixed bug with RECNO, where bval wasn't defaulting to "\n".
1624
1625=item 1.08
1626
1627Documented operation of bval.
1628
18d2dc8c 1629=item 1.09
1630
1631Minor bug fix in DB_File::HASHINFO, DB_File::RECNOINFO and
1632DB_File::BTREEINFO.
1633
1634Changed default mode to 0666.
1635
a0b8c8c1 1636=item 1.10
1637
1638Fixed fd method so that it still returns -1 for in-memory files when db
16391.86 is used.
1640
778183f3 1641=item 1.11
1642
1643Documented the untie gotcha.
1644
610ab055 1645=back
1646
3b35bae3 1647=head1 BUGS
1648
8e07c86e 1649Some older versions of Berkeley DB had problems with fixed length
1650records using the RECNO file format. The newest version at the time of
1651writing was 1.85 - this seems to have fixed the problems with RECNO.
3b35bae3 1652
8e07c86e 1653I am sure there are bugs in the code. If you do find any, or can
1654suggest any enhancements, I would welcome your comments.
3b35bae3 1655
1656=head1 AVAILABILITY
1657
f6b705ef 1658B<DB_File> comes with the standard Perl source distribution. Look in
1659the directory F<ext/DB_File>.
1660
cb1a09d0 1661Berkeley DB is available at your nearest CPAN archive (see
1662L<perlmod/"CPAN"> for a list) in F<src/misc/db.1.85.tar.gz>, or via the
610ab055 1663host F<ftp.cs.berkeley.edu> in F</ucb/4bsd/db.tar.gz>. Alternatively,
1664check out the Berkeley DB home page at F<http://www.bostic.com/db>. It
1665is I<not> under the GPL.
3b35bae3 1666
88108326 1667If you are running IRIX, then get Berkeley DB from
1668F<http://reality.sgi.com/ariel>. It has the patches necessary to
1669compile properly on IRIX 5.3.
1670
a0b8c8c1 1671As of January 1997, version 1.86 of Berkeley DB is available from the
1672Berkeley DB home page. Although this release does fix a number of bugs
778183f3 1673that were present in 1.85 you should be aware of the following
a0b8c8c1 1674information (taken from the Berkeley DB home page) before you consider
1675using it:
1676
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
1680 2.0 is available.
1681
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.
1688
1689
3b35bae3 1690=head1 SEE ALSO
1691
1692L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>
1693
3b35bae3 1694=head1 AUTHOR
1695
8e07c86e 1696The DB_File interface was written by Paul Marquess
88108326 1697E<lt>pmarquess@bfsec.bt.co.ukE<gt>.
8e07c86e 1698Questions about the DB system itself may be addressed to Keith Bostic
88108326 1699E<lt>bostic@cs.berkeley.eduE<gt>.
3b35bae3 1700
1701=cut