ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/TDB_FileX/TDB_FileX.pm
Revision: 1.16
Committed: Sat May 3 19:24:18 2025 UTC (17 months ago) by root
Branch: MAIN
CVS Tags: rel-0_97
Changes since 1.15: +26 -0 lines
Log Message:
*** empty log message ***

File Contents

# Content
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 friends; and an object-oriented interface, which provides access to most
101 of the functions in the TDB library.
102
103 =head2 COMPARISON TO OTHER DBMS
104
105 TDB stands for trivial database - and indeed, the database structure is
106 very simple, requiring manual sizing at creation time, and being limited
107 to 4GB size.
108
109 But otherwise, TDB has features that no other simple DBM has -
110 fine-grained locking, multiprocess database access and transactions.
111
112 GDBM_File for example has a single per-process lock, so only one process
113 can write to the database. Most others have no locking and will happily
114 corrupt your database. TDB_FileX is safe to use from multiple processes.
115
116 As for data safety, GDBM databases easily corrupt (in current version of
117 GDBM), and while GDBM databases can be 30% more compact than equivalent
118 TDB databases, they tend to grow over time (I regularly find 10GB GDBM
119 databases (actual disk usage) that reorganize to 300MB files and have
120 never stored more than that). TDB files do not usually have such bad
121 growth behaviour, but also have no reorganize function to shrink the
122 database again.
123
124 So, if you want safe access from multiple proceses and have a good idea
125 of how many keys to store, TDB_FileX is the thing. If you only want
126 protectioon against obvious data corruption and processes can wait, GDBM
127 is a probably a better choice.
128
129 =head1 ERROR HANDLKING
130
131 The TDB C API is not well designed - among other things, error handling
132 is a bit erratic. Many TDB functions that normally should just work are
133 marked with a [CROAK] - these will throw an exception on error, the
134 exception string being the error message. C<$!> is set to the numerical
135 error value in that case (and will stringify into the wrong OS-error
136 string, so don't do that!).
137
138 This is so that you can concentrate on the important parts, while there
139 are still no silent unexpected errors.
140
141 The other functions will not generally croak - check their description for
142 details on how errors are handled.
143
144 Functions that are not part of the TDB API (such as
145 C<register_hash_function>) may croak on errors without being marked as
146 such. The above only refers to TDB API functions, as they cannot throw
147 perl exceptions themselves.
148
149 =head2 FUNCTIONS
150
151 =over 4
152
153 =item $tdb = tie %hash, TDB_FileX => $path[ , key => value...]
154
155 =item $tdb = TDB_FileX->open ($path[, key => value...])
156
157 TDB_FileX constructor (same as C<TIE>). Opens $path and returns a
158 TDB_FileX object. The same arguments may be passed to the C<tie>
159 function. On error, C<undef> is returned.
160
161 You should consider specifying at least C<log_cb> and C<hash_size> (and
162 possibly C<mutex>), everything else has sensible defaults.
163
164 To open a tdb file that is created and used by another application
165 (maximising compatibility):
166
167 my $tdb = TDB_FileX->open ($path, log_cb => sub { warn $_[1] })
168 or die "$path: failed to open\n";
169
170 To successfully open another database, you might have to duplicate some of
171 the settings, e.g. whether mutex locking is used or the hash function. The
172 C<log_cb> output usually will tell you what's wrong.
173
174 To open a tdb file with good performance for many thousands of large keys,
175 maybe not compatible to other programs:
176
177 my $tdb = TDB_FileX->open ($path,
178 hash_size => 10000,
179 hash => "xxh3",
180 mutex => 1,
181 nocow => 1,
182 log_cb => sub { warn $_[1] },
183 ) or die "$path: failed to open\n";
184
185 The following key-value pairs are understood:
186
187 =over
188
189 =item tdb_flags => $flags (default: C<TDB_FileX::DEFAULT>)
190
191 A set of flags that influence the behaviour and format of the database.
192
193 =over
194
195 =item C<DEFAULT>
196
197 Same as C<0> - no flags.
198
199 =item C<CLEAR_IF_FIRST>
200
201 If this is the first open, wipe the db.
202
203 =item C<INTERNAL>
204
205 In-memory database only, path will be ignored.
206
207 =item C<NOLOCK>
208
209 Don't do any locking.
210
211 =item C<NOMMAP>
212
213 Don't use mmap.
214
215 =item C<NOSYNC>
216
217 Don't use synchronous transactions.
218
219 =item C<SEQNUM>
220
221 Maintain a sequence number.
222
223 =item C<VOLATILE>
224
225 Activate the per-hashchain freelist, default 5. (Same as calling
226 C<set_max_dead> with C<5> instead of the default C<0>).
227
228 =item C<ALLOW_NESTING>
229
230 Allow transactions to nest.
231
232 =item C<DISALLOW_NESTING>
233
234 Disallow transactions to nest.
235
236 =item C<INCOMPATIBLE_HASH>
237
238 Better default hash functioa, but can't be opened by tdb < 1.2.6.
239
240 =item C<MUTEX_LOCKING>
241
242 Optimized locking using robust mutexes if supported,
243
244 =back
245
246 =item open_flags => $flags (default: C<Fcntl::O_RDWR | Fcntl::O_CREAT>)
247
248 Standard open flags, as used in C<sysopen>.
249
250 =item mode => $mode (default: C<0666>)
251
252 Standard file open mode, as use din C<sysopen>. Only used when creating
253 the database file.
254
255 =item hash_size => $int (default: internal to libtdb, but normally C<131>)
256
257 The size of the internal hash table - only used when creating the
258 database. The default is usually very low and only good for a few thousand
259 keys. As a rule of thumb, it should be at least one percent of the number
260 of keys you plan to store, e.g. for C<800000> keys you should use around a
261 size of C<8000>.
262
263 Every hash entry is only 4 octets, os usually it isn't an issue to make the
264 hash table too large.
265
266 To give you an idea of the performance, I inserted about 600000 records,
267 3GB of data, into a TDB file, using different hash sizes.
268
269 size time
270 131 160s
271 256 85s
272 1024 12s
273 4096 5s
274 8192 4s
275
276 As you can see, the default hash table size for this case caused it to
277 use 40 times the time to insert than a larger hash table, the optimum
278 being around 75 keys per hash entry. But the databse easily was cached in
279 memory. If that is not the case, you might want to consider a hash table
280 that is larger than the number of keys you want to store - each hash slot
281 only uses 4 octets.
282
283 =item log_cb => $cb->($level, $msg)
284
285 Sets a code reference that is called with a message and a log level
286 (lower means more important, there are C<DEBUG_FATAL>, C<DEBUG_ERROR>,
287 C<DEBUG_WARNING> and C<DEBUG_TRACE}>). Unlike the "debug" in the name
288 might indicate, if you want to find out why, for instance, you could not
289 open a database, you need to use a logging callback.
290
291 =item hash => $hash (default: C<undef>)
292
293 Selects a hash function to use.
294
295 =over
296
297 =item C<"default"> or C<undef>
298
299 Use autodetection and use either C<"jenkins"> or the original tdb hash function.
300
301 =item C<"jenkins">
302
303 The jenkins hash function. Relatively fast, and recommended for modern tdb databases
304 that need to be interoperable between implementations.
305
306 =item C<"fnv1ax">
307
308 The FNV1-A hash with 32 bit post-mixing. Pretty good and very fast for
309 keys up to 10-20 octets.
310
311 =item C<"xxh3">
312
313 The XXH3 hash. Very good and fast especially for long keys.
314
315 =item value returned by C<register_hash_function>
316
317 Use a custom hash function registered via C<register_hash_function>.
318
319 =back
320
321 =item mutex => $bool (default: C<0>)
322
323 TDB can take advantage of fast interprocess mutexes, which can be
324 orders of magnitude faster than the syscall-based locking used by
325 default, but only works on the same machine.
326
327 Normally, you need to call C<TDB_FileX::runtime_check_for_robust_mutexes>
328 and set the C<MUTEX_LOCKING> flag if support is indicated.
329
330 This option, when enabled, enables C<MUTEX_LOCKING> if it is supported
331 by the platform - which involves a fork when opening the database. When
332 disabled, it will remove the flag.
333
334 It is recommended to keep this one, but enabling this changes the format
335 of the database, so might not be an option if interoperability with other
336 programs is required.
337
338 =item nocow => $bool (default: C<0>)
339
340 Set the no-copy-on-write flag I<iff> this flag is true, C<open_flags>
341 contains C<O_CREAT>, C<tdb_flags> do not contain C<INTERNAL> and this is
342 supported on the platform and filesystem. Copy-on-write filesystems have
343 to make a copy of every block written to, which can both be costly and can
344 cause massive fragmentation of the database file.
345
346 Setting the no-copy-on-write flag (same as C<chattr +C>) disables this,
347 usually at the expense of data protection (checksumming), reducing the
348 safety to the level of a normal filesystem such as ext4.
349
350 This is best effort and usually only takes effect when the
351 database is initially created. If it fails, TDB_FileX will simply
352 continue. Correctness should not be affected either way.
353
354 =back
355
356 There is no explicit close function. The database is closed implicitly
357 when there are no remaining references.
358
359 =item $tdb->store ($key, $value[, $flag=REPLACE]) [CROAK]
360
361 Store $value in the database with key w$key. The $flag defaults to
362 C<REPLACE>, but can also be C<INSERT> or C<MODIFY>, see tdb_store(3) for
363 details.
364
365 =item $tdb->append ($key, $value) [CROAK]
366
367 Appends $data to the data already stored for $key, or creates a new entry with it.
368
369 =item $data = $tdb->fetch ($key) [CROAK]
370
371 Fetch the value associated with $key, or C<undef> if it is not found (or
372 on any error).
373
374 =item $tdb->delete ($key) [CROAK]
375
376 Delete the value associated with $key.
377
378 =item $bool = $tdb->exists ($key)
379
380 Return true if the $key is found, false otherwise.
381
382 =item $key = $tdb->firstkey
383
384 Return the key of the first value in the database. Returns C<undef> on
385 failure or if there are no keys in the database. See tdb_firstkey(3)
386 for details.
387
388 =item $key = $tdb->nextkey ($lastkey)
389
390 Return the next key in the database after $lastkey. Returns C<undef> on
391 failure or if there are no more keys in the database. See tdb_nextkey(3)
392 for details.
393
394 =item $code = $tdb->error
395
396 Returns the current error state of the C<$tdb> object. See the list of
397 error codes given in L<EXPORTS>.
398
399 =item $mesage = $tdb->errorstr
400
401 Returns a printable string that describes the error state of the
402 database.
403
404 =item $tdb->reopen [CROAK]
405
406 Closes and reopens the database. Required after a
407 L<fork|perlfunc/fork>, if both processes wish to use the database.
408
409 B<NB:> If C<reopen> fails, then it is unsafe to call any further methods
410 on C<$tdb>. Thus, the only way to find out I<why> C<reopen> failed is to
411 use a logging function.
412
413 =item TDB_FileX::reopen_all [CROAK]
414
415 Closes and reopens all open databases. See C<reopen>.
416
417 B<NB:> If C<reopen_all> fails, there is no indication of I<which> C<$tdb>
418 objects failed or why. If you have to survive failures, you may wish to do
419 your own C<reopen> loop instead.
420
421 =item $tdb->traverse ($cb->($key, $data)) [CROAK]
422
423 Call $cb for each entry in the database. The callback should return false
424 to continue, or a true value to abort the traversal.
425
426 The callback is called with the key and value as arguments and should
427 return a false value if you wish to continue traversal, and a true value
428 if the traversal should be aborted.
429
430 C<traverse> returns the number of elements traversed. If $cb is C<undef>,
431 then this function simply counts the number of elements.
432
433 =item $tdb->traverse_read ($cb->($key, $data)) [CROAK]
434
435 Like C<traverse>, but only acquires a read lock.
436
437 =item $tdb->set_logging_function ($cb->($level, $msg))
438
439 Set the logging function to use when this database object encounters
440 errors.
441
442 $cb is called with the severity level (an integer) and the message (a
443 string).
444
445 =item $tdb->lockall [CROAK]
446
447 Lock an entire database with an exclusive write lock, returning false on
448 error. The purpose of this call is to avoid locking overhead for many
449 operations, but the database has to be unlocked manually when done.
450
451 =item $tdb->unlockall [CROAK]
452
453 Unlock an entire database previously locked with
454 C<lockall>.
455
456 =item $tdb->lockall_read [CROAK]
457
458 Same as C<lockall>, but uses a shared read lock instead of a writer lock.
459
460 =item $tdb->unlockall_read [CROAK]
461
462 Opposite of C<lockall_read>.
463
464 =item $tdb->lockall_mark [CROAK]
465
466 =item $tdb->lockall_unmark [CROAK]
467
468 These apparently mark and unmark locks internally, but do not actually do
469 locking. Probably you should not use this, but feel free to tell me when
470 these are useful.
471
472 =item $tdb->lockall_nonblock [CROAK]
473
474 =item $success = $tdb->lockall_read_nonblock [CROAK]
475
476 Try to lock, but instead of waiting, fail if the lock could not
477 be acquired. Returns true if the lock could be acquired, false
478 otherwise. Croaks on all other errors.
479
480 =item $tdb->transaction_start [CROAK]
481
482 Starts a transaction - all operations will be queued, but not applied
483 to the database, until the transaction is either committed C<transaction_commit>
484 or aborted/thrown away, with C<transaction_cancel>.
485
486 =item $tdb->transaction_start_nonblock [CROAK]
487
488 Tries to start a transaction, but instead of waiting, fail if the lock
489 could not be acquired. Returns true if the transaction could be started,
490 false otherwise. Croaks on all other errors.
491
492 Please tell me what this does.
493
494 =item $tdb->transaction_commit [CROAK]
495
496 Applies all changes in the transaction.
497
498 =item $tdb->transaction_cancel [CROAK]
499
500 Throws away all changes in the transaction.
501
502 =item $tdb->transaction_prepare_commit [CROAK]
503
504 Instead of calling C<transaction_commit> you can do the commit in
505 two phases by calling this method before commit, which does the expensive
506 steps first.
507
508 =item $bool = $tdb->transaction_active
509
510 Returns true if a transaction is currently active.
511
512 =item $tdb->enable_seqnum
513
514 Enables sequence number generatiuon supporet for the database.
515
516 =item $seq = $tdb->get_seqnum
517
518 Returns the current sequence number. Internally, this is a 32 bit unsigned
519 integer, but the API converts it into a native integer, so the same
520 internal sequence number might be represented differently on different
521 machines.
522
523 =item $tdb->increment_seqnum_nonblock
524
525 Increments the sequence number. Note that the sequence number is also
526 incremented by TDB itself oon many operations.
527
528 =item $size = $tdb->hash_size
529
530 Returns the size of the hash table. The size cannot be changed other than
531 by recreating the database.
532
533 =item $octets = $tdb->map_size
534
535 Returns the current mmap size for the database.
536
537 =item $flags = $tdb->get_flags
538
539 Returns the flags for the database (the same as the C<tdb_flags> in C<open>).
540
541 =item $tdb->add_flags ($flag)
542
543 Tried to add flags to the database - yes, the parameter says C<$flag> (singular)
544 but the documentation and the code say I<flags> (plural).
545
546 =item $tdb->remove_flags ($flag)
547
548 Attempts to remove flags from the database.
549
550 =item $tdb->set_max_dead ($max_dead)
551
552 Set the maximum number of dead records per hash chain.
553
554 =item $fileno = $tdb->fd
555
556 Returns the file descriptor (not file handle) for the underlying database file.
557
558 =item $path = $tdb->name
559
560 Returns the path used to open the database.
561
562 =item $tdb->wipe_all [CROAK]
563
564 Efficientlly deletes all entries in the database. This does not shrink the
565 file itself.
566
567 =item $tdb->repack [CROAK]
568
569 Tries to improve layout of the database by copying all items into a
570 temporary in-memory database, wiping the database, and copying all items
571 back. Yes, everything must fit into memory.
572
573 =item $bool = $tdb->check ($cb->($key, $value))
574
575 Does extensive checks on the database, optionally (if not C<undef>)
576 calling a check function for each pair, which must return true if the data
577 is valid.
578
579 Returns a boolean indicating whether the database was found healthy and
580 all the calls to the callback returned true.
581
582 =item $bool = $tdb->rescue ($cb->($key, $value))
583
584 Tries to recover some or all key-value pairs from a potentially damanged
585 database file. For each recovered pair it calls the given callback.
586
587 Returns a boolean indicating whether the database was found healthy and
588 all the calls to the callback returned true.
589
590 =item $bool = TDB_FileX::runtime_check_for_robust_mutexes
591
592 Tests whether robust mutexes are available for locking. This involves
593 forking the process, so it can be costly and problematic. This function
594 needs to be called before using the C<MUTEX_LOCKING> flag. But see the
595 C<mutex> parametrer to C<open> for an alternative.
596
597 =item $tdb->dump_all
598
599 Dump the records and freelist to STDOUT in an almost human readable
600 form.
601
602 =item $summary = $tdb->summary
603
604 Return a textual summary of the database. The format isn't documented,
605 but for some random databas,e I got this output:
606
607 Size of file/data: 325001216/238324906
608 Header offset/logical size: 4001792/320999424
609 Number of records: 117209
610 Incompatible hash: no
611 Active/supported feature flags: 0x00000001/0x00000001
612 Robust mutexes locking: yes
613 Smallest/average/largest keys: 11/36/102
614 Smallest/average/largest data: 10/1997/2921430
615 Smallest/average/largest padding: 9/530/749374
616 Number of dead records: 0
617 Smallest/average/largest dead records: 0/0/0
618 Number of free records: 1126
619 Smallest/average/largest free records: 12/15312/14681136
620 Number of hash chains: 100000
621 Smallest/average/largest hash chains: 0/1/8
622 Number of uncoalesced records: 0
623 Smallest/average/largest uncoalesced runs: 0/0/0
624 Percentage keys/data/padding/free/dead/rechdrs&tailers/hashes: 1/72/19/5/0/1/0
625
626 =item $octets = $tdb->freelist_size
627
628 Returns the total number of free (unused) octets in the file.
629
630 =item $tdb->printfreelist
631
632 Dump the freelist to STDOUT.
633
634 =item $num_entries = $tdb->validate_freelist [CROAK]
635
636 Verifies consistency of freelist and return the number of entries. This
637 loads the whole freelist into memory, using an in-memory tdb database,
638 which did strike Jeremy as extremely clever.
639
640 =item $func = TDB_FileX::register_hash_function $callback->($key)
641
642 Registers a custom hash function. The callback should take a key and
643 return a 32 bit integer hash of it.
644
645 Returns a value that is suitable to be used as the name of a hash function
646 (C<hash> argument to C<open>).
647
648 A maximum of four custom hash functions cna be registered.
649
650 =item TDB_FileX::unrregister_hash_function ($func)
651
652 Frees the hash function registered by a previous call to
653 C<register_hash_function>. Note that you I<MUST NOT> unregister a function
654 that is still in use.
655
656 =back
657
658 =head2 EXPORTS
659
660 Nothing constants are exported by default.
661
662 The tag C<:all> exports allpo of the constants.
663
664 Individually or with the tag C<:flags>:
665
666 DEFAULT
667 CLEAR_IF_FIRST
668 INTERNAL
669 NOLOCK
670 NOMMAP
671 CONVERT
672 BIGENDIAN
673 NOSYNC
674 SEQNUM
675 VOLATILE
676 ALLOW_NESTING
677 DISALLOW_NESTING
678 INCOMPATIBLE_HASH
679 MUTEX_LOCKING
680
681 Individually or with the tag C<:insert>:
682
683 REPLACE
684 INSERT
685 MODIFY
686
687 Individually or with the tag C<:error>:
688
689 SUCCESS
690 ERR_CORRUPT
691 ERR_IO
692 ERR_LOCK
693 ERR_OOM
694 ERR_EXISTS
695 ERR_NOLOCK
696 ERR_LOCK_TIMEOUT
697 ERR_NOEXIST
698 ERR_EINVAL
699 ERR_RDONLY
700
701 Individually or with the tag C<:debug>:
702
703 DEBUG_FATAL
704 DEBUG_ERROR
705 DEBUG_WARNING
706 DEBUG_TRACE
707
708 =head1 UNICODE HANDLING
709
710 TDB databases can only store octet strings. Unlike most other database
711 interfaces, TDB_FileX will safely handle Perl strings by downgrading
712 them. Perl will warn about strings that cnanot be downgraded.
713
714 =head1 DISK USAGE
715
716 TDB databses use 24 octets for every key-value pair, plus the octet size
717 of the key and sata, e.g. the pair "key" => "value" takes up 24+3+5 octets
718 on disk.
719
720 The database header is 168 octets (if I haven't miscounted).
721
722 Each hashtable entry is 4 octets, and one more than the hash size is
723 allocated, so the hash table size is (hash_size + 1) * 4.
724
725 =head1 LIMITATIONS
726
727 =head2 Database Size
728
729 As far as I can see, TDB databases are limited to 4 GB.
730
731 =head2 Hash Functions
732
733 Hash functioons need to be set globally - they are limited to a maximum of
734 4, but this can be easily extended, but requires source code editing. This
735 is due to a limitation of the TDB C API.
736
737 =head2 No recovery after failed C<reopoen_all>
738
739 There is no way to survive an error during C<reopen_all>.
740 Unfortunately this is a limitation in the TDB C API.
741
742 =head2 No way to resize hash table
743
744 Performance degrades majorly when the databse grows larger then
745 accomodated by the hash table size, and the hash table size needs to be
746 set at database creation time and cannot be resized later.
747
748 =head1 SEE ALSO
749
750 tdb(3), L<perltie>.
751
752 =head1 AUTHOR
753
754 Angus Lees, E<lt>gus@inodes.org>
755
756 Currently maintained by Marc A. Lehmann <schmorp@schmorp.de>
757 http://home.schmorp.de/
758
759 =cut