1 # DB_File.pm -- Perl 5 interface to Berkeley DB
3 # written by Paul Marquess (pmarquess@bfsec.bt.co.uk)
4 # last modified 14th November 1995
7 package DB_File::HASHINFO ;
15 %elements = ( 'bsize' => 0,
25 return $_[0]{$_[1]} if defined $elements{$_[1]} ;
27 croak "DB_File::HASHINFO::FETCH - Unknown element '$_[1]'" ;
33 if ( defined $elements{$_[1]} )
35 $_[0]{$_[1]} = $_[2] ;
39 croak "DB_File::HASHINFO::STORE - Unknown element '$_[1]'" ;
44 if ( defined $elements{$_[1]} )
46 delete ${$_[0]}{$_[1]} ;
50 croak "DB_File::HASHINFO::DELETE - Unknown element '$_[1]'" ;
54 sub DESTROY {undef %{$_[0]} }
55 sub FIRSTKEY { croak "DB_File::HASHINFO::FIRSTKEY is not implemented" }
56 sub NEXTKEY { croak "DB_File::HASHINFO::NEXTKEY is not implemented" }
57 sub EXISTS { croak "DB_File::HASHINFO::EXISTS is not implemented" }
58 sub CLEAR { croak "DB_File::HASHINFO::CLEAR is not implemented" }
60 package DB_File::BTREEINFO ;
68 %elements = ( 'flags' => 0,
80 return $_[0]{$_[1]} if defined $elements{$_[1]} ;
82 croak "DB_File::BTREEINFO::FETCH - Unknown element '$_[1]'" ;
88 if ( defined $elements{$_[1]} )
90 $_[0]{$_[1]} = $_[2] ;
94 croak "DB_File::BTREEINFO::STORE - Unknown element '$_[1]'" ;
99 if ( defined $elements{$_[1]} )
101 delete ${$_[0]}{$_[1]} ;
105 croak "DB_File::BTREEINFO::DELETE - Unknown element '$_[1]'" ;
109 sub DESTROY {undef %{$_[0]} }
110 sub FIRSTKEY { croak "DB_File::BTREEINFO::FIRSTKEY is not implemented" }
111 sub NEXTKEY { croak "DB_File::BTREEINFO::NEXTKEY is not implemented" }
112 sub EXISTS { croak "DB_File::BTREEINFO::EXISTS is not implemented" }
113 sub CLEAR { croak "DB_File::BTREEINFO::CLEAR is not implemented" }
115 package DB_File::RECNOINFO ;
123 %elements = ( 'bval' => 0,
133 return $_[0]{$_[1]} if defined $elements{$_[1]} ;
135 croak "DB_File::RECNOINFO::FETCH - Unknown element '$_[1]'" ;
141 if ( defined $elements{$_[1]} )
143 $_[0]{$_[1]} = $_[2] ;
147 croak "DB_File::RECNOINFO::STORE - Unknown element '$_[1]'" ;
152 if ( defined $elements{$_[1]} )
154 delete ${$_[0]}{$_[1]} ;
158 croak "DB_File::RECNOINFO::DELETE - Unknown element '$_[1]'" ;
162 sub DESTROY {undef %{$_[0]} }
163 sub FIRSTKEY { croak "DB_File::RECNOINFO::FIRSTKEY is not implemented" }
164 sub NEXTKEY { croak "DB_File::RECNOINFO::NEXTKEY is not implemented" }
165 sub EXISTS { croak "DB_File::BTREEINFO::EXISTS is not implemented" }
166 sub CLEAR { croak "DB_File::BTREEINFO::CLEAR is not implemented" }
173 $VERSION = $VERSION = 1.01 ;
175 #typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
176 $DB_BTREE = $DB_BTREE = TIEHASH DB_File::BTREEINFO ;
177 $DB_HASH = $DB_HASH = TIEHASH DB_File::HASHINFO ;
178 $DB_RECNO = $DB_RECNO = TIEHASH DB_File::RECNOINFO ;
184 @ISA = qw(TieHash Exporter DynaLoader);
186 $DB_BTREE $DB_HASH $DB_RECNO
219 ($constname = $AUTOLOAD) =~ s/.*:://;
220 $val = constant($constname, @_ ? $_[0] : 0);
222 if ($! =~ /Invalid/) {
223 $AutoLoader::AUTOLOAD = $AUTOLOAD;
224 goto &AutoLoader::AUTOLOAD;
227 ($pack,$file,$line) = caller;
228 croak "Your vendor has not defined DB macro $constname, used at $file line $line.
232 eval "sub $AUTOLOAD { $val }";
238 # Preloaded methods go here. Autoload methods go after __END__, and are
239 # processed by the autosplit program.
248 DB_File - Perl5 access to Berkeley DB
254 [$X =] tie %hash, DB_File, $filename [, $flags, $mode, $DB_HASH] ;
255 [$X =] tie %hash, DB_File, $filename, $flags, $mode, $DB_BTREE ;
256 [$X =] tie @array, DB_File, $filename, $flags, $mode, $DB_RECNO ;
258 $status = $X->del($key [, $flags]) ;
259 $status = $X->put($key, $value [, $flags]) ;
260 $status = $X->get($key, $value [, $flags]) ;
261 $status = $X->seq($key, $value [, $flags]) ;
262 $status = $X->sync([$flags]) ;
270 B<DB_File> is a module which allows Perl programs to make use of the
271 facilities provided by Berkeley DB. If you intend to use this
272 module you should really have a copy of the Berkeley DB manualpage at
273 hand. The interface defined here mirrors the Berkeley DB interface
276 Berkeley DB is a C library which provides a consistent interface to a
277 number of database formats. B<DB_File> provides an interface to all
278 three of the database types currently supported by Berkeley DB.
286 This database type allows arbitrary key/data pairs to be stored in data
287 files. This is equivalent to the functionality provided by other
288 hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
289 the files created using DB_HASH are not compatible with any of the
290 other packages mentioned.
292 A default hashing algorithm, which will be adequate for most
293 applications, is built into Berkeley DB. If you do need to use your own
294 hashing algorithm it is possible to write your own in Perl and have
295 B<DB_File> use it instead.
299 The btree format allows arbitrary key/data pairs to be stored in a
300 sorted, balanced binary tree.
302 As with the DB_HASH format, it is possible to provide a user defined
303 Perl routine to perform the comparison of keys. By default, though, the
304 keys are stored in lexical order.
308 DB_RECNO allows both fixed-length and variable-length flat text files
309 to be manipulated using the same key/value pair interface as in DB_HASH
310 and DB_BTREE. In this case the key will consist of a record (line)
315 =head2 How does DB_File interface to Berkeley DB?
317 B<DB_File> allows access to Berkeley DB files using the tie() mechanism
318 in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
319 allows B<DB_File> to access Berkeley DB files using either an
320 associative array (for DB_HASH & DB_BTREE file types) or an ordinary
321 array (for the DB_RECNO file type).
323 In addition to the tie() interface, it is also possible to use most of
324 the functions provided in the Berkeley DB API.
326 =head2 Differences with Berkeley DB
328 Berkeley DB uses the function dbopen() to open or create a database.
329 Below is the C prototype for dbopen().
332 dbopen (const char * file, int flags, int mode,
333 DBTYPE type, const void * openinfo)
335 The parameter C<type> is an enumeration which specifies which of the 3
336 interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
337 Depending on which of these is actually chosen, the final parameter,
338 I<openinfo> points to a data structure which allows tailoring of the
339 specific interface method.
341 This interface is handled slightly differently in B<DB_File>. Here is
342 an equivalent call using B<DB_File>.
344 tie %array, DB_File, $filename, $flags, $mode, $DB_HASH ;
346 The C<filename>, C<flags> and C<mode> parameters are the direct
347 equivalent of their dbopen() counterparts. The final parameter $DB_HASH
348 performs the function of both the C<type> and C<openinfo> parameters in
351 In the example above $DB_HASH is actually a reference to a hash
352 object. B<DB_File> has three of these pre-defined references. Apart
353 from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
355 The keys allowed in each of these pre-defined references is limited to
356 the names used in the equivalent C structure. So, for example, the
357 $DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
358 C<ffactor>, C<hash>, C<lorder> and C<nelem>.
360 To change one of these elements, just assign to it like this
362 $DB_HASH{cachesize} = 10000 ;
368 In order to make RECNO more compatible with Perl the array offset for all
369 RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
372 =head2 In Memory Databases
374 Berkeley DB allows the creation of in-memory databases by using NULL
375 (that is, a C<(char *)0 in C) in place of the filename. B<DB_File>
376 uses C<undef> instead of NULL to provide this functionality.
379 =head2 Using the Berkeley DB Interface Directly
381 As well as accessing Berkeley DB using a tied hash or array, it is also
382 possible to make direct use of most of the functions defined in the
383 Berkeley DB documentation.
386 To do this you need to remember the return value from the tie.
388 $db = tie %hash, DB_File, "filename"
390 Once you have done that, you can access the Berkeley DB API functions
393 $db->put($key, $value, R_NOOVERWRITE) ;
395 All the functions defined in L<dbx(3X)> are available except for
396 close() and dbopen() itself. The B<DB_File> interface to these
397 functions have been implemented to mirror the the way Berkeley DB
398 works. In particular note that all the functions return only a status
399 value. Whenever a Berkeley DB function returns data via one of its
400 parameters, the B<DB_File> equivalent does exactly the same.
402 All the constants defined in L<dbopen> are also available.
404 Below is a list of the functions available.
410 Same as in C<recno> except that the flags parameter is optional.
411 Remember the value associated with the key you request is returned in
412 the $value parameter.
416 As usual the flags parameter is optional.
418 If you use either the R_IAFTER or R_IBEFORE flags, the key parameter
419 will have the record number of the inserted key/value pair set.
423 The flags parameter is optional.
431 The flags parameter is optional.
433 Both the key and value parameters will be set.
437 The flags parameter is optional.
443 It is always a lot easier to understand something when you see a real
444 example. So here are a few.
451 tie %h, "DB_File", "hashed", O_RDWR|O_CREAT, 0640, $DB_HASH ;
453 # Add a key/value pair to the file
454 $h{"apple"} = "orange" ;
456 # Check for existence of a key
457 print "Exists\n" if $h{"banana"} ;
466 Here is sample of code which used BTREE. Just to make life more
467 interesting the default comparision function will not be used. Instead
468 a Perl sub, C<Compare()>, will be used to do a case insensitive
476 my ($key1, $key2) = @_ ;
478 "\L$key1" cmp "\L$key2" ;
481 $DB_BTREE->{compare} = 'Compare' ;
483 tie %h, 'DB_File', "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE ;
485 # Add a key/value pair to the file
486 $h{'Wall'} = 'Larry' ;
487 $h{'Smith'} = 'John' ;
488 $h{'mouse'} = 'mickey' ;
489 $h{'duck'} = 'donald' ;
494 # Cycle through the keys printing them in order.
495 # Note it is not necessary to sort the keys as
496 # the btree will have kept them in order automatically.
502 Here is the output from the code above.
514 $DB_RECNO->{psize} = 3000 ;
516 tie @h, DB_File, "text", O_RDWR|O_CREAT, 0640, $DB_RECNO ;
518 # Add a key/value pair to the file
521 # Check for existence of a key
522 print "Exists\n" if $h[1] ;
527 =head2 Locking Databases
529 Concurrent access of a read-write database by several parties requires
530 them all to use some kind of locking. Here's an example of Tom's that
531 uses the I<fd> method to get the file descriptor, and then a careful
532 open() to give something Perl will flock() for you. Run this repeatedly
533 in the background to watch the locks granted in proper order.
545 my($oldval, $fd, $db, %db, $value, $key);
547 $key = shift || 'default';
548 $value = shift || 'magic';
552 $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0644)
553 || die "dbcreat /tmp/foo.db $!";
555 print "$$: db fd is $fd\n";
556 open(DB_FH, "+<&=$fd") || die "dup $!";
559 unless (flock (DB_FH, LOCK_SH | LOCK_NB)) {
560 print "$$: CONTENTION; can't read during write update!
561 Waiting for read lock ($!) ....";
562 unless (flock (DB_FH, LOCK_SH)) { die "flock: $!" }
564 print "$$: Read lock granted\n";
567 print "$$: Old value was $oldval\n";
568 flock(DB_FH, LOCK_UN);
570 unless (flock (DB_FH, LOCK_EX | LOCK_NB)) {
571 print "$$: CONTENTION; must have exclusive lock!
572 Waiting for write lock ($!) ....";
573 unless (flock (DB_FH, LOCK_EX)) { die "flock: $!" }
576 print "$$: Write lock granted\n";
580 flock(DB_FH, LOCK_UN);
583 print "$$: Updated db to $key=$value\n";
595 When B<DB_File> is opening a database file it no longer terminates the
596 process if I<dbopen> returned an error. This allows file protection
597 errors to be caught at run time. Thanks to Judith Grass
598 E<lt>grass@cybercash.comE<gt> for spotting the bug.
602 Added prototype support for multiple btree compare callbacks.
606 B<DB_File> has been in use for over a year. To reflect that, the
607 version number has been incremented to 1.0.
609 Added complete support for multiple concurrent callbacks.
611 Using the I<push> method on an empty list didn't work properly. This
616 Fixed a core dump problem with SunOS.
618 The return value from TIEHASH wasn't set to NULL when dbopen returned
623 If you happen find any other functions defined in the source for this
624 module that have not been mentioned in this document -- beware. I may
625 drop them at a moments notice.
627 If you cannot find any, then either you didn't look very hard or the
628 moment has passed and I have dropped them.
632 Some older versions of Berkeley DB had problems with fixed length
633 records using the RECNO file format. The newest version at the time of
634 writing was 1.85 - this seems to have fixed the problems with RECNO.
636 I am sure there are bugs in the code. If you do find any, or can
637 suggest any enhancements, I would welcome your comments.
641 Berkeley DB is available at your nearest CPAN archive (see
642 L<perlmod/"CPAN"> for a list) in F<src/misc/db.1.85.tar.gz>, or via the
643 host F<ftp.cs.berkeley.edu> in F</ucb/4bsd/db.tar.gz>. It is I<not> under
648 L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>
650 Berkeley DB is available from F<ftp.cs.berkeley.edu> in the directory
655 The DB_File interface was written by Paul Marquess
656 <pmarquess@bfsec.bt.co.uk>.
657 Questions about the DB system itself may be addressed to Keith Bostic
658 <bostic@cs.berkeley.edu>.