Regenerated.
[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)
4633a7c4 4# last modified 14th November 1995
5# version 1.01
8e07c86e 6
7package DB_File::HASHINFO ;
8use Carp;
9
10sub TIEHASH
11{
12 bless {} ;
13}
14
15%elements = ( 'bsize' => 0,
16 'ffactor' => 0,
17 'nelem' => 0,
18 'cachesize' => 0,
19 'hash' => 0,
20 'lorder' => 0
21 ) ;
22
23sub FETCH
24{
25 return $_[0]{$_[1]} if defined $elements{$_[1]} ;
26
27 croak "DB_File::HASHINFO::FETCH - Unknown element '$_[1]'" ;
28}
29
30
31sub STORE
32{
33 if ( defined $elements{$_[1]} )
34 {
35 $_[0]{$_[1]} = $_[2] ;
36 return ;
37 }
38
39 croak "DB_File::HASHINFO::STORE - Unknown element '$_[1]'" ;
40}
41
42sub DELETE
43{
44 if ( defined $elements{$_[1]} )
45 {
46 delete ${$_[0]}{$_[1]} ;
47 return ;
48 }
49
50 croak "DB_File::HASHINFO::DELETE - Unknown element '$_[1]'" ;
51}
52
53
54sub DESTROY {undef %{$_[0]} }
55sub FIRSTKEY { croak "DB_File::HASHINFO::FIRSTKEY is not implemented" }
56sub NEXTKEY { croak "DB_File::HASHINFO::NEXTKEY is not implemented" }
57sub EXISTS { croak "DB_File::HASHINFO::EXISTS is not implemented" }
58sub CLEAR { croak "DB_File::HASHINFO::CLEAR is not implemented" }
59
60package DB_File::BTREEINFO ;
61use Carp;
62
63sub TIEHASH
64{
65 bless {} ;
66}
67
68%elements = ( 'flags' => 0,
69 'cachesize' => 0,
70 'maxkeypage' => 0,
71 'minkeypage' => 0,
72 'psize' => 0,
73 'compare' => 0,
74 'prefix' => 0,
75 'lorder' => 0
76 ) ;
77
78sub FETCH
79{
80 return $_[0]{$_[1]} if defined $elements{$_[1]} ;
81
82 croak "DB_File::BTREEINFO::FETCH - Unknown element '$_[1]'" ;
83}
84
85
86sub STORE
87{
88 if ( defined $elements{$_[1]} )
89 {
90 $_[0]{$_[1]} = $_[2] ;
91 return ;
92 }
93
94 croak "DB_File::BTREEINFO::STORE - Unknown element '$_[1]'" ;
95}
96
97sub DELETE
98{
99 if ( defined $elements{$_[1]} )
100 {
101 delete ${$_[0]}{$_[1]} ;
102 return ;
103 }
104
105 croak "DB_File::BTREEINFO::DELETE - Unknown element '$_[1]'" ;
106}
107
108
109sub DESTROY {undef %{$_[0]} }
110sub FIRSTKEY { croak "DB_File::BTREEINFO::FIRSTKEY is not implemented" }
111sub NEXTKEY { croak "DB_File::BTREEINFO::NEXTKEY is not implemented" }
112sub EXISTS { croak "DB_File::BTREEINFO::EXISTS is not implemented" }
113sub CLEAR { croak "DB_File::BTREEINFO::CLEAR is not implemented" }
114
115package DB_File::RECNOINFO ;
116use Carp;
117
118sub TIEHASH
119{
120 bless {} ;
121}
122
123%elements = ( 'bval' => 0,
124 'cachesize' => 0,
125 'psize' => 0,
126 'flags' => 0,
127 'lorder' => 0,
128 'reclen' => 0,
129 'bfname' => 0
130 ) ;
131sub FETCH
132{
133 return $_[0]{$_[1]} if defined $elements{$_[1]} ;
134
135 croak "DB_File::RECNOINFO::FETCH - Unknown element '$_[1]'" ;
136}
137
138
139sub STORE
140{
141 if ( defined $elements{$_[1]} )
142 {
143 $_[0]{$_[1]} = $_[2] ;
144 return ;
145 }
146
147 croak "DB_File::RECNOINFO::STORE - Unknown element '$_[1]'" ;
148}
149
150sub DELETE
151{
152 if ( defined $elements{$_[1]} )
153 {
154 delete ${$_[0]}{$_[1]} ;
155 return ;
156 }
157
158 croak "DB_File::RECNOINFO::DELETE - Unknown element '$_[1]'" ;
159}
160
161
162sub DESTROY {undef %{$_[0]} }
163sub FIRSTKEY { croak "DB_File::RECNOINFO::FIRSTKEY is not implemented" }
164sub NEXTKEY { croak "DB_File::RECNOINFO::NEXTKEY is not implemented" }
165sub EXISTS { croak "DB_File::BTREEINFO::EXISTS is not implemented" }
166sub CLEAR { croak "DB_File::BTREEINFO::CLEAR is not implemented" }
167
168
169
170package DB_File ;
171use Carp;
172
c07a80fd 173$VERSION = $VERSION = 1.01 ;
8e07c86e 174
175#typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
c07a80fd 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 ;
8e07c86e 179
180require TieHash;
181require Exporter;
182use AutoLoader;
183require DynaLoader;
184@ISA = qw(TieHash Exporter DynaLoader);
185@EXPORT = qw(
186 $DB_BTREE $DB_HASH $DB_RECNO
187 BTREEMAGIC
188 BTREEVERSION
189 DB_LOCK
190 DB_SHMEM
191 DB_TXN
192 HASHMAGIC
193 HASHVERSION
194 MAX_PAGE_NUMBER
195 MAX_PAGE_OFFSET
196 MAX_REC_NUMBER
197 RET_ERROR
198 RET_SPECIAL
199 RET_SUCCESS
200 R_CURSOR
201 R_DUP
202 R_FIRST
203 R_FIXEDLEN
204 R_IAFTER
205 R_IBEFORE
206 R_LAST
207 R_NEXT
208 R_NOKEY
209 R_NOOVERWRITE
210 R_PREV
211 R_RECNOSYNC
212 R_SETCURSOR
213 R_SNAPSHOT
214 __R_UNUSED
215);
216
217sub AUTOLOAD {
218 local($constname);
219 ($constname = $AUTOLOAD) =~ s/.*:://;
220 $val = constant($constname, @_ ? $_[0] : 0);
221 if ($! != 0) {
222 if ($! =~ /Invalid/) {
223 $AutoLoader::AUTOLOAD = $AUTOLOAD;
224 goto &AutoLoader::AUTOLOAD;
225 }
226 else {
227 ($pack,$file,$line) = caller;
228 croak "Your vendor has not defined DB macro $constname, used at $file line $line.
229";
230 }
231 }
232 eval "sub $AUTOLOAD { $val }";
233 goto &$AUTOLOAD;
234}
235
c07a80fd 236bootstrap DB_File ;
8e07c86e 237
238# Preloaded methods go here. Autoload methods go after __END__, and are
239# processed by the autosplit program.
240
2411;
242__END__
243
244=cut
3b35bae3 245
246=head1 NAME
247
248DB_File - Perl5 access to Berkeley DB
249
250=head1 SYNOPSIS
251
252 use DB_File ;
253
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 ;
257
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]) ;
263 $status = $X->fd ;
264
265 untie %hash ;
266 untie @array ;
267
268=head1 DESCRIPTION
269
8e07c86e 270B<DB_File> is a module which allows Perl programs to make use of the
271facilities provided by Berkeley DB. If you intend to use this
272module you should really have a copy of the Berkeley DB manualpage at
273hand. The interface defined here mirrors the Berkeley DB interface
274closely.
3b35bae3 275
8e07c86e 276Berkeley DB is a C library which provides a consistent interface to a
277number of database formats. B<DB_File> provides an interface to all
278three of the database types currently supported by Berkeley DB.
3b35bae3 279
280The file types are:
281
282=over 5
283
284=item DB_HASH
285
8e07c86e 286This database type allows arbitrary key/data pairs to be stored in data
287files. This is equivalent to the functionality provided by other
288hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though,
289the files created using DB_HASH are not compatible with any of the
290other packages mentioned.
3b35bae3 291
8e07c86e 292A default hashing algorithm, which will be adequate for most
293applications, is built into Berkeley DB. If you do need to use your own
294hashing algorithm it is possible to write your own in Perl and have
295B<DB_File> use it instead.
3b35bae3 296
297=item DB_BTREE
298
8e07c86e 299The btree format allows arbitrary key/data pairs to be stored in a
300sorted, balanced binary tree.
3b35bae3 301
8e07c86e 302As with the DB_HASH format, it is possible to provide a user defined
303Perl routine to perform the comparison of keys. By default, though, the
304keys are stored in lexical order.
3b35bae3 305
306=item DB_RECNO
307
8e07c86e 308DB_RECNO allows both fixed-length and variable-length flat text files
309to be manipulated using the same key/value pair interface as in DB_HASH
310and DB_BTREE. In this case the key will consist of a record (line)
311number.
3b35bae3 312
313=back
314
315=head2 How does DB_File interface to Berkeley DB?
316
317B<DB_File> allows access to Berkeley DB files using the tie() mechanism
8e07c86e 318in Perl 5 (for full details, see L<perlfunc/tie()>). This facility
319allows B<DB_File> to access Berkeley DB files using either an
320associative array (for DB_HASH & DB_BTREE file types) or an ordinary
321array (for the DB_RECNO file type).
3b35bae3 322
8e07c86e 323In addition to the tie() interface, it is also possible to use most of
324the functions provided in the Berkeley DB API.
3b35bae3 325
326=head2 Differences with Berkeley DB
327
8e07c86e 328Berkeley DB uses the function dbopen() to open or create a database.
329Below is the C prototype for dbopen().
3b35bae3 330
331 DB*
332 dbopen (const char * file, int flags, int mode,
333 DBTYPE type, const void * openinfo)
334
335The parameter C<type> is an enumeration which specifies which of the 3
336interface methods (DB_HASH, DB_BTREE or DB_RECNO) is to be used.
337Depending on which of these is actually chosen, the final parameter,
338I<openinfo> points to a data structure which allows tailoring of the
339specific interface method.
340
8e07c86e 341This interface is handled slightly differently in B<DB_File>. Here is
342an equivalent call using B<DB_File>.
3b35bae3 343
344 tie %array, DB_File, $filename, $flags, $mode, $DB_HASH ;
345
8e07c86e 346The C<filename>, C<flags> and C<mode> parameters are the direct
347equivalent of their dbopen() counterparts. The final parameter $DB_HASH
348performs the function of both the C<type> and C<openinfo> parameters in
349dbopen().
3b35bae3 350
8e07c86e 351In the example above $DB_HASH is actually a reference to a hash
352object. B<DB_File> has three of these pre-defined references. Apart
353from $DB_HASH, there is also $DB_BTREE and $DB_RECNO.
3b35bae3 354
8e07c86e 355The keys allowed in each of these pre-defined references is limited to
356the names used in the equivalent C structure. So, for example, the
357$DB_HASH reference will only allow keys called C<bsize>, C<cachesize>,
358C<ffactor>, C<hash>, C<lorder> and C<nelem>.
3b35bae3 359
360To change one of these elements, just assign to it like this
361
362 $DB_HASH{cachesize} = 10000 ;
363
364
365=head2 RECNO
366
367
368In order to make RECNO more compatible with Perl the array offset for all
369RECNO arrays begins at 0 rather than 1 as in Berkeley DB.
370
371
372=head2 In Memory Databases
373
8e07c86e 374Berkeley 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>
376uses C<undef> instead of NULL to provide this functionality.
3b35bae3 377
378
379=head2 Using the Berkeley DB Interface Directly
380
381As well as accessing Berkeley DB using a tied hash or array, it is also
8e07c86e 382possible to make direct use of most of the functions defined in the
383Berkeley DB documentation.
3b35bae3 384
385
386To do this you need to remember the return value from the tie.
387
388 $db = tie %hash, DB_File, "filename"
389
8e07c86e 390Once you have done that, you can access the Berkeley DB API functions
391directly.
3b35bae3 392
393 $db->put($key, $value, R_NOOVERWRITE) ;
394
8e07c86e 395All the functions defined in L<dbx(3X)> are available except for
396close() and dbopen() itself. The B<DB_File> interface to these
397functions have been implemented to mirror the the way Berkeley DB
398works. In particular note that all the functions return only a status
399value. Whenever a Berkeley DB function returns data via one of its
400parameters, the B<DB_File> equivalent does exactly the same.
3b35bae3 401
402All the constants defined in L<dbopen> are also available.
403
404Below is a list of the functions available.
405
406=over 5
407
408=item get
409
8e07c86e 410Same as in C<recno> except that the flags parameter is optional.
411Remember the value associated with the key you request is returned in
412the $value parameter.
3b35bae3 413
414=item put
415
416As usual the flags parameter is optional.
417
8e07c86e 418If you use either the R_IAFTER or R_IBEFORE flags, the key parameter
419will have the record number of the inserted key/value pair set.
3b35bae3 420
421=item del
422
423The flags parameter is optional.
424
425=item fd
426
427As in I<recno>.
428
429=item seq
430
431The flags parameter is optional.
432
433Both the key and value parameters will be set.
434
435=item sync
436
437The flags parameter is optional.
438
439=back
440
441=head1 EXAMPLES
442
8e07c86e 443It is always a lot easier to understand something when you see a real
444example. So here are a few.
3b35bae3 445
446=head2 Using HASH
447
448 use DB_File ;
449 use Fcntl ;
450
8e07c86e 451 tie %h, "DB_File", "hashed", O_RDWR|O_CREAT, 0640, $DB_HASH ;
3b35bae3 452
453 # Add a key/value pair to the file
454 $h{"apple"} = "orange" ;
455
456 # Check for existence of a key
457 print "Exists\n" if $h{"banana"} ;
458
459 # Delete
460 delete $h{"apple"} ;
461
462 untie %h ;
463
464=head2 Using BTREE
465
8e07c86e 466Here is sample of code which used BTREE. Just to make life more
467interesting the default comparision function will not be used. Instead
468a Perl sub, C<Compare()>, will be used to do a case insensitive
469comparison.
3b35bae3 470
471 use DB_File ;
472 use Fcntl ;
473
474 sub Compare
475 {
476 my ($key1, $key2) = @_ ;
477
478 "\L$key1" cmp "\L$key2" ;
479 }
480
481 $DB_BTREE->{compare} = 'Compare' ;
482
8e07c86e 483 tie %h, 'DB_File', "tree", O_RDWR|O_CREAT, 0640, $DB_BTREE ;
3b35bae3 484
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' ;
490
491 # Delete
492 delete $h{"duck"} ;
493
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.
497 foreach (keys %h)
498 { print "$_\n" }
499
500 untie %h ;
501
502Here is the output from the code above.
503
504 mouse
505 Smith
506 Wall
507
508
509=head2 Using RECNO
510
511 use DB_File ;
512 use Fcntl ;
513
514 $DB_RECNO->{psize} = 3000 ;
515
516 tie @h, DB_File, "text", O_RDWR|O_CREAT, 0640, $DB_RECNO ;
517
518 # Add a key/value pair to the file
519 $h[0] = "orange" ;
520
521 # Check for existence of a key
522 print "Exists\n" if $h[1] ;
523
524 untie @h ;
525
526
cb1a09d0 527=head2 Locking Databases
3b35bae3 528
cb1a09d0 529Concurrent access of a read-write database by several parties requires
530them all to use some kind of locking. Here's an example of Tom's that
531uses the I<fd> method to get the file descriptor, and then a careful
532open() to give something Perl will flock() for you. Run this repeatedly
533in the background to watch the locks granted in proper order.
3b35bae3 534
cb1a09d0 535 use Fcntl;
536 use DB_File;
537
538 use strict;
539
540 sub LOCK_SH { 1 }
541 sub LOCK_EX { 2 }
542 sub LOCK_NB { 4 }
543 sub LOCK_UN { 8 }
544
545 my($oldval, $fd, $db, %db, $value, $key);
546
547 $key = shift || 'default';
548 $value = shift || 'magic';
549
550 $value .= " $$";
551
552 $db = tie(%db, 'DB_File', '/tmp/foo.db', O_CREAT|O_RDWR, 0644)
553 || die "dbcreat /tmp/foo.db $!";
554 $fd = $db->fd;
555 print "$$: db fd is $fd\n";
556 open(DB_FH, "+<&=$fd") || die "dup $!";
557
558
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: $!" }
563 }
564 print "$$: Read lock granted\n";
565
566 $oldval = $db{$key};
567 print "$$: Old value was $oldval\n";
568 flock(DB_FH, LOCK_UN);
569
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: $!" }
574 }
575
576 print "$$: Write lock granted\n";
577 $db{$key} = $value;
578 sleep 10;
579
580 flock(DB_FH, LOCK_UN);
581 untie %db;
582 close(DB_FH);
583 print "$$: Updated db to $key=$value\n";
584
585=head1 HISTORY
586
587=over
588
589=item 0.1
3b35bae3 590
591First Release.
592
cb1a09d0 593=item 0.2
3b35bae3 594
595When B<DB_File> is opening a database file it no longer terminates the
596process if I<dbopen> returned an error. This allows file protection
597errors to be caught at run time. Thanks to Judith Grass
cb1a09d0 598E<lt>grass@cybercash.comE<gt> for spotting the bug.
3b35bae3 599
cb1a09d0 600=item 0.3
8e07c86e 601
602Added prototype support for multiple btree compare callbacks.
603
cb1a09d0 604=item 1.0
8e07c86e 605
606B<DB_File> has been in use for over a year. To reflect that, the
607version number has been incremented to 1.0.
608
609Added complete support for multiple concurrent callbacks.
610
611Using the I<push> method on an empty list didn't work properly. This
612has been fixed.
613
cb1a09d0 614=item 1.01
4633a7c4 615
616Fixed a core dump problem with SunOS.
617
618The return value from TIEHASH wasn't set to NULL when dbopen returned
619an error.
620
3b35bae3 621=head1 WARNINGS
622
8e07c86e 623If you happen find any other functions defined in the source for this
624module that have not been mentioned in this document -- beware. I may
625drop them at a moments notice.
3b35bae3 626
8e07c86e 627If you cannot find any, then either you didn't look very hard or the
628moment has passed and I have dropped them.
3b35bae3 629
630=head1 BUGS
631
8e07c86e 632Some older versions of Berkeley DB had problems with fixed length
633records using the RECNO file format. The newest version at the time of
634writing was 1.85 - this seems to have fixed the problems with RECNO.
3b35bae3 635
8e07c86e 636I am sure there are bugs in the code. If you do find any, or can
637suggest any enhancements, I would welcome your comments.
3b35bae3 638
639=head1 AVAILABILITY
640
cb1a09d0 641Berkeley DB is available at your nearest CPAN archive (see
642L<perlmod/"CPAN"> for a list) in F<src/misc/db.1.85.tar.gz>, or via the
643host F<ftp.cs.berkeley.edu> in F</ucb/4bsd/db.tar.gz>. It is I<not> under
644the GPL.
3b35bae3 645
646=head1 SEE ALSO
647
648L<perl(1)>, L<dbopen(3)>, L<hash(3)>, L<recno(3)>, L<btree(3)>
649
8e07c86e 650Berkeley DB is available from F<ftp.cs.berkeley.edu> in the directory
651F</ucb/4bsd>.
3b35bae3 652
653=head1 AUTHOR
654
8e07c86e 655The DB_File interface was written by Paul Marquess
656<pmarquess@bfsec.bt.co.uk>.
657Questions about the DB system itself may be addressed to Keith Bostic
658<bostic@cs.berkeley.edu>.
3b35bae3 659
660=cut