BerkeleyDB
view release on metacpan or search on metacpan
BerkeleyDB.pod.P view on Meta::CPAN
BerkeleyDB - Perl extension for Berkeley DB version 2, 3, 4, 5 or 6
=head1 SYNOPSIS
use BerkeleyDB;
$env = new BerkeleyDB::Env [OPTIONS] ;
$db = tie %hash, 'BerkeleyDB::Hash', [OPTIONS] ;
$db = new BerkeleyDB::Hash [OPTIONS] ;
$db = tie %hash, 'BerkeleyDB::Btree', [OPTIONS] ;
$db = new BerkeleyDB::Btree [OPTIONS] ;
$db = tie @array, 'BerkeleyDB::Recno', [OPTIONS] ;
$db = new BerkeleyDB::Recno [OPTIONS] ;
$db = tie @array, 'BerkeleyDB::Queue', [OPTIONS] ;
$db = new BerkeleyDB::Queue [OPTIONS] ;
$db = new BerkeleyDB::Heap [OPTIONS] ;
$db = new BerkeleyDB::Unknown [OPTIONS] ;
$status = BerkeleyDB::db_remove [OPTIONS]
$status = BerkeleyDB::db_rename [OPTIONS]
$status = BerkeleyDB::db_verify [OPTIONS]
$hash{$key} = $value ;
$value = $hash{$key} ;
each %hash ;
keys %hash ;
values %hash ;
$env = $db->Env()
$status = $db->db_get()
$status = $db->db_exists() ;
$status = $db->db_put() ;
$status = $db->db_del() ;
$status = $db->db_sync() ;
$status = $db->db_close() ;
$status = $db->db_pget()
$hash_ref = $db->db_stat() ;
$status = $db->db_key_range();
$type = $db->type() ;
$status = $db->status() ;
$boolean = $db->byteswapped() ;
$status = $db->truncate($count) ;
$status = $db->compact($start, $stop, $c_data, $flags, $end);
$status = $db->get_blob_threshold($t1) ;
$status = $db->get_blob_dir($dir) ;
$bool = $env->cds_enabled();
$bool = $db->cds_enabled();
$lock = $db->cds_lock();
$lock->cds_unlock();
($flag, $old_offset, $old_length) = $db->partial_set($offset, $length) ;
($flag, $old_offset, $old_length) = $db->partial_clear() ;
$cursor = $db->db_cursor([$flags]) ;
$newcursor = $cursor->c_dup([$flags]);
$status = $cursor->c_get() ;
$status = $cursor->c_put() ;
$status = $cursor->c_del() ;
$status = $cursor->c_count() ;
$status = $cursor->c_pget() ;
$status = $cursor->status() ;
$status = $cursor->c_close() ;
$stream = $cursor->db_stream() ;
$cursor = $db->db_join() ;
$status = $cursor->c_get() ;
$status = $cursor->c_close() ;
$status = $stream->size($S);
$status = $stream->read($data, $offset, $size);
$status = $stream->write($data, $offset);
$status = $env->txn_checkpoint()
$hash_ref = $env->txn_stat()
$status = $env->set_mutexlocks()
$status = $env->set_flags()
$status = $env->set_timeout()
$status = $env->lock_detect()
$status = $env->lsn_reset()
$status = $env->get_blob_threshold($t1) ;
$status = $env->get_blob_dir($dir) ;
$txn = $env->txn_begin() ;
$db->Txn($txn);
$txn->Txn($db1, $db2,...);
$status = $txn->txn_prepare()
$status = $txn->txn_commit()
$status = $txn->txn_abort()
$status = $txn->txn_id()
$status = $txn->txn_discard()
$status = $txn->set_timeout()
$status = $env->set_lg_dir();
$status = $env->set_lg_bsize();
$status = $env->set_lg_max();
$status = $env->set_data_dir() ;
$status = $env->set_tmp_dir() ;
$status = $env->set_verbose() ;
$db_env_ptr = $env->DB_ENV() ;
$BerkeleyDB::Error
$BerkeleyDB::db_version
# DBM Filters
$old_filter = $db->filter_store_key ( sub { ... } ) ;
$old_filter = $db->filter_store_value( sub { ... } ) ;
$old_filter = $db->filter_fetch_key ( sub { ... } ) ;
$old_filter = $db->filter_fetch_value( sub { ... } ) ;
# deprecated, but supported
$txn_mgr = $env->TxnMgr();
$status = $txn_mgr->txn_checkpoint()
$hash_ref = $txn_mgr->txn_stat()
$txn = $txn_mgr->txn_begin() ;
=head1 DESCRIPTION
B<NOTE: This document is still under construction. Expect it to be
incomplete in places.>
This Perl module provides an interface to most of the functionality
available in Berkeley DB versions 2, 3, 5 and 6. In general it is safe to assume
that the interface provided here to be identical to the Berkeley DB
interface. The main changes have been to make the Berkeley DB API work
in a Perl way. Note that if you are using Berkeley DB 2.x, the new
features available in Berkeley DB 3.x or later are not available via
this module.
The reader is expected to be familiar with the Berkeley DB
documentation. Where the interface provided here is identical to the
Berkeley DB library and the... TODO
The B<db_appinit>, B<db_cursor>, B<db_open> and B<db_txn> man pages are
particularly relevant.
The interface to Berkeley DB is implemented with a number of Perl
classes.
=head1 The BerkeleyDB::Env Class
The B<BerkeleyDB::Env> class provides an interface to the Berkeley DB
function B<db_appinit> in Berkeley DB 2.x or B<db_env_create> and
B<DBENV-E<gt>open> in Berkeley DB 3.x (or later). Its purpose is to initialise a
number of sub-systems that can then be used in a consistent way in all
the databases you make use of in the environment.
If you don't intend using transactions, locking or logging, then you
shouldn't need to make use of B<BerkeleyDB::Env>.
Note that an environment consists of a number of files that Berkeley DB
manages behind the scenes for you. When you first use an environment, it
needs to be explicitly created. This is done by including C<DB_CREATE>
with the C<Flags> parameter, described below.
=head2 Synopsis
$env = new BerkeleyDB::Env
[ -Home => $path, ]
[ -Server => $name, ]
[ -CacheSize => $number, ]
[ -Config => { name => value, name => value }, ]
[ -ErrFile => filename, ]
[ -MsgFile => filename, ]
[ -ErrPrefix => "string", ]
[ -Flags => number, ]
[ -SetFlags => bitmask, ]
[ -LockDetect => number, ]
[ -TxMax => number, ]
[ -LogConfig => number, ]
[ -MaxLockers => number, ]
[ -MaxLocks => number, ]
[ -MaxObjects => number, ]
[ -SharedMemKey => number, ]
[ -Verbose => boolean, ]
[ -BlobThreshold=> $number, ]
[ -BlobDir => directory, ]
[ -Encrypt => { Password => "string",
Flags => number }, ]
All the parameters to the BerkeleyDB::Env constructor are optional.
=over 5
=item -Home
If present, this parameter should point to an existing directory. Any
files that I<aren't> specified with an absolute path in the sub-systems
that are initialised by the BerkeleyDB::Env class will be assumed to
live in the B<Home> directory.
For example, in the code fragment below the database "fred.db" will be
opened in the directory "/home/databases" because it was specified as a
relative path, but "joe.db" will be opened in "/other" because it was
BerkeleyDB.pod.P view on Meta::CPAN
=back
The variant C<db_pget> allows you to query a secondary database:
$status = $sdb->db_pget($skey, $pkey, $value);
using the key C<$skey> in the secondary db to lookup C<$pkey> and C<$value>
from the primary db.
=head2 $status = $db->db_exists($key [, $flags])
This method checks for the existence of the given key (C<$key>), but
does not read the value. If the key is not found, B<db_exists> will
return B<DB_NOTFOUND>. Requires BDB 4.6 or better.
=head2 $status = $db->db_put($key, $value [, $flags])
Stores a key/value pair in the database.
The B<$flags> parameter is optional. If present it must be set to B<one>
of the following values:
=over 5
=item B<DB_APPEND>
This flag is only applicable when accessing a B<BerkeleyDB::Recno>
database.
TODO.
=item B<DB_NOOVERWRITE>
If this flag is specified and C<$key> already exists in the database,
the call to B<db_put> will return B<DB_KEYEXIST>.
=back
=head2 $status = $db->db_del($key [, $flags])
Deletes a key/value pair in the database associated with C<$key>.
If duplicate keys are enabled in the database, B<db_del> will delete
B<all> key/value pairs with key C<$key>.
The B<$flags> parameter is optional and is currently unused.
=head2 $status = $env->stat_print([$flags])
Prints statistical information.
If the C<MsgFile> option is specified the output will be sent to the
file. Otherwise output is sent to standard output.
This option requires Berkeley DB 4.3 or better.
=head2 $status = $db->db_sync()
If any parts of the database are in memory, write them to the database.
=head2 $cursor = $db->db_cursor([$flags])
Creates a cursor object. This is used to access the contents of the
database sequentially. See L<CURSORS> for details of the methods
available when working with cursors.
The B<$flags> parameter is optional. If present it must be set to B<one>
of the following values:
=over 5
=item B<DB_RMW>
TODO.
=back
=head2 ($flag, $old_offset, $old_length) = $db->partial_set($offset, $length) ;
TODO
=head2 ($flag, $old_offset, $old_length) = $db->partial_clear() ;
TODO
=head2 $db->byteswapped()
TODO
=head2 $status = $db->get_blob_threshold($t1) ;
Sets the parameter $t1 to the threshold value (in bytes) that is used to
determine when a data item is stored as a Blob.
=head2 $status = $db->get_blob_dir($dir) ;
Sets the $dir parameter to the directory where blob files are stored.
=head2 $db->type()
Returns the type of the database. The possible return code are B<DB_HASH>
for a B<BerkeleyDB::Hash> database, B<DB_BTREE> for a B<BerkeleyDB::Btree>
database and B<DB_RECNO> for a B<BerkeleyDB::Recno> database. This method
is typically used when a database has been opened with
B<BerkeleyDB::Unknown>.
=head2 $bool = $env->cds_enabled();
Returns true if the Berkeley DB environment C<$env> has been opened on
CDS mode.
=head2 $bool = $db->cds_enabled();
Returns true if the database C<$db> has been opened on CDS mode.
=head2 $lock = $db->cds_lock();
Creates a CDS write lock object C<$lock>.
It is a fatal error to attempt to create a cds_lock if the Berkeley DB
environment has not been opened in CDS mode.
=head2 $lock->cds_unlock();
Removes a CDS lock. The destruction of the CDS lock object automatically
BerkeleyDB.pod.P view on Meta::CPAN
=over 5
=item * compact_deadlock
=item * compact_levels
=item * compact_pages_free
=item * compact_pages_examine
=item * compact_pages_truncated
=back
You need to be running Berkeley DB 4.4 or better if you want to make use of
C<compact>.
=head2 $status = $db->associate($secondary, \&key_callback)
Associate C<$db> with the secondary DB C<$secondary>
New key/value pairs inserted to the database will be passed to the callback
which must set its third argument to the secondary key to allow lookup. If
an array reference is set multiple keys secondary keys will be associated
with the primary database entry.
Data may be retrieved fro the secondary database using C<db_pget> to also
obtain the primary key.
Secondary databased are maintained automatically.
=head2 $status = $db->associate_foreign($secondary, callback, $flags)
Associate a foreign key database C<$db> with the secondary DB
C<$secondary>.
The second parameter must be a reference to a sub or C<undef>.
The C<$flags> parameter must be either C<DB_FOREIGN_CASCADE>,
C<DB_FOREIGN_ABORT> or C<DB_FOREIGN_NULLIFY>.
When the flags parameter is C<DB_FOREIGN_NULLIFY> the second parameter is a
reference to a sub of the form
sub foreign_cb
{
my $key = \$_[0];
my $value = \$_[1];
my $foreignkey = \$_[2];
my $changed = \$_[3] ;
# for ... set $$value and set $$changed to 1
return 0;
}
$foreign_db->associate_foreign($secondary, \&foreign_cb, DB_FOREIGN_NULLIFY);
=head1 CURSORS
A cursor is used whenever you want to access the contents of a database
in sequential order.
A cursor object is created with the C<db_cursor>
A cursor object has the following methods available:
=head2 $newcursor = $cursor->c_dup($flags)
Creates a duplicate of C<$cursor>. This method needs Berkeley DB 3.0.x or better.
The C<$flags> parameter is optional and can take the following value:
=over 5
=item DB_POSITION
When present this flag will position the new cursor at the same place as the
existing cursor.
=back
=head2 $status = $cursor->c_get($key, $value, $flags)
Reads a key/value pair from the database, returning the data in C<$key>
and C<$value>. The key/value pair actually read is controlled by the
C<$flags> parameter, which can take B<one> of the following values:
=over 5
=item B<DB_FIRST>
Set the cursor to point to the first key/value pair in the
database. Return the key/value pair in C<$key> and C<$value>.
=item B<DB_LAST>
Set the cursor to point to the last key/value pair in the database. Return
the key/value pair in C<$key> and C<$value>.
=item B<DB_NEXT>
If the cursor is already pointing to a key/value pair, it will be
incremented to point to the next key/value pair and return its contents.
If the cursor isn't initialised, B<DB_NEXT> works just like B<DB_FIRST>.
If the cursor is already positioned at the last key/value pair, B<c_get>
will return B<DB_NOTFOUND>.
=item B<DB_NEXT_DUP>
This flag is only valid when duplicate keys have been enabled in
a database.
If the cursor is already pointing to a key/value pair and the key of
the next key/value pair is identical, the cursor will be incremented to
point to it and their contents returned.
=item B<DB_PREV>
If the cursor is already pointing to a key/value pair, it will be
decremented to point to the previous key/value pair and return its
contents.
If the cursor isn't initialised, B<DB_PREV> works just like B<DB_LAST>.
If the cursor is already positioned at the first key/value pair, B<c_get>
will return B<DB_NOTFOUND>.
=item B<DB_CURRENT>
If the cursor has been set to point to a key/value pair, return their
contents.
If the key/value pair referenced by the cursor has been deleted, B<c_get>
will return B<DB_KEYEMPTY>.
=item B<DB_SET>
Set the cursor to point to the key/value pair referenced by B<$key>
and return the value in B<$value>.
=item B<DB_SET_RANGE>
This flag is a variation on the B<DB_SET> flag. As well as returning
the value, it also returns the key, via B<$key>.
When used with a B<BerkeleyDB::Btree> database the key matched by B<c_get>
will be the shortest key (in length) which is greater than or equal to
the key supplied, via B<$key>. This allows partial key searches.
See ??? for an example of how to use this flag.
=item B<DB_GET_BOTH>
Another variation on B<DB_SET>. This one returns both the key and
the value.
=item B<DB_SET_RECNO>
TODO.
=item B<DB_GET_RECNO>
TODO.
=back
In addition, the following value may be set by bitwise OR'ing it into
the B<$flags> parameter:
=over 5
=item B<DB_RMW>
TODO.
=back
=head2 $status = $cursor->c_put($key, $value, $flags)
Stores the key/value pair in the database. The position that the data is
stored in the database is controlled by the C<$flags> parameter, which
must take B<one> of the following values:
=over 5
=item B<DB_AFTER>
When used with a Btree or Hash database, a duplicate of the key referenced
by the current cursor position will be created and the contents of
B<$value> will be associated with it - B<$key> is ignored.
The new key/value pair will be stored immediately after the current
cursor position.
Obviously the database has to have been opened with B<DB_DUP>.
When used with a Recno ... TODO
=item B<DB_BEFORE>
When used with a Btree or Hash database, a duplicate of the key referenced
by the current cursor position will be created and the contents of
B<$value> will be associated with it - B<$key> is ignored.
The new key/value pair will be stored immediately before the current
cursor position.
Obviously the database has to have been opened with B<DB_DUP>.
When used with a Recno ... TODO
=item B<DB_CURRENT>
If the cursor has been initialised, replace the value of the key/value
pair stored in the database with the contents of B<$value>.
=item B<DB_KEYFIRST>
Only valid with a Btree or Hash database. This flag is only really
used when duplicates are enabled in the database and sorted duplicates
haven't been specified.
In this case the key/value pair will be inserted as the first entry in
the duplicates for the particular key.
=item B<DB_KEYLAST>
Only valid with a Btree or Hash database. This flag is only really
used when duplicates are enabled in the database and sorted duplicates
haven't been specified.
In this case the key/value pair will be inserted as the last entry in
the duplicates for the particular key.
=back
=head2 $status = $cursor->c_del([$flags])
This method deletes the key/value pair associated with the current cursor
position. The cursor position will not be changed by this operation, so
any subsequent cursor operation must first initialise the cursor to
point to a valid key/value pair.
If the key/value pair associated with the cursor have already been
deleted, B<c_del> will return B<DB_KEYEMPTY>.
The B<$flags> parameter is not used at present.
=head2 $status = $cursor->c_count($cnt [, $flags])
Stores the number of duplicates at the current cursor position in B<$cnt>.
The B<$flags> parameter is not used at present. This method needs
Berkeley DB 3.1 or better.
=head2 $status = $cursor->status()
Returns the status of the last cursor method as a dual type.
=head2 $status = $cursor->c_pget() ;
See C<db_pget>
=head2 $status = $cursor->c_close()
Closes the cursor B<$cursor>.
=head2 $stream = $cursor->db_stream($flags);
Create a BerkeleyDB::DbStream object to read the blob at the current cursor location.
See L<Blob> for details of the the BerkeleyDB::DbStream object.
$flags must be one or more of the following OR'ed together
DB_STREAM_READ
DB_STREAM_WRITE
DB_STREAM_SYNC_WRITE
For full information on the flags refer to the Berkeley DB Reference Guide.
=head2 Cursor Examples
TODO
Iterating from first to last, then in reverse.
examples of each of the flags.
=head1 JOIN
Join support for BerkeleyDB is in progress. Watch this space.
TODO
=head1 TRANSACTIONS
Transactions are created using the C<txn_begin> method on L<BerkeleyDB::Env>:
my $txn = $env->txn_begin;
If this is a nested transaction, supply the parent transaction as an
argument:
my $child_txn = $env->txn_begin($parent_txn);
Then in order to work with the transaction, you must set it as the current
transaction on the database handles you want to work with:
$db->Txn($txn);
Or for multiple handles:
$txn->Txn(@handles);
The current transaction is given by BerkeleyDB each time to the various BDB
operations. In the C api it is required explicitly as an argument to every
operation.
To commit a transaction call the C<commit> method on it:
$txn->txn_commit;
and to roll back call abort:
$txn->txn_abort
After committing or aborting a child transaction you need to set the active
transaction again using C<Txn>.
=head1 BerkeleyDBB::DbStream -- support for BLOB
Blob support is available in Berkeley DB starting with version 6.0. Refer
to the section "Blob Support" in the Berkeley DB Programmer Reference for
details of how Blob supports works.
A Blob is access via a BerkeleyDBB::DbStream object. This is created via a
cursor object.
# Note - error handling not shown below.
# Set the key we want
my $k = "some key";
# Don't want the value retrieved by the cursor,
# so use partial_set to make sure no data is retrieved.
my $v = '';
$cursor->partial_set(0,0) ;
$cursor->c_get($k, $v, DB_SET) ;
$cursor->partial_clear() ;
# Now create a stream to the blob
my $stream = $cursor->db_stream(DB_STREAM_WRITE) ;
# get the size of the blob
$stream->size(my $s) ;
# Read the first 1k of data from the blob
my $data ;
$stream->read($data, 0, 1024);
A BerkeleyDB::DbStream object has the following methods available:
=head2 $status = $stream->size($SIZE);
Outputs the length of the Blob in the $SIZE parameter.
=head2 $status = $stream->read($data, $offset, $size);
Read from the blob. $offset is the number of bytes from the start of the
blob to read from. $size if the number of bytes to read.
=head2 $status = $stream->write($data, $offset, $flags);
Write $data to the blob, starting at offset $offset.
Example
Below is an example of how to walk through a database when you don't know
beforehand which entries are blobs and which are not.
while (1)
{
my $k = '';
my $v = '';
$cursor->partial_set(0,0) ;
my $status = $cursor->c_get($k, $v, DB_NEXT) ;
$cursor->partial_clear();
last if $status != 0 ;
my $stream = $cursor->db_stream(DB_STREAM_WRITE);
if (defined $stream)
{
# It's a Blob
$stream->size(my $s) ;
}
else
{
# Not a Blob
$cursor->c_get($k, $v, DB_CURRENT) ;
}
}
=head1 Berkeley DB Concurrent Data Store (CDS)
The Berkeley DB I<Concurrent Data Store> (CDS) is a lightweight locking
mechanism that is useful in scenarios where transactions are overkill.
=head2 What is CDS?
The Berkeley DB CDS interface is a simple lightweight locking mechanism
that allows safe concurrent access to Berkeley DB databases. Your
application can have multiple reader and write processes, but Berkeley DB
will arrange it so that only one process can have a write lock against the
database at a time, i.e. multiple processes can read from a database
concurrently, but all write processes will be serialised.
=head2 Should I use it?
Whilst this simple locking model is perfectly adequate for some
applications, it will be too restrictive for others. Before deciding on
using CDS mode, you need to be sure that it is suitable for the expected
behaviour of your application.
The key features of this model are
=over 5
=item *
All writes operations are serialised.
=item *
A write operation will block until all reads have finished.
=back
There are a few of the attributes of your application that you need to be
aware of before choosing to use CDS.
Firstly, if you application needs either recoverability or transaction
support, then CDS will not be suitable.
Next what is the ratio of read operation to write operations will your
application have?
If it is carrying out mostly read operations, and very few writes, then CDS
may be appropriate.
What is the expected throughput of reads/writes in your application?
If you application does 90% writes and 10% reads, but on average you only
have a transaction every 5 seconds, then the fact that all writes are
serialised will not matter, because there will hardly ever be multiple
writes processes blocking.
In summary CDS mode may be appropriate for your application if it performs
mostly reads and very few writes or there is a low throughput. Also, if
you do not need to be able to roll back a series of database operations if
an error occurs, then CDS is ok.
If any of these is not the case you will need to use Berkeley DB
transactions. That is outside the scope of this document.
=head2 Locking Used
Berkeley DB implements CDS mode using two kinds of lock behind the scenes -
namely read locks and write locks. A read lock allows multiple processes to
access the database for reading at the same time. A write lock will only
get access to the database when there are no read or write locks active.
The write lock will block until the process holding the lock releases it.
Multiple processes with read locks can all access the database at the same
time as long as no process has a write lock. A process with a write lock
can only access the database if there are no other active read or write
locks.
The majority of the time the Berkeley DB CDS mode will handle all locking
without your application having to do anything. There are a couple of
exceptions you need to be aware of though - these will be discussed in
L<Safely Updating Records> and L<Implicit Cursors> below.
A Berkeley DB Cursor (created with C<< $db->db_cursor >>) will by hold a
lock on the database until it is either explicitly closed or destroyed.
This means the lock has the potential to be long lived.
By default Berkeley DB cursors create a read lock, but it is possible to
create a cursor that holds a write lock, thus
$cursor = $db->db_cursor(DB_WRITECURSOR);
Whilst either a read or write cursor is active, it will block any other
processes that wants to write to the database.
To avoid blocking problems, only keep cursors open as long as they are
needed. The same is true when you use the C<cursor> method or the
C<cds_lock> method.
For full information on CDS see the "Berkeley DB Concurrent Data Store
applications" section in the Berkeley DB Reference Guide.
=head2 Opening a database for CDS
Here is the typical signature that is used when opening a database in CDS
mode.
use BerkeleyDB ;
my $env = new BerkeleyDB::Env
-Home => "./home" ,
-Flags => DB_CREATE| DB_INIT_CDB | DB_INIT_MPOOL
or die "cannot open environment: $BerkeleyDB::Error\n";
my $db = new BerkeleyDB::Hash
-Filename => 'test1.db',
-Flags => DB_CREATE,
-Env => $env
or die "cannot open database: $BerkeleyDB::Error\n";
or this, if you use the tied interface
tie %hash, "BerkeleyDB::Hash",
-Filename => 'test2.db',
-Flags => DB_CREATE,
-Env => $env
or die "cannot open database: $BerkeleyDB::Error\n";
The first thing to note is that you B<MUST> always use a Berkeley DB
environment if you want to use locking with Berkeley DB.
Remember, that apart from the actual database files you explicitly create
yourself, Berkeley DB will create a few behind the scenes to handle locking
- they usually have names like "__db.001". It is therefore a good idea to
use the C<-Home> option, unless you are happy for all these files to be
written in the current directory.
Next, remember to include the C<DB_CREATE> flag when opening the
environment for the first time. A common mistake is to forget to add this
option and then wonder why the application doesn't work.
Finally, it is vital that all processes that are going to access the
database files use the same Berkeley DB environment.
=head2 Safely Updating a Record
One of the main gotchas when using CDS is if you want to update a record in
a database, i.e. you want to retrieve a record from a database, modify it
in some way and put it back in the database.
For example, say you are writing a web application and you want to keep a
record of the number of times your site is accessed in a Berkeley DB
database. So your code will have a line of code like this (assume, of
course, that C<%hash> has been tied to a Berkeley DB database):
$hash{Counter} ++ ;
That may look innocent enough, but there is a race condition lurking in
there. If I rewrite the line of code using the low-level Berkeley DB API,
which is what will actually be executed, the race condition may be more
apparent:
$db->db_get("Counter", $value);
++ $value ;
$db->db_put("Counter", $value);
Consider what happens behind the scenes when you execute the commands
above. Firstly, the existing value for the key "Counter" is fetched from
the database using C<db_get>. A read lock will be used for this part of the
update. The value is then incremented, and the new value is written back
to the database using C<db_put>. This time a write lock will be used.
Here's the problem - there is nothing to stop two (or more) processes
executing the read part at the same time. Remember multiple processes can
hold a read lock on the database at the same time. So both will fetch the
same value, let's say 7, from the database. Both increment the value to 8
and attempt to write it to the database. Berkeley DB will ensure that only
one of the processes gets a write lock, while the other will be blocked. So
the process that happened to get the write lock will store the value 8 to
the database and release the write lock. Now the other process will be
unblocked, and it too will write the value 8 to the database. The result,
in this example, is we have missed a hit in the counter.
To deal with this kind of scenario, you need to make the update atomic. A
convenience method, called C<cds_lock>, is supplied with the BerkeleyDB
module for this purpose. Using C<cds_lock>, the counter update code can now
be rewritten thus:
my $lk = $dbh->cds_lock() ;
$hash{Counter} ++ ;
$lk->cds_unlock;
or this, where scoping is used to limit the lifetime of the lock object
{
my $lk = $dbh->cds_lock() ;
$hash{Counter} ++ ;
}
Similarly, C<cds_lock> can be used with the native Berkeley DB API
my $lk = $dbh->cds_lock() ;
$db->db_get("Counter", $value);
++ $value ;
$db->db_put("Counter", $value);
$lk->unlock;
The C<cds_lock> method will ensure that the current process has exclusive
access to the database until the lock is either explicitly released, via
the C<< $lk->cds_unlock() >> or by the lock object being destroyed.
If you are interested, all that C<cds_lock> does is open a "write" cursor.
This has the useful side-effect of holding a write-lock on the database
until the cursor is deleted. This is how you create a write-cursor
$cursor = $db->db_cursor(DB_WRITECURSOR);
If you have instantiated multiple C<cds_lock> objects for one database
within a single process, that process will hold a write-lock on the
database until I<ALL> C<cds_lock> objects have been destroyed.
As with all write-cursors, you should try to limit the scope of the
C<cds_lock> to as short a time as possible. Remember the complete database
will be locked to other process whilst the write lock is in place.
=head2 Cannot write with a read cursor while a write cursor is active
This issue is easier to demonstrate with an example, so consider the code
below. The intention of the code is to increment the values of all the
elements in a database by one.
# Assume $db is a database opened in a CDS environment.
# Create a write-lock
my $lock = $db->db_cursor(DB_WRITECURSOR);
# or
# my $lock = $db->cds_lock();
my $cursor = $db->db_cursor();
# Now loop through the database, and increment
# each value using c_put.
while ($cursor->c_get($key, $value, DB_NEXT) == 0)
{
$cursor->c_put($key, $value+1, DB_CURRENT) == 0
or die "$BerkeleyDB::Error\n";
}
When this code is run, it will fail on the C<c_put> line with this error
Write attempted on read-only cursor
The read cursor has automatically disallowed a write operation to prevent a
deadlock.
So the rule is -- you B<CANNOT> carry out a write operation using a
read-only cursor (i.e. you cannot use C<c_put> or C<c_del>) whilst another
write-cursor is already active.
The workaround for this issue is to just use C<db_put> instead of C<c_put>,
like this
# Assume $db is a database opened in a CDS environment.
# Create a write-lock
my $lock = $db->db_cursor(DB_WRITECURSOR);
# or
# my $lock = $db->cds_lock();
my $cursor = $db->db_cursor();
# Now loop through the database, and increment
# each value using c_put.
while ($cursor->c_get($key, $value, DB_NEXT) == 0)
{
$db->db_put($key, $value+1) == 0
or die "$BerkeleyDB::Error\n";
}
=head2 Implicit Cursors
All Berkeley DB cursors will hold either a read lock or a write lock on the
database for the existence of the cursor. In order to prevent blocking of
other processes you need to make sure that they are not long lived.
There are a number of instances where the Perl interface to Berkeley DB
will create a cursor behind the scenes without you being aware of it. Most
of these are very short-lived and will not affect the running of your
script, but there are a few notable exceptions.
Consider this snippet of code
while (my ($k, $v) = each %hash)
{
# do something
}
To implement the "each" functionality, a read cursor will be created behind
the scenes to allow you to iterate through the tied hash, C<%hash>. While
that cursor is still active, a read lock will obviously be held against the
database. If your application has any other writing processes, these will
be blocked until the read cursor is closed. That won't happen until the
loop terminates.
To avoid blocking problems, only keep cursors open as long as they are
needed. The same is true when you use the C<cursor> method or the
C<cds_lock> method.
The locking behaviour of the C<values> or C<keys> functions, shown below,
is subtly different.
foreach my $k (keys %hash)
{
# do something
}
foreach my $v (values %hash)
{
# do something
}
Just as in the C<each> function, a read cursor will be created to iterate
over the database in both of these cases. Where C<keys> and C<values>
differ is the place where the cursor carries out the iteration through the
database. Whilst C<each> carried out a single iteration every time it was
invoked, the C<keys> and C<values> functions will iterate through the
entire database in one go -- the complete database will be read into memory
before the first iteration of the loop.
Apart from the fact that a read lock will be held for the amount of time
required to iterate through the database, the use of C<keys> and C<values>
is B<not> recommended because it will result in the complete database being
read into memory.
=head2 Avoiding Deadlock with multiple databases
If your CDS application uses multiple database files, and you need to write
to more than one of them, you need to be careful you don't create a
deadlock.
For example, say you have two databases, D1 and D2, and two processes, P1
and P2. Assume you want to write a record to each database. If P1 writes
the records to the databases in the order D1, D2 while process P2 writes
the records in the order D2, D1, there is the potential for a deadlock to
occur.
This scenario can be avoided by either always acquiring the write locks in
exactly the same order in your application code, or by using the
C<DB_CDB_ALLDB> flag when opening the environment. This flag will make a
write-lock apply to all the databases in the environment.
Add example here
=head1 DBM Filters
A DBM Filter is a piece of code that is be used when you I<always>
want to make the same transformation to all keys and/or values in a DBM
database. All of the database classes (BerkeleyDB::Hash,
BerkeleyDB::Btree and BerkeleyDB::Recno) support DBM Filters.
An example is when you need to encode your data in UTF-8 before writing to
the database and then decode the UTF-8 when reading from the database file.
There are two ways to use a DBM Filter.
=over 5
=item 1.
Using the low-level API defined below.
=item 2.
Using the L<DBM_Filter> module.
This module hides the complexity of the API defined below and comes
with a number of "canned" filters that cover some of the common use-cases.
=back
Use of the L<DBM_Filter> module is recommended.
=head2 DBM Filter Low-level API
( run in 1.215 second using v1.01-cache-2.11-cpan-39bf76dae61 )