ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/TDB_FileX/TDB_FileX.pm
Revision: 1.10
Committed: Fri May 2 21:04:38 2025 UTC (17 months, 1 week ago) by root
Branch: MAIN
Changes since 1.9: +13 -7 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 package TDB_FileX;
2    
3     use common::sense;
4    
5     use Exporter ();
6     use XSLoader ();
7    
8     our @ISA = qw(Exporter);
9    
10     # Items to export into callers namespace by default. Note: do not export
11     # names by default without a very good reason. Use EXPORT_OK instead.
12     # Do not simply export all your public functions/methods/constants.
13    
14     our %EXPORT_TAGS = (
15     flags => [qw(
16     ALLOW_NESTING
17     BIGENDIAN
18     CLEAR_IF_FIRST
19     CONVERT
20     DEFAULT
21     DISALLOW_NESTING
22     INCOMPATIBLE_HASH
23     INTERNAL
24     MUTEX_LOCKING
25     NOLOCK
26     NOMMAP
27     NOSYNC
28     SEQNUM
29     VOLATILE
30     )],
31     insert => [qw(
32     INSERT
33     MODIFY
34     REPLACE
35     )],
36     error => [qw(
37     SUCCESS
38     ERR_CORRUPT
39     ERR_EXISTS
40     ERR_IO
41     ERR_LOCK
42     ERR_LOCK_TIMEOUT
43     ERR_NOEXIST
44     ERR_NOLOCK
45     ERR_OOM
46     ERR_EINVAL
47     ERR_RDONLY
48     )],
49     debug => [qw(
50     DEBUG_FATAL
51     DEBUG_ERROR
52     DEBUG_WARNING
53     DEBUG_TRACE}
54     )],
55     );
56    
57     our @EXPORT_OK;
58    
59     Exporter::export_ok_tags qw(flags insert error debug);
60    
61     $EXPORT_TAGS{all} = \@EXPORT_OK;
62    
63     our $VERSION = '0.97';
64    
65     XSLoader::load __PACKAGE__, $VERSION;
66    
67     1;
68     __END__
69    
70     =head1 NAME
71    
72     TDB_FileX - Perl access to the trivial database library
73    
74     =head1 SYNOPSIS
75    
76     use TDB_FileX;
77    
78     # tie interface
79     tie %hash, TDB_FileX => $filename,
80     hash_size => 8000,
81     mutex => 1,
82     ;
83     $hash{key} = 'value';
84     while (my ($k, $v) = each %hash) { print "$k -> $v\n" }
85    
86     # OO interface
87     my $tdb = TDB_FileX->open ($filename, flags => TDB_FileX::CLEAR_IF_FIRST)
88     or die $!;
89    
90     $tdb->store (key => 'value') or die $tdb->errorstr;
91     $tdb->traverse (sub { print "$_[0] -> $_[1]\n" });
92    
93     =head1 DESCRIPTION
94    
95     TDB is a simple database similar to GDBM, but allows multiple simultaneous
96     writers. It's main drawback is the need to manually configure a hash table
97     size in advance - see the C<hash_size> option for C<open>.
98    
99     TDB_FileX provides a simple C<tie> interface, similar to DB_File and
100 root 1.3 friends; and an object-oriented interface, which provides access to most
101     of the functions in the TDB library.
102    
103     =head1 ERROR HANDLKING
104    
105     The TDB C API is not well designed - among other things, error handling is
106     a bit erratic. Many functions that normally should just work are marked
107     with a [CROAK] - these will throw an exception on error, the exception
108     string being the error message. C<$!> is set to the numerical error value
109     in that case (and will stringify into the wrong OS-error string, so don't
110     do that!).
111    
112     This is so that you can concentrate on the important parts, while there
113     are still no silent unexpected errors.
114    
115     The other functions will not generally croak - check their description for
116     details on how errors are handled.
117 root 1.1
118     =head2 FUNCTIONS
119    
120     =over 4
121    
122 root 1.3 =item $tdb = tie %hash, TDB_FileX => $path[ , key => value...]
123    
124     =item $tdb = TDB_FileX->open ($path[, key => value...])
125    
126     TDB_FileX constructor (same as C<TIE>). Opens $path and returns a
127     TDB_FileX object. The same arguments may be passed to the C<tie>
128     function. On error, C<undef> is returned.
129 root 1.1
130 root 1.10 You should consider specifying at least C<log_cb> and C<hash_size> (and
131     possibly C<mutex>), everything else has sensible defaults.
132    
133 root 1.3 To open a tdb file that is created and used by another application
134 root 1.6 (maximising compatibility):
135 root 1.3
136     my $tdb = TDB_FileX->open ($path, log_cb => sub { warn $_[1] })
137     or die "$path: failed to open\n";
138    
139 root 1.10 To successfully open another database, you might have to duplicate some of
140     the settings, e.g. whether mutex locking is used or the hash function. The
141     C<log_cb> output usually will tell you what's wrong.
142    
143 root 1.3 To open a tdb file with good performance for many thousands of large keys,
144 root 1.10 maybe not compatible to other programs:
145 root 1.3
146     my $tdb = TDB_FileX->open ($path,
147     hash_size => 10000,
148     hash => "xxh3",
149     mutex => 1,
150 root 1.6 nocow => 1,
151 root 1.3 log_cb => sub { warn $_[1] },
152     ) or die "$path: failed to open\n";
153 root 1.1
154 root 1.10 The following key-value pairs are understood:
155 root 1.1
156     =over
157    
158     =item tdb_flags => $flags (default: C<TDB_FileX::DEFAULT>)
159    
160     A set of flags that influence the behaviour and format of the database.
161    
162     See tdb_open(3) for the meanings and possible values (note that the
163     C<TDB_> prefix has to be removed, see the L<EXPORTS> section for a list.
164    
165 root 1.10 TODO: list flags with short explanation
166    
167 root 1.1 =item open_flags => $flags (default: C<Fcntl::O_RDWR | Fcntl::O_CREAT>)
168    
169     Standard open flags, as used in C<sysopen>.
170    
171     =item mode => $mode (default: C<0666>)
172    
173     Standard file open mode, as use din C<sysopen>. Only used when creating
174     the database file.
175    
176     =item hash_size => $int (default: internal to libtdb, but normally C<131>)
177    
178     The size of the internal hash table - only used when creating the
179     database. The default is usually very low and only good for a few thousand
180     keys. As a rule of thumb, it should be at least one percent of the number
181     of keys you plan to store, e.g. for C<800000> keys you should use around a
182     size of C<8000>.
183    
184 root 1.5 Every hash entry is only 4 octets, os usually it isn't an issue to make the
185 root 1.2 hash table too large.
186    
187     To give you an idea of the performance, I inserted about 600000 records,
188     3GB of data, into a TDB file, using different hash sizes.
189 root 1.1
190     size time
191     131 160s
192     256 85s
193     1024 12s
194     4096 5s
195     8192 4s
196    
197 root 1.3 As you can see, the default hash table size for this case caused it to
198     use 40 times the time to insert than a larger hash table, the optimum
199 root 1.5 being around 75 keys per hash entry. But the databse easily was cached in
200 root 1.3 memory. If that is not the case, you might want to consider a hash table
201     that is larger than the number of keys you want to store - each hash slot
202     only uses 4 octets.
203 root 1.1
204     =item log_cb => $cb->($level, $msg)
205    
206 root 1.2 Sets a code reference that is called with a message and a log level
207 root 1.1 (lower means more important, there are C<DEBUG_FATAL>, C<DEBUG_ERROR>,
208     C<DEBUG_WARNING> and C<DEBUG_TRACE}>). Unlike the "debug" in the name
209     might indicate, if you want to find out why, for instance, you could not
210     open a database, you need to use a logging callback.
211    
212     =item hash => $hash (default: C<undef>)
213    
214     Selects a hash function to use.
215    
216     =over
217    
218     =item C<"default"> or C<undef>
219    
220     Use autodetection and use either C<"jenkins"> or the original tdb hash function.
221    
222     =item C<"jenkins">
223    
224     The jenkins hash function. Relatively fast, and recommended for modern tdb databases
225     that need to be interoperable between implementations.
226    
227     =item C<"fnv1ax">
228    
229 root 1.10 The FNV1-A hash with 32 bit post-mixing. Pretty good and very fast for
230 root 1.1 keys up to 10-20 octets.
231    
232     =item C<"xxh3">
233    
234     The XXH3 hash. Very good and fast especially for long keys.
235    
236     =item C<1> .. C<4>
237    
238     Specify one of up to four custom hash functions (see L<set_hash_function>).
239    
240     =back
241    
242     =item mutex => $bool (default: C<0>)
243    
244 root 1.6 TDB can take advantage of fast interprocess mutexes, which can be
245     orders of magnitude faster than the syscall-based locking used by
246     default, but only works on the same machine.
247    
248     Normally, you need to call C<TDB_FileX::runtime_check_for_robust_mutexes>
249     and set the C<MUTEX_LOCKING> flag if support is indicated.
250 root 1.1
251     This option, when enabled, enables C<MUTEX_LOCKING> if it is supported
252     by the platform - which involves a fork when opening the database. When
253     disabled, it will remove the flag.
254    
255     It is recommended to keep this one, but enabling this changes the format
256     of the database, so might not be an option if interoperability with other
257     programs is required.
258    
259 root 1.6 =item nocow => $bool (default: C<0>)
260    
261     Set the no-copy-on-write flag I<iff> this flag is true, C<open_flags>
262 root 1.7 contains C<O_CREAT>, C<tdb_flags> do not contain C<INTERNAL> and this is
263     supported on the platform and filesystem. Copy-on-write filesystems have
264     to make a copy of every block written to, which can both be costly and can
265     cause massive fragmentation of the database file.
266 root 1.6
267     Setting the no-copy-on-write flag (same as C<chattr +C>) disables this,
268     usually at the expense of data protection (checksumming), reducing the
269     safety to the level of a normal filesystem such as ext4.
270    
271     This is best effort and usually only takes effect when the
272     database is initially created. If it fails, TDB_FileX will simply
273     continue. Correctness should not be affected either way.
274    
275 root 1.1 =back
276    
277     There is no explicit close function. The database is closed implicitly
278     when there are no remaining references.
279    
280 root 1.3 =item $tdb->store ($key, $value[, $flag=REPLACE]) [CROAK]
281 root 1.1
282     Store $value in the database with key w$key. The $flag defaults to
283     C<REPLACE>, but can also be C<INSERT> or C<MODIFY>, see tdb_store(3) for
284     details.
285    
286 root 1.3 =item $tdb->append ($key, $value) [CROAK]
287    
288     Appends $data to the data already stored for $key, or creates a new entry with it.
289 root 1.1
290     =item $tdb->fetch ($key)
291    
292 root 1.3 Fetch the value associated with $key, or C<undef> if it is not found (or
293     on any error).
294 root 1.1
295 root 1.3 =item $tdb->delete ($key) [CROAK]
296 root 1.1
297     Delete the value associated with $key.
298    
299     On failure, a perl false is returned. See L</$tdb->error> and
300     L</$tdb->errorstr> for the reason.
301    
302 root 1.3 =item $bool = $tdb->exists ($key)
303 root 1.1
304     Return true if the $key is found, false otherwise.
305    
306     =item $tdb->firstkey
307    
308     Return the key of the first value in the database. Returns C<undef> on
309     failure or if there are no keys in the database. See tdb_firstkey(3)
310     for details.
311    
312     =item $tdb->nextkey ($lastkey)
313    
314     Return the next key in the database after $lastkey. Returns C<undef> on
315     failure or if there are no more keys in the database. See tdb_nextkey(3)
316     for details.
317    
318     =item $tdb->error
319    
320     Returns the current error state of the C<$tdb> object. See the list of
321     error codes given in L<EXPORTS>.
322    
323     =item $tdb->errorstr
324    
325     Returns a printable string that describes the error state of the
326     database.
327    
328 root 1.3 =item $tdb->reopen [CROAK]
329 root 1.1
330     Closes and reopens the database. Required after a
331     L<fork|perlfunc/fork>, if both processes wish to use the database.
332    
333 root 1.3 B<NB:> If C<reopen> fails, then it is unsafe to call any further methods
334     on C<$tdb>. Thus, the only way to find out I<why> C<reopen> failed is to
335     use a logging function.
336 root 1.1
337 root 1.3 =item TDB_FileX::reopen_all [CROAK]
338 root 1.1
339     Closes and reopens all open databases. See L</$tdb->reopen>.
340    
341 root 1.3 B<NB:> If C<reopen_all> fails, there is no indication of I<which> C<$tdb>
342     objects failed or why. If you have to survive failures, you may wish to do
343     your own C<reopen> loop instead.
344 root 1.1
345 root 1.4 =item $tdb->traverse ($cb->($key, $data)) [CROAK]
346 root 1.1
347 root 1.4 Call $cb for each entry in the database. The callback should return false
348     to continue, or a true value to abort the traversal.
349 root 1.1
350 root 1.3 The callback is called with the key and value as arguments and should
351 root 1.4 return a false value if you wish to continue traversal, and a true value
352     if the traversal should be aborted.
353 root 1.1
354 root 1.4 C<traverse> returns the number of elements traversed. If $cb is C<undef>,
355     then this function simply counts the number of elements.
356    
357     =item $tdb->traverse_read ($cb->($key, $data)) [CROAK]
358    
359     Like C<traverse>, but only acquires a read lock.
360 root 1.1
361 root 1.3 =item $tdb->set_logging_function ($cb->($level, $msg))
362 root 1.1
363     Set the logging function to use when this database object encounters
364 root 1.3 errors.
365 root 1.1
366 root 1.3 $cb is called with the severity level (an integer) and the message (a
367 root 1.1 string).
368    
369 root 1.3 =item $tdb->lockall [CROAK]
370 root 1.1
371 root 1.2 Lock an entire database with an exclusive write lock, returning false on
372     error. The purpose of this call is to avoid locking overhead for many
373     operations, but the database has to be unlocked manually when done.
374 root 1.1
375 root 1.3 =item $tdb->unlockall [CROAK]
376 root 1.1
377     Unlock an entire database previously locked with
378     L</$tdb->lockall>.
379    
380 root 1.3 =item $tdb->lockall_read [CROAK]
381 root 1.2
382     Same as L</$tdb->lockall>, but uses a shared read lock instead of a writer lock.
383    
384 root 1.3 =item $tdb->unlockall_read [CROAK]
385 root 1.2
386     Opposite of L</$tdb->lockall_read>.
387    
388 root 1.3 =item $tdb->lockall_mark [CROAK]
389 root 1.2
390 root 1.3 =item $tdb->lockall_unmark [CROAK]
391 root 1.2
392 root 1.8 These apparently mark and unmark locks internally, but do not actually do
393     locking. Probably you should not use this, but feel free to tell me when
394     these are useful.
395 root 1.2
396 root 1.3 =item $tdb->lockall_nonblock [CROAK]
397 root 1.2
398 root 1.8 =item $success = $tdb->lockall_read_nonblock [CROAK]
399 root 1.2
400 root 1.8 Try to lock, but instead of waiting, fail if the lock could not
401     be acquired. Returns true if the lock could be acquired, false
402     otherwise. Croaks on all other errors.
403 root 1.2
404 root 1.3 =item $tdb->transaction_start [CROAK]
405 root 1.2
406     Starts a transaction - all operations will be queued, but not applied
407     to the database, until the transaction is either committed L</$tdb->transaction_commit>
408     or aborted/thrown away, with L</$tdb->transaction_cancel>.
409    
410 root 1.3 =item $tdb->transaction_start_nonblock [CROAK]
411 root 1.2
412 root 1.8 Tries to start a transaction, but instead of waiting, fail if the lock
413     could not be acquired. Returns true if the transaction could be started,
414     false otherwise. Croaks on all other errors.
415    
416 root 1.2 Please tell me what this does.
417    
418 root 1.3 =item $tdb->transaction_commit [CROAK]
419 root 1.2
420     Applies all changes in the transaction.
421    
422 root 1.3 =item $tdb->transaction_cancel [CROAK]
423 root 1.2
424     Throws away all changes in the transaction.
425    
426 root 1.3 =item $tdb->transaction_prepare_commit [CROAK]
427 root 1.2
428     Instead of calling L</$tdb->transaction_commit> you can do the commit in
429     two phases by calling this method before commit, which does the expensive
430     steps first.
431    
432     =item $bool = $tdb->transaction_active
433    
434     Returns true if a transaction is currently active.
435    
436     =item $tdb->enable_seqnum
437    
438     Enables sequence number generatiuon supporet for the database.
439    
440     =item $seq = $tdb->get_seqnum
441    
442     Returns the current sequence number. Internally, this is a 32 bit unsigned
443     integer, but the API converts it into a native integer, so the same
444     internal sequence number might be represented differently on different
445     machines.
446    
447     =item $tdb->increment_seqnum_nonblock
448    
449     Increments the sequence number. Note that the sequence number is also
450     incremented by TDB itself oon many operations.
451    
452     =item $size = $tdb->hash_size
453    
454     Returns the size of the hash table. The size cannot be changed other than
455     by recreating the database.
456    
457     =item $octets = $tdb->map_size
458    
459     Returns the current mmap size for the database.
460    
461     =item $flags = $tdb->get_flags
462    
463     Returns the flags for the database (the same as the C<tdb_flags> in C<open>).
464    
465     =item $tdb->add_flags ($flag)
466    
467     Tried to add flags to the database - yes, the parameter says C<$flag> (singular)
468     but the documentation and the code say I<flags> (plural).
469    
470     =item $tdb->remove_flags ($flag)
471    
472     Attempts to remove flags from the database.
473    
474     =item $fileno = $tdb->fd
475    
476     Returns the file descriptor (not file handle) for the underlying database file.
477    
478     =item $path = $tdb->name
479    
480     Returns the path used to open the database.
481    
482 root 1.3 =item $tdb->wipe_all [CROAK]
483 root 1.2
484     Efficientlly deletes all entries in the database. This does not shrink the
485     file itself.
486    
487 root 1.3 =item $tdb->repack [CROAK]
488 root 1.2
489     Tries to improve layout of the database by copying all items into a
490     temporary in-memory database, wiping the database, and copying all items
491 root 1.3 back. Yes, everything must fit into memory.
492 root 1.2
493 root 1.4 =item $bool = $tdb->check ($cb->($key, $value))
494    
495     Does extensive checks on the database, optionally (if not C<undef>)
496     calling a check function for each pair, which must return true if the data
497     is valid.
498    
499     Returns a boolean indicating whether the database was found healthy and
500     all the calls to the callback returned true.
501    
502     =item $bool = $tdb->rescue ($cb->($key, $value))
503    
504     Tries to recover some or all key-value pairs from a potentially damanged
505     database file. For each recovered pair it calls the given callback.
506    
507     Returns a boolean indicating whether the database was found healthy and
508     all the calls to the callback returned true.
509    
510 root 1.2 =item $bool = TDB_FileX::runtime_check_for_robust_mutexes
511    
512     Tests whether robust mutexes are available for locking. This involves
513     forking the process, so it can be costly and problematic. This function
514     needs to be called before using the C<MUTEX_LOCKING> flag. But see the
515     C<mutex> parametrer to C<open> for an alternative.
516    
517 root 1.1 =item $tdb->dump_all
518    
519     Dump the records and freelist to STDOUT in an almost human readable
520     form.
521    
522 root 1.9 =item $summary = $tdb->summary
523    
524     Return a textual summary of the database. The format isn't documented,
525     but for some random databas,e I got this output:
526    
527     Size of file/data: 325001216/238324906
528     Header offset/logical size: 4001792/320999424
529     Number of records: 117209
530     Incompatible hash: no
531     Active/supported feature flags: 0x00000001/0x00000001
532     Robust mutexes locking: yes
533     Smallest/average/largest keys: 11/36/102
534     Smallest/average/largest data: 10/1997/2921430
535     Smallest/average/largest padding: 9/530/749374
536     Number of dead records: 0
537     Smallest/average/largest dead records: 0/0/0
538     Number of free records: 1126
539     Smallest/average/largest free records: 12/15312/14681136
540     Number of hash chains: 100000
541     Smallest/average/largest hash chains: 0/1/8
542     Number of uncoalesced records: 0
543     Smallest/average/largest uncoalesced runs: 0/0/0
544     Percentage keys/data/padding/free/dead/rechdrs&tailers/hashes: 1/72/19/5/0/1/0
545    
546     =item $octets = $tdb->freelist_size
547    
548     Returns the total number of free (unused) octets in the file.
549    
550 root 1.1 =item $tdb->printfreelist
551    
552     Dump the freelist to STDOUT.
553    
554     =back
555    
556     =head2 EXPORTS
557    
558     Nothing constants are exported by default.
559    
560     The tag C<:all> exports allpo of the constants.
561    
562     Individually or with the tag C<:flags>:
563    
564     DEFAULT
565     CLEAR_IF_FIRST
566     INTERNAL
567     NOLOCK
568     NOMMAP
569     CONVERT
570     BIGENDIAN
571     NOSYNC
572     SEQNUM
573     VOLATILE
574     ALLOW_NESTING
575     DISALLOW_NESTING
576     INCOMPATIBLE_HASH
577     MUTEX_LOCKING
578    
579     Individually or with the tag C<:insert>:
580    
581     REPLACE
582     INSERT
583     MODIFY
584    
585     Individually or with the tag C<:error>:
586    
587     SUCCESS
588     ERR_CORRUPT
589     ERR_IO
590     ERR_LOCK
591     ERR_OOM
592     ERR_EXISTS
593     ERR_NOLOCK
594     ERR_LOCK_TIMEOUT
595     ERR_NOEXIST
596     ERR_EINVAL
597     ERR_RDONLY
598    
599     Individually or with the tag C<:debug>:
600    
601     DEBUG_FATAL
602     DEBUG_ERROR
603     DEBUG_WARNING
604     DEBUG_TRACE
605    
606 root 1.2 =head1 UNICODE HANDLING
607    
608     TDB databases can only store octet strings. Unlike most other database
609     interfaces, TDB_FileX will safely handle Perl strings by downgrading
610     them. Perl will warn about strings that cnanot be downgraded.
611    
612     =head1 DISK USAGE
613    
614     TDB databses use 24 octets for every key-value pair, plus the octet size
615     of the key and sata, e.g. the pair "key" => "value" takes up 24+3+5 octets
616     on disk.
617    
618     The database header is 168 octets (if I haven't miscounted).
619    
620     Each hashtable entry is 4 octets, and one more than the hash size is
621 root 1.10 allocated, so the hash table size is (hash_size + 1) * 4.
622 root 1.2
623     =head1 LIMITATIONS
624    
625     =head2 Database Size
626    
627     As far as I can see, TDB dastabases are limited to 4 GB.
628    
629     =head2 Hash Functions
630    
631     Hash functioons need to be set globally - they are limited to a maximum of
632     4, but this can be easily extended, but requires source code editing. This
633     is due to a limitation of the TDB C API.
634    
635     =head2 No recoivery after failed C<reopoen_all>
636 root 1.1
637     There is no way to survive an error during C<reopen_all>.
638     Unfortunately this is a limitation in the TDB C API.
639    
640     =head1 SEE ALSO
641    
642     tdb(3), L<perltie>.
643    
644     =head1 AUTHOR
645    
646     Angus Lees, E<lt>gus@inodes.org>
647    
648     Currently maintained by Marc A. Lehmann <schmorp@schmorp.de>
649     http://home.schmorp.de/
650    
651     =cut