DESCRIPTION

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 and 4. 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 DB 4.x 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 interface to Berkeley DB is implemented with a number of Perl classes.

The BerkeleyDB::Env Class

The BerkeleyDB::Env class provides an interface to the Berkeley DB function db_appinit in Berkeley DB 2.x or db_env_create and DBENV->open in Berkeley DB 3.x/4.x. 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 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 DB_CREATE with the Flags parameter, described below.

If present, this parameter should point to an existing directory. Any files that 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 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 part of an absolute path.

Examples

Global Classes

THE DATABASE CLASSES

BerkeleyDB supports the following database formats:

BerkeleyDB::Hash

This database type allows arbitrary key/value pairs to be stored in data files. This is equivalent to the functionality provided by other hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. Remember though, the files created using BerkeleyDB::Hash are not compatible with any of the other packages mentioned.

A default hashing algorithm, which will be adequate for most applications, is built into BerkeleyDB. If you do need to use your own hashing algorithm it is possible to write your own in Perl and have BerkeleyDB use it instead.

BerkeleyDB::Btree

The Btree format allows arbitrary key/value pairs to be stored in a B+tree.

As with the BerkeleyDB::Hash format, it is possible to provide a user defined Perl routine to perform the comparison of keys. By default, though, the keys are stored in lexical order.

BerkeleyDB::Recno

TODO.

BerkeleyDB::Queue

TODO.

BerkeleyDB::Unknown

This isn't a database format at all. It is used when you want to open an existing Berkeley DB database without having to know what type is it.

Each of the database formats described above is accessed via a corresponding BerkeleyDB class. These will be described in turn in the next sections.

BerkeleyDB::Hash

Equivalent to calling db_open with type DB_HASH in Berkeley DB 2.x and calling db_create followed by DB->open with type DB_HASH in Berkeley DB 3.x or greater.

When the "tie" interface is used, reading from and writing to the database is achieved via the tied hash. In this case the database operates like a Perl associative array that happens to be stored on disk.

In addition to the high-level tied hash interface, it is possible to make use of the underlying methods provided by Berkeley DB

Options

In addition to the standard set of options (see "COMMON OPTIONS") BerkeleyDB::Hash supports these options:

-Property

Used to specify extra flags when opening a database. The following flags may be specified by bitwise OR'ing together one or more of the following values:

DB_DUP

When creating a new database, this flag enables the storing of duplicate keys in the database. If DB_DUPSORT is not specified as well, the duplicates are stored in the order they are created in the database.

DB_DUPSORT

Enables the sorting of duplicate keys in the database. Ignored if DB_DUP isn't also specified.

-Ffactor

-Nelem

See the Berkeley DB documentation for details of these options.

-Hash

Allows you to provide a user defined hash function. If not specified, a default hash function is used. Here is a template for a user-defined hash function

Duplicate keys

The code below is a variation on the examples above. This time the hash has been inverted. The key this time is colour and the value is the fruit name. The DB_DUP flag has been specified to allow duplicates.

Sorting Duplicate Keys

In the previous example, when there were duplicate keys, the values are sorted in the order they are stored in. The code below is identical to the previous example except the DB_DUPSORT flag is specified.

Options

In addition to the standard set of options (see "COMMON OPTIONS") BerkeleyDB::Btree supports these options:

-Property

Used to specify extra flags when opening a database. The following flags may be specified by bitwise OR'ing together one or more of the following values:

DB_DUP

When creating a new database, this flag enables the storing of duplicate keys in the database. If DB_DUPSORT is not specified as well, the duplicates are stored in the order they are created in the database.

DB_DUPSORT

Enables the sorting of duplicate keys in the database. Ignored if DB_DUP isn't also specified.

Here is the output from the code above. The keys have been sorted using Berkeley DB's default sorting algorithm.

Smith
Wall
mouse

Changing the sort order

It is possible to supply your own sorting algorithm if the one that Berkeley DB used isn't suitable. The code below is identical to the previous example except for the case insensitive compare function.

($flag, $old_offset, $old_length) = $db->partial_clear() ;

TODO

$db->byteswapped()

TODO

$db->type()

Returns the type of the database. The possible return code are DB_HASH for a BerkeleyDB::Hash database, DB_BTREE for a BerkeleyDB::Btree database and DB_RECNO for a BerkeleyDB::Recno database. This method is typically used when a database has been opened with BerkeleyDB::Unknown.

$bool = $env->cds_enabled();

Returns true if the Berkeley DB environment $env has been opened on CDS mode.

$bool = $db->cds_enabled();

Returns true if the database $db has been opened on CDS mode.

$lock = $db->cds_lock();

Creates a CDS write lock object $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.

$lock->cds_unlock();

Removes a CDS lock. The destruction of the CDS lock object automatically calls this method.

Note that if multiple CDS lock objects are created, the underlying write lock will not be released until all CDS lock objects are either explictly unlocked with this method, or the CDS lock objects have been destroyed.

$ref = $db->db_stat()

Returns a reference to an associative array containing information about the database. The keys of the associative array correspond directly to the names of the fields defined in the Berkeley DB documentation. For example, in the DB documentation, the field bt_version stores the version of the Btree database. Assuming you called db_stat on a Btree database the equivalent field would be accessed as follows:

$version = $ref->{'bt_version'} ;

If you are using Berkeley DB 3.x or better, this method will work will all database formats. When DB 2.x is used, it only works with BerkeleyDB::Btree.

$status = $db->status()

Returns the status of the last $db method called.

$status = $db->truncate($count)

Truncates the datatabase and returns the number or records deleted in $count.

$status = $db->compact($start, $stop, $c_data, $flags, $end);

Compacts the database $db.

All the parameters are optional - if only want to make use of some of them, use undef for those you don't want. Trailing unusused parameters can be omitted. For example, if you only want to use the $c_data parameter to set the compact_fillpercent, write you code like this

The parameters operate identically to the C equivalent of this method. The $c_data needs a bit of explanation - it must be a hash reference. The values of the following keys can be set before calling compact and will affect the operation of the compaction.

The following keys, along with associated values, will be created in the hash reference if the compact operation was successful.

You need to be running Berkeley DB 4.4 or better if you wan to make use of compact.

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 db_cursor

A cursor object has the following methods available:

$newcursor = $cursor->c_dup($flags)

Creates a duplicate of $cursor. This method needs Berkeley DB 3.0.x or better.

The $flags parameter is optional and can take the following value:

DB_POSITION

When present this flag will position the new cursor at the same place as the existing cursor.

$status = $cursor->c_get($key, $value, $flags)

Reads a key/value pair from the database, returning the data in $key and $value. The key/value pair actually read is controlled by the $flags parameter, which can take one of the following values:

DB_FIRST

Set the cursor to point to the first key/value pair in the database. Return the key/value pair in $key and $value.

DB_LAST

Set the cursor to point to the last key/value pair in the database. Return the key/value pair in $key and $value.

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, DB_NEXT works just like DB_FIRST.

If the cursor is already positioned at the last key/value pair, c_get will return DB_NOTFOUND.

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.

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, DB_PREV works just like DB_LAST.

If the cursor is already positioned at the first key/value pair, c_get will return DB_NOTFOUND.

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, c_get will return DB_KEYEMPTY.

DB_SET

Set the cursor to point to the key/value pair referenced by $key and return the value in $value.

DB_SET_RANGE

This flag is a variation on the DB_SET flag. As well as returning the value, it also returns the key, via $key. When used with a BerkeleyDB::Btree database the key matched by c_get will be the shortest key (in length) which is greater than or equal to the key supplied, via $key. This allows partial key searches. See ??? for an example of how to use this flag.

DB_GET_BOTH

Another variation on DB_SET. This one returns both the key and the value.

DB_SET_RECNO

TODO.

DB_GET_RECNO

TODO.

In addition, the following value may be set by bitwise OR'ing it into the $flags parameter:

DB_RMW

TODO.

$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 $flags parameter, which must take one of the following values:

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 $value will be associated with it - $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 DB_DUP.

When used with a Recno ... TODO

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 $value will be associated with it - $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 DB_DUP.

When used with a Recno ... TODO

DB_CURRENT

If the cursor has been initialised, replace the value of the key/value pair stored in the database with the contents of $value.

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.

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.

$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, c_del will return DB_KEYEMPTY.

The $flags parameter is not used at present.

$status = $cursor->c_count($cnt [, $flags])

Stores the number of duplicates at the current cursor position in $cnt.

The $flags parameter is not used at present. This method needs Berkeley DB 3.1 or better.

$status = $cursor->status()

Returns the status of the last cursor method as a dual type.

$status = $cursor->c_pget() ;

TODO

$status = $cursor->c_close()

Closes the cursor $cursor.

Cursor Examples

TODO

Iterating from first to last, then in reverse.

examples of each of the flags.

JOIN

Join support for BerkeleyDB is in progress. Watch this space.

TODO

TRANSACTIONS

TODO.

CDS Mode

The Berkeley Db Concurrent Data Store is a lightweight locking mechanism that is useful in scenarios where transactions are overkill. See the accompanying document .. for details of using this module in CDS mode.

DBM Filters

A DBM Filter is a piece of code that is be used when you 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.

There are four methods associated with DBM Filters. All work identically, and each is used to install (or uninstall) a single DBM Filter. Each expects a single parameter, namely a reference to a sub. The only difference between them is the place that the filter is installed.

To summarise:

filter_store_key

If a filter has been installed with this method, it will be invoked every time you write a key to a DBM database.

filter_store_value

If a filter has been installed with this method, it will be invoked every time you write a value to a DBM database.

filter_fetch_key

If a filter has been installed with this method, it will be invoked every time you read a key from a DBM database.

filter_fetch_value

If a filter has been installed with this method, it will be invoked every time you read a value from a DBM database.

You can use any combination of the methods, from none, to all four.

All filter methods return the existing filter, if present, or undef in not.

To delete a filter pass undef to it.

The Filter

When each filter is called by Perl, a local copy of $_ will contain the key or value to be filtered. Filtering is achieved by modifying the contents of $_. The return code from the filter is ignored.

An Example -- the NULL termination problem.

Consider the following scenario. You have a DBM database that you need to share with a third-party C application. The C application assumes that all keys and values are NULL terminated. Unfortunately when Perl writes to DBM databases it doesn't use NULL termination, so your Perl application will have to manage NULL termination itself. When you write to the database you will have to use something like this:

$hash{"$key\0"} = "$value\0" ;

Similarly the NULL needs to be taken into account when you are considering the length of existing keys/values.

It would be much better if you could ignore the NULL terminations issue in the main application code and have a mechanism that automatically added the terminating NULL to all keys and values whenever you write to the database and have them removed when you read from the database. As I'm sure you have already guessed, this is a problem that DBM Filters can fix very easily.

Hopefully the contents of each of the filters should be self-explanatory. Both "fetch" filters remove the terminating NULL, and both "store" filters add a terminating NULL.

Another Example -- Key is a C int.

Here is another real-life example. By default, whenever Perl writes to a DBM database it always writes the key and value as strings. So when you use this:

$hash{12345} = "something" ;

the key 12345 will get stored in the DBM database as the 5 byte string "12345". If you actually want the key to be stored in the DBM database as a C int, you will have to use pack when writing, and unpack when reading.

This time only two filters have been used -- we only need to manipulate the contents of the key, so it wasn't necessary to install any value filters.

Using BerkeleyDB with MLDBM

Both BerkeleyDB::Hash and BerkeleyDB::Btree can be used with the MLDBM module. The code fragment below shows how to open associate MLDBM with BerkeleyDB::Btree. To use BerkeleyDB::Hash just replace BerkeleyDB::Btree with BerkeleyDB::Hash.

See the MLDBM documentation for information on how to use the module and for details of its limitations.

EXAMPLES

TODO.

HINTS & TIPS

Sharing Databases With C Applications

There is no technical reason why a Berkeley DB database cannot be shared by both a Perl and a C application.

The vast majority of problems that are reported in this area boil down to the fact that C strings are NULL terminated, whilst Perl strings are not. See "An Example -- the NULL termination problem." in the DBM FILTERS section for a generic way to work around this problem.

The untie Gotcha

TODO

COMMON QUESTIONS

This section attempts to answer some of the more common questions that I get asked.

Relationship with DB_File

Before Berkeley DB 2.x was written there was only one Perl module that interfaced to Berkeley DB. That module is called DB_File. Although DB_File can be build with Berkeley DB 1.x, 2.x, 3.x or 4.x, it only provides an interface to the functionality available in Berkeley DB 1.x. That means that it doesn't support transactions, locking or any of the other new features available in DB 2.x or better.

How do I store Perl data structures with BerkeleyDB?

HISTORY

AVAILABILITY

The most recent version of BerkeleyDB can always be found on CPAN (see "CPAN" in perlmod for details), in the directory modules/by-module/BerkeleyDB.

The official web site for Berkeley DB is http://www.sleepycat.com.

COPYRIGHT

Copyright (c) 1997-2004 Paul Marquess. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Although BerkeleyDB is covered by the Perl license, the library it makes use of, namely Berkeley DB, is not. Berkeley DB has its own copyright and its own license. Please take the time to read it.

Here are few words taken from the Berkeley DB FAQ (at http://www.sleepycat.com) regarding the license:

Do I have to license DB to use it in Perl scripts?
No. The Berkeley DB license requires that software that uses
Berkeley DB be freely redistributable. In the case of Perl, that
software is Perl, and not your scripts. Any Perl scripts that you
write are your property, including scripts that make use of Berkeley
DB. Neither the Perl license nor the Berkeley DB license
place any restriction on what you may do with them.

If you are in any doubt about the license situation, contact either the Berkeley DB authors or the author of BerkeleyDB. See "AUTHOR" for details.

AUTHOR

Paul Marquess <pmqs@cpan.org>.

Questions about Berkeley DB may be addressed to <db@sleepycat.com>.

SEE ALSO

perl(1), DB_File, Berkeley DB.

Module Install Instructions

To install BerkeleyDB, simply copy and paste either of the commands in to your terminal

As a valued partner and proud supporter of MetaCPAN, StickerYou is
happy to offer a 10% discount on all Custom Stickers,
Business Labels, Roll Labels,
Vinyl Lettering or Custom Decals. StickerYou.com
is your one-stop shop to make your business stick.
Use code METACPAN10 at checkout to apply your discount.