BerkeleyDB(3)

πŸ’– BerkeleyDB(3) πŸ’–

okay so this is a User Contributed Perl Documentation page, and it's literally the blueprint for the BerkeleyDB Perl extension. bestie, if you're trying to talk to Berkeley DB from Perl, you're in the right place. it's giving "main character energy" for databases. πŸ’…


✨ NAME ✨

BerkeleyDB β€” Perl extension for Berkeley DB version 2, 3, 4, 5 or 6


🌈 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() ;

πŸ’… DESCRIPTION πŸ’…

NOTE: This document is still under construction. Expect it to be incomplete in places.

so this Perl module is basically the glow-up for most of the functionality in Berkeley DB versions 2, 3, 5 and 6. (yes, 4 is skipped in that list β€” not me pointing it out, just saying. πŸ™ˆ) you can generally assume the interface here is identical to the Berkeley DB interface, but the main changes were made to make the Berkeley DB API work in a Perl way. and bestie, if you're on Berkeley DB 2.x, the new features from Berkeley DB 3.x or later are simply not available via this module. no cap.

you're expected to already be familiar with the Berkeley DB documentation. where the interface provided here is identical to the Berkeley DB library and the... TODO

the db_appinit, db_cursor, db_open and db_txn man pages are particularly relevant.

the interface to Berkeley DB is implemented with a number of Perl classes.


🧚 The BerkeleyDB::Env Class 🧚

the BerkeleyDB::Env class is your go-to for the Berkeley DB function db_appinit in Berkeley DB 2.x, or db_env_create and DBENV->open in Berkeley DB 3.x (or later). its whole purpose is to initialise a bunch of sub-systems so they can then be used in a consistent way across all the databases you use in the environment. it's giving "let's get everyone on the same page". ✨

if you don't intend using transactions, locking or logging, then you shouldn't need to make use of BerkeleyDB::Env. periodt.

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. don't forget it, bestie, or nothing's gonna work. πŸ’€

🌸 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. you love to see it. πŸŽ€

  • -Home β€” 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.

      $env = new BerkeleyDB::Env
               -Home         => "/home/databases"
      ...

      $db1 = new BerkeleyDB::Hash
               -Filename => "fred.db",
               -Env => $env
      ...

      $db2 = new BerkeleyDB::Hash
               -Filename => "/other/joe.db",
               -Env => $env
      ...
  • -Server β€” if present, this parameter should be the hostname of a server that is running the Berkeley DB RPC server. all databases will be accessed via the RPC server.
  • -Encrypt β€” if present, this parameter will enable encryption of all data before it is written to the database. this parameter must be given a hash reference. the format is shown below.
      -Encrypt => { -Password => "abc", Flags => DB_ENCRYPT_AES }

valid values for the Flags are 0 or "DB_ENCRYPT_AES".

this option requires Berkeley DB 4.1 or better.

  • -Cachesize β€” if present, this parameter sets the size of the environments shared memory buffer pool.
  • -TxMax β€” if present, this parameter sets the number of simultaneous transactions that are allowed. default 100. this default is definitely too low for programs using the MVCC capabilities. like, way too low. 😭
  • -LogConfig β€” if present, this parameter is used to configure log options.
  • -MaxLockers β€” if present, this parameter is used to configure the maximum number of processes doing locking on the database. default 1000.
  • -MaxLocks β€” if present, this parameter is used to configure the maximum number of locks on the database. default 1000. this is often lower than required.
  • -MaxObjects β€” if present, this parameter is used to configure the maximum number of locked objects. default 1000. this is often lower than required.
  • -SharedMemKey β€” if present, this parameter sets the base segment ID for the shared memory region used by Berkeley DB.

this option requires Berkeley DB 3.1 or better.

use "$env->get_shm_key($id)" to find out the base segment ID used once the environment is open.

  • -ThreadCount β€” if present, this parameter declares the approximate number of threads that will be used in the database environment. this parameter is only necessary when the $env->failchk method will be used. it does not actually set the maximum number of threads but rather is used to determine memory sizing.

this option requires Berkeley DB 4.4 or better. it is only supported on Unix/Linux.

  • -BlobThreshold β€” sets the size threshold that will be used to decide when data is stored as a BLOB. this option must be set for blobs to be used.

this option requires Berkeley DB 6.0 or better.

  • -BlobDir β€” the directory where the BLOB objects are stored.

if not specified blob files are stored in the environment directory.

this option requires Berkeley DB 6.0 or better.

  • -Config β€” this is a variation on the -Home parameter, but it allows finer control of where specific types of files will be stored.

the parameter expects a reference to a hash. valid keys are: DB_DATA_DIR, DB_LOG_DIR and DB_TMP_DIR

the code below shows an example of how it can be used.

      $env = new BerkeleyDB::Env
               -Config => { DB_DATA_DIR => "/home/databases",
                            DB_LOG_DIR  => "/home/logs",
                            DB_TMP_DIR  => "/home/tmp"
                          }
      ...
  • -ErrFile β€” bestie this one wants a filename or a filehandle, and every error Berkeley DB coughs up internally gets logged there. The iconic debug move is opening your env with either
-ErrFile => *STDOUT

or

-ErrFile => *STDERR
  • -ErrPrefix β€” lets you slap a little prefix on your error messages before they head off to -ErrFile. branding era πŸ’…
  • -Flags β€” this parameter says BOTH which sub-systems to initialise AND a whole pile of environment-wide options. For the full tea on these, go read the Berkeley DB documentation. Any of these you can specify by OR'ing them together:
    • DB_CREATE β€” if any of the files you named don't exist yet, create them. no cap.
    • DB_INIT_CDB β€” initialise the Concurrent Access Methods
    • DB_INIT_LOCK β€” initialise the Locking sub-system.
    • DB_INIT_LOG β€” initialise the Logging sub-system.
    • DB_INIT_MPOOL β€” initialise the shared memory buffer pool subsystem. This one should be used whenever your app is using any Berkeley DB access method. literally always, bestie.
    • DB_INIT_TXN β€” initialise the transaction subsystem. Use this when recovery and atomicity of multiple operations matter to you. Heads up: the DB_INIT_TXN flag implies the DB_INIT_LOG flag. πŸ‘‘
    • DB_MPOOL_PRIVATE β€” create a private memory pool; see memp_open. Ignored unless DB_INIT_MPOOL is also specified.
    • DB_INIT_MPOOL is also specified.
    • DB_NOMMAP β€” do not map this database into process memory.
    • DB_RECOVER β€” run normal recovery on this environment before opening it for normal use. If this flag is set, the DB_CREATE flag must also be set, since the regions will be removed and recreated. Also, the db_appinit function returns successfully if DB_RECOVER is specified and no log files exist, so it is necessary to ensure all necessary log files are present before running recovery. (yes that's a real trap, don't get got 🫢)
    • DB_PRIVATE
    • DB_RECOVER_FATAL β€” run catastrophic recovery on this environment before opening it for normal use. If this flag is set, the DB_CREATE flag must also be set, since the regions will be removed and recreated. Same deal as above: the db_appinit function returns successfully if DB_RECOVER_FATAL is specified and no log files exist, so it is necessary to ensure all necessary log files are present before running recovery. 🚨
    • DB_THREAD β€” ensure that handles returned by the Berkeley DB subsystems are useable by multiple threads within a single process, i.e., that the system is free-threaded.
    • DB_TXN_NOSYNC β€” on transaction commit, do not synchronously flush the log; see txn_open. Ignored unless DB_INIT_TXN is also specified.
    • DB_USE_ENVIRON β€” the Berkeley DB process' environment may be permitted to specify information to be used when naming files; see Berkeley DB File Naming. Because letting users specify which files get used can create security problems, environment information will be used in file naming for all users only if the DB_USE_ENVIRON flag is set. ⚠️
    • DB_USE_ENVIRON_ROOT β€” same naming-files situation as above; see Berkeley DB File Naming. And again, since permitting users to specify which files are used can create security problems, if the DB_USE_ENVIRON_ROOT flag is set, environment information will be used for file naming only for users with a user-ID matching that of the superuser (specifically, users for whom the getuid(2) system call returns the user-ID 0).
  • -SetFlags β€” calls ENV->set_flags with the bitmask you supply. Use this when you need to make use of DB_ENV->set_flags before DB_ENV->open is called.

Only valid when Berkeley DB 3.x or better is used.

  • -LockDetect β€” specifies what to do when a lock conflict occurs. The value should be one of:
    • DB_LOCK_DEFAULT β€” use the default policy as specified by db_deadlock.
    • DB_LOCK_OLDEST β€” abort the oldest transaction.
    • DB_LOCK_RANDOM β€” abort a random transaction involved in the deadlock.
    • DB_LOCK_YOUNGEST β€” abort the youngest transaction. πŸ’€
  • -Verbose β€” adds extra debugging information to the messages sent to -ErrFile.

🌸 Methods 🌸

The environment class has the following methods, bestie, take notes:

  • $env->errPrefix("string") ; β€” this method is identical to the -ErrPrefix flag. It lets the error prefix string be changed dynamically. ✨
  • $env->set_flags(bitmask, 1|0);
  • $txn = $env->TxnMgr() β€” constructor for creating a TxnMgr object. See "TRANSACTIONS" for more details of using transactions.
This method is deprecated. Access the transaction methods using the txn_ methods below from the environment object directly. it's giving old money, move on πŸ’…
  • $env->txn_begin() β€” TODO
  • $env->txn_stat() β€” TODO
  • $env->txn_checkpoint() β€” TODO
  • $env->status() β€” returns the status of the last BerkeleyDB::Env method.
  • $env->DB_ENV() β€” returns a pointer to the underlying DB_ENV data structure that Berkeley DB uses. peek behind the curtain ✨
  • $env->get_shm_key($id) β€” writes the base segment ID for the shared memory region used by the Berkeley DB environment into $id. Returns 0 on success.

This option requires Berkeley DB 4.2 or better.

Use the -SharedMemKey option when opening the environmet to set the base segment ID.

  • $env->set_isalive() β€” set the callback that determines if the thread of control, identified by the pid and tid arguments, is still running. This method should only be used in combination with $env->failchk.

This option requires Berkeley DB 4.4 or better.

  • $env->failchk($flags) β€” the $env->failchk method checks for threads of control (either a true thread or a process) that have exited while manipulating Berkeley DB library data structures, while holding a logical database lock, or with an unresolved transaction (that is, a transaction that was never aborted or committed).

If $env->failchk determines a thread of control exited while holding database read locks, it will release those locks. If $env->failchk determines a thread of control exited with an unresolved transaction, the transaction will be aborted. cleanup queen 🧹

Applications calling the $env->failchk method must have already called the $env->set_isalive method, on the same DB environment, and must have configured their database environment using the -ThreadCount flag. The ThreadCount flag cannot be used on an environment that wasn't previously initialized with it.

This option requires Berkeley DB 4.4 or better.

  • $env->stat_print β€” prints statistical information.

If the "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.

  • $env->lock_stat_print β€” prints locking subsystem statistics.

If the "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.

  • $env->mutex_stat_print β€” prints mutex subsystem statistics.

If the "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.4 or better.

  • $status = $env->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.
  • $status = $env->get_blob_dir($dir) ; β€” sets the $dir parameter to the directory where blob files are stored.
  • $env->set_timeout($timeout, $flags)
  • $env->status() β€” returns the status of the last BerkeleyDB::Env method.

πŸŽ€ Examples πŸŽ€

TODO.


🌈 Global Classes 🌈

$status = BerkeleyDB::db_remove [OPTIONS]
$status = BerkeleyDB::db_rename [OPTIONS]
$status = BerkeleyDB::db_verify [OPTIONS]

πŸ‘‘ THE DATABASE CLASSES πŸ‘‘

BerkeleyDB supports the following database formats, and bestie, they are a whole lineup:

BerkeleyDB::Hash

This database type allows arbitrary key/value pairs to be stored in data files. It's equivalent to the functionality provided by other hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM. But remember though β€” the files created using BerkeleyDB::Hash are not compatible with any of the other packages mentioned. no crossover episodes, sorry πŸ¦‹

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. main character energy, honestly.

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::Heap

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 πŸ’–

ok bestie so this one is the hash database class and honestly? iconic.

It's equivalent to calling db_open with type DB_HASH in Berkeley DB 2.x, and to calling db_create followed by DB->open with type DB_HASH in Berkeley DB 3.x or greater.

There are two forms of constructor, pick your fighter πŸ₯Š:

    $db = new BerkeleyDB::Hash
                [ -Filename      => "filename", ]
                [ -Subname       => "sub-database name", ]
                [ -Flags         => flags,]
                [ -Property      => flags,]
                [ -Mode          => number,]
                [ -Cachesize     => number,]
                [ -Lorder        => number,]
                [ -Pagesize      => number,]
                [ -Env           => $env,]
                [ -Txn           => $txn,]
                [ -Encrypt       => { Password => "string",
                                      Flags    => number }, ],
                [ -BlobThreshold=> $number, ]
                [ -BlobDir      => directory, ]
                # BerkeleyDB::Hash specific
                [ -Ffactor       => number,]
                [ -Nelem         => number,]
                [ -Hash          => code reference,]
                [ -DupCompare    => code reference,]

and this one:

    [$db =] tie %hash, 'BerkeleyDB::Hash',
                [ -Filename      => "filename", ]
                [ -Subname       => "sub-database name", ]
                [ -Flags         => flags,]
                [ -Property      => flags,]
                [ -Mode          => number,]
                [ -Cachesize     => number,]
                [ -Lorder        => number,]
                [ -Pagesize      => number,]
                [ -Env           => $env,]
                [ -Txn           => $txn,]
                [ -Encrypt       => { Password => "string",
                                      Flags    => number }, ],
                [ -BlobThreshold=> $number, ]
                [ -BlobDir      => directory, ]
                # BerkeleyDB::Hash specific
                [ -Ffactor       => number,]
                [ -Nelem         => number,]
                [ -Hash          => code reference,]
                [ -DupCompare    => code reference,]

When you go the tie route, reading from and writing to the database is literally just vibing through the tied hash. The database behaves like a Perl associative array that happens to be chillin' on disk. πŸ’Ύβœ¨

And beyond the high-level tied hash interface, you can also make use of the underlying methods that Berkeley DB provides. the range? unmatched.


✨ Options ✨

On top of the standard set of options (go see "COMMON OPTIONS" for those), BerkeleyDB::Hash also supports these:

  • -Property β€” used to specify extra flags when you're opening a database. You get the following flags by bitwise OR'ing together one or more of these values:
    • DB_DUP β€” when you're creating a new database, this flag enables storing duplicate keys in the database. If DB_DUPSORT is not also specified, the duplicates get stored in the order they were created in the database.
    • DB_DUPSORT β€” enables sorting of the duplicate keys in the database. It gets ignored if DB_DUP isn't also specified, so don't be out here using it solo. πŸ™ˆ
  • -Ffactor
  • -Nelem β€” see the Berkeley DB documentation for the details on these two, bestie.
  • -Hash β€” lets you provide a user defined hash function. If you don't specify one, a default hash function is used. Here's a template for a user-defined hash function:
    sub hash
    {
        my ($data) = shift ;
        ...
        # return the hash value for $data
        return $hash ;
    }

    tie %h, "BerkeleyDB::Hash",
        -Filename => $filename,
        -Hash     => \&hash,
        ...

See "" for an example.

  • -DupCompare β€” used in conjunction with the DB_DUPOSRT flag.
    sub compare
    {
        my ($key, $key2) = @_ ;
        ...
        # return  0 if $key1 eq $key2
        #        -1 if $key1 lt $key2
        #         1 if $key1 gt $key2
        return (-1 , 0 or 1) ;
    }

    tie %h, "BerkeleyDB::Hash",
        -Filename   => $filename,
        -Property   => DB_DUP|DB_DUPSORT,
        -DupCompare => \&compare,
        ...

🌸 Methods 🌸

BerkeleyDB::Hash only supports the standard database methods. Peep "COMMON DATABASE METHODS" for the lineup.


πŸ“ A Simple Tied Hash Example πŸ“

    use strict ;
    use BerkeleyDB ;
    use vars qw( %h $k $v ) ;

    my $filename = "fruit" ;
    unlink $filename ;
    tie %h, "BerkeleyDB::Hash",
                -Filename => $filename,
                -Flags    => DB_CREATE
        or die "Cannot open file $filename: $! $BerkeleyDB::Error\n" ;

    # Add a few key/value pairs to the file
    $h{"apple"} = "red" ;
    $h{"orange"} = "orange" ;
    $h{"banana"} = "yellow" ;
    $h{"tomato"} = "red" ;

    # Check for existence of a key
    print "Banana Exists\n\n" if $h{"banana"} ;

    # Delete a key/value pair.
    delete $h{"apple"} ;

    # print the contents of the file
    while (($k, $v) = each %h)
      { print "$k -> $v\n" }

    untie %h ;

here is the output:

    Banana Exists

    orange -> orange
    tomato -> red
    banana -> yellow

Just a heads up bestie: like ordinary associative arrays, the order of the keys you retrieve from a Hash database is in an apparently random order. no notes, that's just the vibe. πŸ¦‹


🌈 Another Simple Hash Example 🌈

Same energy as the previous example, but this time we're not using tie.

    use strict ;
    use BerkeleyDB ;

    my $filename = "fruit" ;
    unlink $filename ;
    my $db = new BerkeleyDB::Hash
                -Filename => $filename,
                -Flags    => DB_CREATE
        or die "Cannot open file $filename: $! $BerkeleyDB::Error\n" ;

    # Add a few key/value pairs to the file
    $db->db_put("apple", "red") ;
    $db->db_put("orange", "orange") ;
    $db->db_put("banana", "yellow") ;
    $db->db_put("tomato", "red") ;

    # Check for existence of a key
    print "Banana Exists\n\n" if $db->db_get("banana", $v) == 0;

    # Delete a key/value pair.
    $db->db_del("apple") ;

    # print the contents of the file
    my ($k, $v) = ("", "") ;
    my $cursor = $db->db_cursor() ;
    while ($cursor->c_get($k, $v, DB_NEXT) == 0)
      { print "$k -> $v\n" }

    undef $cursor ;
    undef $db ;

πŸ’… Duplicate keys πŸ’…

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

    use strict ;
    use BerkeleyDB ;

    my $filename = "fruit" ;
    unlink $filename ;
    my $db = new BerkeleyDB::Hash
                -Filename => $filename,
                -Flags    => DB_CREATE,
                -Property  => DB_DUP
        or die "Cannot open file $filename: $! $BerkeleyDB::Error\n" ;

    # Add a few key/value pairs to the file
    $db->db_put("red", "apple") ;
    $db->db_put("orange", "orange") ;
    $db->db_put("green", "banana") ;
    $db->db_put("yellow", "banana") ;
    $db->db_put("red", "tomato") ;
    $db->db_put("green", "apple") ;

    # print the contents of the file
    my ($k, $v) = ("", "") ;
    my $cursor = $db->db_cursor() ;
    while ($cursor->c_get($k, $v, DB_NEXT) == 0)
      { print "$k -> $v\n" }

    undef $cursor ;
    undef $db ;

here is the output:

    orange -> orange
    yellow -> banana
    red -> apple
    red -> tomato
    green -> banana
    green -> apple

⭐ Sorting Duplicate Keys ⭐

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

    use strict ;
    use BerkeleyDB ;

    my $filename = "fruit" ;
    unlink $filename ;
    my $db = new BerkeleyDB::Hash
                -Filename => $filename,
                -Flags    => DB_CREATE,
                -Property  => DB_DUP | DB_DUPSORT
        or die "Cannot open file $filename: $! $BerkeleyDB::Error\n" ;

    # Add a few key/value pairs to the file
    $db->db_put("red", "apple") ;
    $db->db_put("orange", "orange") ;
    $db->db_put("green", "banana") ;
    $db->db_put("yellow", "banana") ;
    $db->db_put("red", "tomato") ;
    $db->db_put("green", "apple") ;

    # print the contents of the file
    my ($k, $v) = ("", "") ;
    my $cursor = $db->db_cursor() ;
    while ($cursor->c_get($k, $v, DB_NEXT) == 0)
      { print "$k -> $v\n" }

    undef $cursor ;
    undef $db ;

Notice that in the output below the duplicate values are sorted. πŸ‘‘

    orange -> orange
    yellow -> banana
    red -> apple
    red -> tomato
    green -> apple
    green -> banana

🧚 Custom Sorting Duplicate Keys 🧚

Another variation

TODO


πŸŽ€ Changing the hash πŸŽ€

TODO


πŸ’œ Using db_stat πŸ’œ

TODO

πŸ¦‹ BerkeleyDB::Btree πŸ¦‹

okay bestie so Btree is literally the same deal as calling db_open with type DB_BTREE in Berkeley DB 2.x, or calling db_create and then DB->open with type DB_BTREE in Berkeley DB 3.x and up. same energy, different era πŸ’…

you get two whole flavors of constructor, pick your fighter:

$db = new BerkeleyDB::Btree
            [ -Filename      => "filename", ]
            [ -Subname       => "sub-database name", ]
            [ -Flags         => flags,]
            [ -Property      => flags,]
            [ -Mode          => number,]
            [ -Cachesize     => number,]
            [ -Lorder        => number,]
            [ -Pagesize      => number,]
            [ -Env           => $env,]
            [ -Txn           => $txn,]
            [ -Encrypt       => { Password => "string",
                                  Flags    => number }, ],
            [ -BlobThreshold=> $number, ]
            [ -BlobDir      => directory, ]
            # BerkeleyDB::Btree specific
            [ -Minkey        => number,]
            [ -Compare       => code reference,]
            [ -DupCompare    => code reference,]
            [ -Prefix        => code reference,]

and then this one, the tie girlie πŸŽ€

[$db =] tie %hash, 'BerkeleyDB::Btree',
            [ -Filename      => "filename", ]
            [ -Subname       => "sub-database name", ]
            [ -Flags         => flags,]
            [ -Property      => flags,]
            [ -Mode          => number,]
            [ -Cachesize     => number,]
            [ -Lorder        => number,]
            [ -Pagesize      => number,]
            [ -Env           => $env,]
            [ -Txn           => $txn,]
            [ -Encrypt       => { Password => "string",
                                  Flags    => number }, ],
            [ -BlobThreshold=> $number, ]
            [ -BlobDir      => directory, ]
            # BerkeleyDB::Btree specific
            [ -Minkey        => number,]
            [ -Compare       => code reference,]
            [ -DupCompare    => code reference,]
            [ -Prefix        => code reference,]

✨ Options ✨

so on top of the whole standard set of options (go read "COMMON OPTIONS", it's giving required reading), BerkeleyDB::Btree also serves these:

  • -Property β€” this one is for specifying extra flags when you open a database. you can stack them by bitwise OR'ing one or more of these bad boys together:
    • DB_DUP β€” when you're creating a brand new database, this flag turns on storing duplicate keys in the database. and heads up: if you don't also specify DB_DUPSORT, the duplicates just get stored in the order they were created in the database. no sorting, just vibes.
    • DB_DUPSORT β€” this enables the sorting of duplicate keys in the database. it gets ignored if DB_DUP isn't also specified, so don't skip that one bestie.
  • Minkey β€” TODO πŸ™ˆ (yes really, that's all she wrote)
  • Compare β€” this lets you override the default sort order used in the database. want a peek at how? check out "Changing the sort order" for an example. here's the shape of it:
sub compare
{
    my ($key, $key2) = @_ ;
    ...
    # return  0 if $key1 eq $key2
    #        -1 if $key1 lt $key2
    #         1 if $key1 gt $key2
    return (-1 , 0 or 1) ;
}

tie %h, "BerkeleyDB::Hash",
    -Filename   => $filename,
    -Compare    => \&compare,
    ...
  • Prefix β€” the prefix callback, and honestly it's giving very specific:
sub prefix
{
    my ($key, $key2) = @_ ;
    ...
    # return number of bytes of $key2 which are
    # necessary to determine that it is greater than $key1
    return $bytes ;
}

tie %h, "BerkeleyDB::Hash",
    -Filename   => $filename,
    -Prefix     => \&prefix,
    ...
  • DupCompare β€” okay so the original page marks this one with an =item DupCompare (love a formatting plot twist, we keep it real):
sub compare
{
    my ($key, $key2) = @_ ;
    ...
    # return  0 if $key1 eq $key2
    #        -1 if $key1 lt $key2
    #         1 if $key1 gt $key2
    return (-1 , 0 or 1) ;
}

tie %h, "BerkeleyDB::Hash",
    -Filename   => $filename,
    -DupCompare => \&compare,
    ...
  • set_bt_compress β€” this enables compression of the btree data πŸ”₯. heads up though: the callback interface is not supported at present, no cap. and you need Berkeley DB 4.8 or better for this one.

🌸 Methods 🌸

BerkeleyDB::Btree supports the following database methods. also go check "COMMON DATABASE METHODS" because the overlap is real.

and listen β€” all the methods below return 0 to indicate success. zero equals slay. that's just how it is here πŸ’€

  • $status = $db->db_key_range($key, $less, $equal, $greater [, $flags]) β€” give it a key, $key, and it hands you back the proportion of keys less than $key in $less, the proportion equal to $key in $equal, and the proportion greater than $key in $greater.

the proportion comes back as a double in the range 0.0 to 1.0. clean. simple. iconic.


🧚 A Simple Btree Example 🧚

this code below is a whole little btree moment. enjoy:

use strict ;
use BerkeleyDB ;

my $filename = "tree" ;
unlink $filename ;
my %h ;
tie %h, 'BerkeleyDB::Btree',
            -Filename   => $filename,
            -Flags      => DB_CREATE
  or die "Cannot open $filename: $! $BerkeleyDB::Error\n" ;

# Add a key/value pair to the file
$h{'Wall'} = 'Larry' ;
$h{'Smith'} = 'John' ;
$h{'mouse'} = 'mickey' ;
$h{'duck'}  = 'donald' ;

# Delete
delete $h{"duck"} ;

# Cycle through the keys printing them in order.
# Note it is not necessary to sort the keys as
# the btree will have kept them in order automatically.
foreach (keys %h)
  { print "$_\n" }

untie %h ;

and here's the output from that code. the keys got sorted using Berkeley DB's default sorting algorithm, she did that all by herself:

Smith
Wall
mouse

πŸŽ€ Changing the sort order πŸŽ€

okay so it is <highkey>possible</highkey> to supply your own sorting algorithm if the one Berkeley DB used isn't suitable for you. the code below is literally identical to the previous example except for the case insensitive compare function. watch:

use strict ;
use BerkeleyDB ;

my $filename = "tree" ;
unlink $filename ;
my %h ;
tie %h, 'BerkeleyDB::Btree',
            -Filename   => $filename,
            -Flags      => DB_CREATE,
            -Compare    => sub { lc $_[0] cmp lc $_[1] }
  or die "Cannot open $filename: $!\n" ;

# Add a key/value pair to the file
$h{'Wall'} = 'Larry' ;
$h{'Smith'} = 'John' ;
$h{'mouse'} = 'mickey' ;
$h{'duck'}  = 'donald' ;

# Delete
delete $h{"duck"} ;

# Cycle through the keys printing them in order.
# Note it is not necessary to sort the keys as
# the btree will have kept them in order automatically.
foreach (keys %h)
  { print "$_\n" }

untie %h ;

and boom, here's the output from that code:

mouse
Smith
Wall

now, there are a few points to bear in mind if you wanna change the ordering in a BTREE database, and these are not optional, bestie:

  1. the new compare function must be specified when you create the database.
  2. you cannot change the ordering once the database has been created. so you must use the same compare function every single time you access the database. every time. periodt.

πŸ’œ Using db_stat πŸ’œ

TODO πŸ™ˆ (the original page really just left this one hanging, so we're leaving it exactly as it is)

🌸 BerkeleyDB::Recno 🌸

Basically the same energy as calling db_open with type DB_RECNO in Berkeley DB 2.x, and calling db_create followed by DB->open with type DB_RECNO in Berkeley DB 3.x or greater. πŸ’–

Two forms of constructor are supported, bestie β€” pick your fighter:

$db = new BerkeleyDB::Recno
            [ -Filename      => "filename", ]
            [ -Subname       => "sub-database name", ]
            [ -Flags         => flags,]
            [ -Property      => flags,]
            [ -Mode          => number,]
            [ -Cachesize     => number,]
            [ -Lorder        => number,]
            [ -Pagesize      => number,]
            [ -Env           => $env,]
            [ -Txn           => $txn,]
            [ -Encrypt       => { Password => "string",
                                  Flags    => number }, ],
            # BerkeleyDB::Recno specific
            [ -Delim           => byte,]
            [ -Len             => number,]
            [ -Pad             => byte,]
            [ -Source          => filename,]

and this one:

[$db =] tie @arry, 'BerkeleyDB::Recno',
            [ -Filename      => "filename", ]
            [ -Subname       => "sub-database name", ]
            [ -Flags         => flags,]
            [ -Property      => flags,]
            [ -Mode          => number,]
            [ -Cachesize     => number,]
            [ -Lorder        => number,]
            [ -Pagesize      => number,]
            [ -Env           => $env,]
            [ -Txn           => $txn,]
            [ -Encrypt       => { Password => "string",
                                  Flags    => number }, ],
            # BerkeleyDB::Recno specific
            [ -Delim           => byte,]
            [ -Len             => number,]
            [ -Pad             => byte,]
            [ -Source          => filename,]

✨ A Recno Example ✨

Okay so here's a little baby example that uses RECNO β€” and heads up: if you're running a version of Perl earlier than 5.004_57, this example will not work 😭 (peep "Extra RECNO Methods" for a workaround, ily).

use strict ;
use BerkeleyDB ;

my $filename = "text" ;
unlink $filename ;

my @h ;
tie @h, 'BerkeleyDB::Recno',
            -Filename   => $filename,
            -Flags      => DB_CREATE,
            -Property   => DB_RENUMBER
  or die "Cannot open $filename: $!\n" ;

# Add a few key/value pairs to the file
$h[0] = "orange" ;
$h[1] = "blue" ;
$h[2] = "yellow" ;

push @h, "green", "black" ;

my $elements = scalar @h ;
print "The array contains $elements entries\n" ;

my $last = pop @h ;
print "popped $last\n" ;

unshift @h, "white" ;
my $first = shift @h ;
print "shifted $first\n" ;

# Check for existence of a key
print "Element 1 Exists with value $h[1]\n" if $h[1] ;

untie @h ;

And here's the output from the script, no cap:

The array contains 5 entries
popped black
shifted white
Element 1 Exists with value blue
The last element is green
The 2nd last element is yellow

πŸ¦‹ BerkeleyDB::Queue πŸ¦‹

Equivalent to calling db_create followed by DB->open with type DB_QUEUE in Berkeley DB 3.x or greater. Heads up though β€” this database format isn't available if you use Berkeley DB 2.x. πŸ™ˆ

Two forms of constructor are supported:

$db = new BerkeleyDB::Queue
            [ -Filename      => "filename", ]
            [ -Subname       => "sub-database name", ]
            [ -Flags         => flags,]
            [ -Property      => flags,]
            [ -Mode          => number,]
            [ -Cachesize     => number,]
            [ -Lorder        => number,]
            [ -Pagesize      => number,]
            [ -Env           => $env,]
            [ -Txn           => $txn,]
            [ -Encrypt       => { Password => "string",
                                  Flags    => number }, ],
            # BerkeleyDB::Queue specific
            [ -Len             => number,]
            [ -Pad             => byte,]
            [ -ExtentSize    => number, ]

and this one:

[$db =] tie @arry, 'BerkeleyDB::Queue',
            [ -Filename      => "filename", ]
            [ -Subname       => "sub-database name", ]
            [ -Flags         => flags,]
            [ -Property      => flags,]
            [ -Mode          => number,]
            [ -Cachesize     => number,]
            [ -Lorder        => number,]
            [ -Pagesize      => number,]
            [ -Env           => $env,]
            [ -Txn           => $txn,]
            [ -Encrypt       => { Password => "string",
                                  Flags    => number }, ],
            # BerkeleyDB::Queue specific
            [ -Len             => number,]
            [ -Pad             => byte,]

🌈 BerkeleyDB::Heap 🌈

Equivalent to calling db_create followed by DB->open with type DB_HEAP in Berkeley DB 5.2.x or greater. And again β€” this database format isn't available if you use an older version of Berkeley DB. πŸ’€

Only one form of constructor is supported:

$db = new BerkeleyDB::Heap
            [ -Filename      => "filename", ]
            [ -Subname       => "sub-database name", ]
            [ -Flags         => flags,]
            [ -Property      => flags,]
            [ -Mode          => number,]
            [ -Cachesize     => number,]
            [ -Lorder        => number,]
            [ -Pagesize      => number,]
            [ -Env           => $env,]
            [ -Txn           => $txn,]
            [ -Encrypt       => { Password => "string",
                                  Flags    => number }, ],
            [ -BlobThreshold=> $number, ]
            [ -BlobDir      => directory, ]
            # BerkeleyDB::Heap specific
            [ -HeapSize      => number, ]
            [ -HeapSizeGb    => number, ]

πŸ’œ BerkeleyDB::Unknown πŸ’œ

This class is used to open an existing database. Like, it's already there. You're just walking in. πŸšͺ✨

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

The constructor looks like this:

$db = new BerkeleyDB::Unknown
            [ -Filename      => "filename", ]
            [ -Subname       => "sub-database name", ]
            [ -Flags         => flags,]
            [ -Property      => flags,]
            [ -Mode          => number,]
            [ -Cachesize     => number,]
            [ -Lorder        => number,]
            [ -Pagesize      => number,]
            [ -Env           => $env,]
            [ -Txn           => $txn,]
            [ -Encrypt       => { Password => "string",
                                  Flags    => number }, ],

πŸ’… An example πŸ’…


⭐ COMMON OPTIONS ⭐

Every single one of the database access class constructors supports this common set of options defined below. And guess what β€” all of them are optional. Every. Single. One. 🫢

  • -Filename β€” the database filename. If no filename is specified, a temporary file will be created and removed once the program terminates. Gone. Poof. Never happened. πŸŽ€
  • -Subname β€” specifies the name of the sub-database to open. This option is only valid if you are using Berkeley DB 3.x or greater.
  • -Flags β€” specify how the database will be opened/created. The valid flags are:
    • DB_CREATE β€” create any underlying files, as necessary. If the files do not already exist and the DB_CREATE flag is not specified, the call will fail. 😭
    • DB_NOMMAP β€” not supported by BerkeleyDB. Nope. Not a thing here.
    • DB_RDONLY β€” opens the database in read-only mode. Look but don't touch energy. πŸ‘€
    • DB_THREAD β€” not supported by BerkeleyDB. Also nope.
    • DB_TRUNCATE β€” if the database file already exists, remove all the data before opening it. Bestie. It DELETES everything. All of it. Be so serious rn. πŸ’€
  • -Mode β€” determines the file protection when the database is created. Defaults to 0666.
  • -Cachesize
  • -Lorder
  • -Pagesize
  • -Env β€” when working under a Berkeley DB environment, this parameter

Defaults to no environment.

  • -Encrypt β€” if present, this parameter will enable encryption of all data before it is written to the database. This parameters must be given a hash reference. The format is shown below.
-Encrypt => { -Password => "abc", Flags => DB_ENCRYPT_AES }

Valid values for the Flags are 0 or "DB_ENCRYPT_AES".

This option requires Berkeley DB 4.1 or better.

  • -Txn β€” TODO. (yeah, that's literally what it says, we don't know either πŸ’€)

🌈 COMMON DATABASE METHODS 🌈

okay bestie so like, every single one of the database interfaces out there supports this one shared little set of methods, right here. it's the group chat they all live in πŸ’…

and listen β€” all of these methods return 0 to signal success. that's the vibe. zero means we ate. πŸ”₯


πŸ’– $env = $db->Env();

hands you back the environment object that this database is attached to. if you opened the database with no environment at all, you get undef back instead. simple as. 🫢


πŸ’– $status = $db->db_get($key, $value [, $flags])

give it a key ($key) and it goes and reads the value chilling next to it in the database. if that value exists, the thing it read comes back to you inside the $value parameter. ✨

the $flags parameter? optional, queen. but if you do pass it, it has to be set to one of these:

  • DB_GET_BOTH β€” when this flag is on, db_get checks that both the $key and the $value actually exist in the database.
  • DB_SET_RECNO β€” TODO.

on top of that, you can bitwise OR this next one into $flags:

  • DB_RMW β€” TODO

also there's this variant, db_pget, which lets you go query a secondary database:

$status = $sdb->db_pget($skey, $pkey, $value);

like, you use the key $skey in the secondary db to look up $pkey and $value from the primary db. iconic behavior honestly. πŸ’…


πŸ’– $status = $db->db_exists($key [, $flags])

this one just checks whether the given key ($key) exists β€” it does not read the value. nosy but respectful. if the key isn't found, db_exists returns DB_NOTFOUND.

heads up: this one needs BDB 4.6 or better to work.

πŸ’– $status = $db->db_put($key, $value [, $flags])

stores a key/value pair in the database. cute, right? πŸŽ€

$flags is optional, but if you bring it, it's gotta be one of these:

  • DB_APPEND β€” only applicable when you're accessing a BerkeleyDB::Recno database. TODO.
  • DB_NOOVERWRITE β€” if you set this and $key is already in the database, the db_put call comes back with DB_KEYEXIST. no overwriting today, bestie. πŸ’€

πŸ’– $status = $db->db_del($key [, $flags])

deletes the key/value pair in the database tied to $key. and ooh β€” if duplicate keys are enabled in the database, db_del will delete all the key/value pairs with key $key. it does not play.

$flags is optional and, ngl, currently unused.


πŸ’– $status = $env->stat_print([$flags])

prints statistical information. ✨

if the "MsgFile" option is specified, the output gets sent to that file. otherwise it just goes straight to standard output.

this one requires Berkeley DB 4.3 or better.

πŸ’– $status = $db->db_sync()

if any parts of the database are still chillin' in memory, this writes them out to the database. flushing the vibe check, basically. πŸ¦‹


πŸ’– $cursor = $db->db_cursor([$flags])

creates a cursor object. you use it to walk through the contents of the database sequentially. for all the deets on what you can do once you're holding a cursor, go peek at CURSORS.

$flags is optional. if present it must be set to one of these:

  • DB_RMW β€” TODO.

πŸ’– ($flag, $old_offset, $old_length) = $db->partial_set($offset, $length) ;

TODO


πŸ’– ($flag, $old_offset, $old_length) = $db->partial_clear() ;

TODO


πŸ’– $db->byteswapped()

TODO


πŸ’– $status = $db->get_blob_threshold($t1) ;

sets the $t1 parameter to the threshold value (in bytes) that decides when a data item gets stored as a Blob. 🫧


πŸ’– $status = $db->get_blob_dir($dir) ;

sets the $dir parameter to the directory where the blob files live. πŸ“


πŸ’– $db->type()

returns the type of the database. the possible return codes are DB_HASH for a BerkeleyDB::Hash database, DB_BTREE for a BerkeleyDB::Btree database, and DB_RECNO for a BerkeleyDB::Recno database.

this one's typically your girl when a database has been opened with BerkeleyDB::Unknown and you're like... okay but what are you. πŸ™ˆ


πŸ’– $bool = $env->cds_enabled();

returns true if the Berkeley DB environment $env was opened on CDS mode. ⭐


πŸ’– $bool = $db->cds_enabled();

returns true if the database $db was opened on CDS mode. ⭐


πŸ’– $lock = $db->cds_lock();

creates a CDS write lock object, $lock.

it is a fatal error to try to create a cds_lock if the Berkeley DB environment was not opened in CDS mode. so like, don't. 😭

πŸ’– $lock->cds_unlock();

removes a CDS lock. and the destruction of the CDS lock object automatically calls this method for you, no cap. 🧚

okay important note: if you created multiple CDS lock objects, the underlying write lock will not be released until all the CDS lock objects are either explicitly unlocked with this method, or the CDS lock objects have been destroyed. it's a whole group thing. πŸ‘‘


πŸ’– $ref = $db->db_stat()

returns a reference to an associative array stuffed with info about the database. the keys of that associative array line up directly with the names of the fields defined in the Berkeley DB documentation. like, in the DB docs, the field bt_version stores the version of the Btree database. so if you called db_stat on a Btree database, the equivalent field would be accessed like this:

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

if you're on Berkeley DB 3.x or better, this method works with all database formats. but when DB 2.x is used, it only works with BerkeleyDB::Btree. rough out here. πŸ’€


πŸ’– $status = $db->status()

returns the status of the last $db method that got called. receipts, basically. 🧾


πŸ’– $status = $db->truncate($count)

truncates the database and returns the number of records deleted inside $count. bye bye data πŸ‘‹


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

compacts the database $db. ✨

all the parameters are optional β€” if you only wanna use some of them, just drop "undef" in for the ones you don't want. and trailing unused parameters can be left off entirely. for example, if you only want to use the $c_data parameter to set the "compact_fillpercent", you'd write your code like this:

my %hash;
$hash{compact_fillpercent} = 50;
$db->compact(undef, undef, \%hash);

these parameters operate identically to the C equivalent of this method. the $c_data needs a lil explanation tho β€” it must be a hash reference. the values of these keys can be set before calling "compact" and they'll affect how the compaction operates:

  • compact_fillpercent
  • compact_timeout

and these keys, along with their associated values, get created in the hash reference if the "compact" operation was successful:

  • compact_deadlock
  • compact_levels
  • compact_pages_free
  • compact_pages_examine
  • compact_pages_truncated
you gotta be running Berkeley DB 4.4 or better if you wanna make use of "compact".

πŸ’– $status = $db->associate($secondary, \&key_callback)

associates $db with the secondary DB $secondary. 🫢

new key/value pairs inserted into the database get passed to the callback, which must set its third argument to the secondary key so lookup can happen. if an array reference is set, multiple secondary keys will be associated with the primary database entry. slay.

data may be retrieved fro the secondary database using "db_pget" to also obtain the primary key. (yes, the original says "fro". we're keeping it. iconic typo πŸ’…)

and bestie β€” secondary databases are maintained automatically. no manual labor required.


πŸ’– $status = $db->associate_foreign($secondary, callback, $flags)

associates a foreign key database $db with the secondary DB $secondary.

the second parameter must be a reference to a sub or "undef".

the $flags parameter must be either "DB_FOREIGN_CASCADE", "DB_FOREIGN_ABORT" or "DB_FOREIGN_NULLIFY".

when the flags parameter is "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);

and that's the whole common methods moment, but like β€” we are so not done yet. keep scrolling, we got more. πŸ¦‹

πŸ¦‹ CURSORS πŸ¦‹

okay so bestie, a cursor is what you reach for whenever you want to walk through a database's contents 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) ✨

Makes a whole duplicate of $cursor. This method needs Berkeley DB 3.0.x or better, no cap.

$flags is optional and can take this one value:

  • DB_POSITION β€” when you pass this, the new cursor gets plopped down at the exact same spot as the existing cursor.

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

Reads a key/value pair out of the database and hands you the data in $key and $value. Which pair you actually get is controlled by $flags, which can be one of these:

  • DB_FIRST β€” points the cursor at the first key/value pair in the database. Returns that pair in $key and $value.
  • DB_LAST β€” points the cursor at the last key/value pair in the database. Returns that pair in $key and $value.
  • DB_NEXT β€” if the cursor is already pointing at a key/value pair, it gets bumped forward to the next pair and its contents come back.
    • If the cursor isn't initialised, DB_NEXT behaves just like DB_FIRST.
    • If the cursor is already sitting on the last key/value pair, c_get returns DB_NOTFOUND.
  • DB_NEXT_DUP β€” this one's only valid when duplicate keys have been enabled on a database. If the cursor is already pointing at a key/value pair and the key of the next key/value pair is identical, the cursor gets incremented to point at it and the contents come back.
  • DB_PREV β€” if the cursor is already pointing at a key/value pair, it gets decremented back to the previous pair and returns its contents.
    • If the cursor isn't initialised, DB_PREV behaves just like DB_LAST.
    • If the cursor is already sitting on the first key/value pair, c_get returns DB_NOTFOUND.
  • DB_CURRENT β€” if the cursor has been set to point at a key/value pair, their contents get returned. But if the key/value pair the cursor references has been deleted, c_get returns DB_KEYEMPTY.
  • DB_SET β€” points the cursor at the key/value pair referenced by $key and returns the value in $value.
  • DB_SET_RANGE β€” this is a little remix of the DB_SET flag. As well as returning the value, it also returns the key, via $key. When you use it with a BerkeleyDB::Btree database, the key that c_get matches will be the shortest key (in length) that's greater than or equal to the key you supplied via $key. This is what makes partial key searches a thing. 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.

On top of all that, this next value can also 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. Where the data lands is controlled by $flags, which must take one of these:

  • DB_AFTER β€” when used with a Btree or Hash database, a duplicate of the key referenced by the current cursor position gets created, and the contents of $value get associated with it β€” $key is ignored. The new key/value pair gets stored immediately after the current cursor position. Obviously the database had 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 gets created, and the contents of $value get associated with it β€” $key is ignored. The new key/value pair gets stored immediately before the current cursor position. Obviously the database had to have been opened with DB_DUP.
    • When used with a Recno ... TODO
  • DB_CURRENT β€” if the cursor has been initialised, replaces 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 really only used when duplicates are enabled in the database and sorted duplicates haven't been specified. In that case the key/value pair gets inserted as the first entry in the duplicates for that particular key.
  • DB_KEYLAST β€” only valid with a Btree or Hash database. This flag is really only used when duplicates are enabled in the database and sorted duplicates haven't been specified. In that case the key/value pair gets inserted as the last entry in the duplicates for that particular key.

✨ $status = $cursor->c_del([$flags]) ✨

This method deletes the key/value pair hanging out at the current cursor position. Heads up: the cursor position is not changed by this operation, so any cursor operation you do after this has to first initialise the cursor to point at a valid key/value pair. πŸ’€

If the key/value pair associated with the cursor has already been deleted, c_del returns DB_KEYEMPTY.

The $flags parameter is not used at present.


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

Stashes the number of duplicates at the current cursor position into $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() ; ✨

See "db_pget"


✨ $status = $cursor->c_close() ✨

Closes the cursor $cursor. bye bestie 🫢


✨ $stream = $cursor->db_stream($flags); ✨

Creates a BerkeleyDB::DbStream object so you can read the blob at the current cursor location. See Blob for the 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.


πŸ“ 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 πŸ’Έ

Transactions get created using the txn_begin method on BerkeleyDB::Env:

        my $txn = $env->txn_begin;

If this is a nested transaction, hand over the parent transaction as an argument:

        my $child_txn = $env->txn_begin($parent_txn);

Then, so you can actually work with the transaction, you have to set it as the current transaction on the database handles you want to mess with:

        $db->Txn($txn);

Or, for multiple handles:

        $txn->Txn(@handles);

The current transaction is handed over by BerkeleyDB each time to the various BDB operations. In the C api it's required explicitly as an argument to every operation.

To commit a transaction, call the 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 Txn.


🫧 BerkeleyDBB::DbStream -- support for BLOB 🫧

Blob support is available in Berkeley DB starting with version 6.0. Go look at the section "Blob Support" in the Berkeley DB Programmer Reference for the details of how Blob support works.

A Blob is accessed 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:

🌸 $status = $stream->size($SIZE); 🌸

Outputs the length of the Blob into the $SIZE parameter.

🌸 $status = $stream->read($data, $offset, $size); 🌸

Reads 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.

🌸 $status = $stream->write($data, $offset, $flags); 🌸

Writes $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) ;
        }
    }

πŸ‘‘ Berkeley DB Concurrent Data Store (CDS) πŸ‘‘

The Berkeley DB Concurrent Data Store (CDS) is a lightweight locking mechanism that's useful in scenarios where transactions are, honestly, overkill.

🌈 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 hold 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.

🌈 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's suitable for the expected behaviour of your application.

The key features of this model are

  • All writes operations are serialised.
  • A write operation will block until all reads have finished.

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's 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. πŸ‘‹


πŸ”’ 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 "Safely Updating Records" and "Implicit Cursors" below. ✨

A Berkeley DB Cursor (created with $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 "cursor" method or the "cds_lock" method. 🫢

For full information on CDS see the "Berkeley DB Concurrent Data Store applications" section in the Berkeley DB Reference Guide.


πŸ“‚ 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 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 -Home option, unless you are happy for all these files to be written in the current directory.

Next, remember to include the "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.


πŸ›Ÿ 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 %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 "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 "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 "cds_lock", is supplied with the BerkeleyDB module for this purpose. Using "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, "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 "cds_lock" method will ensure that the current process has exclusive access to the database until the lock is either explicitly released, via the "$lk->cds_unlock()" or by the lock object being destroyed.

If you are interested, all that "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 "cds_lock" objects for one database within a single process, that process will hold a write-lock on the database until ALL "cds_lock" objects have been destroyed. πŸ‘‘

As with all write-cursors, you should try to limit the scope of the "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.


🚫 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_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 CANNOT carry out a write operation using a read-only cursor (i.e. you cannot use "c_put" or "c_del") whilst another write-cursor is already active.

The workaround for this issue is to just use "db_put" instead of "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";
}

πŸ«₯ 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, %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 "cursor" method or the "cds_lock" method.

The locking behaviour of the "values" or "keys" functions, shown below, is subtly different.

foreach my $k (keys %hash)
{
    # do something
}

foreach my $v (values %hash)
{
    # do something
}

Just like in the each function, a read cursor gets spun up to iterate over the database in both of these cases. Where keys and values differ from each is where the cursor does its iterating. each did one single iteration every time you called it, but keys and values iterate through the entire database in one go β€” the whole thing gets read into memory before the first loop iteration even happens. 😭

Apart from the fact that a read lock gets held for the entire time it takes to iterate through the database, using keys and values is not recommended because it results in the complete database being read into memory. It's giving memory-hungry. πŸ’€

Avoiding Deadlock with multiple databases

If your CDS application uses multiple database files, and you need to write to more than one of them, bestie you have 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 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


🌈 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. πŸ’…

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.

  1. Using the low-level API defined below.
  2. Using the 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.

Use of the DBM_Filter module is recommended. πŸ‘‘

✨ DBM Filter Low-level API ✨

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. (she just doesn't care about your return value, periodt πŸ’…)

πŸ’– 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. πŸ”₯

use strict ;
use BerkeleyDB ;

my %hash ;
my $filename = "filt.db" ;
unlink $filename ;

my $db = tie %hash, 'BerkeleyDB::Hash',
            -Filename   => $filename,
            -Flags      => DB_CREATE
  or die "Cannot open $filename: $!\n" ;

# Install DBM Filters
$db->filter_fetch_key  ( sub { s/\0$//    } ) ;
$db->filter_store_key  ( sub { $_ .= "\0" } ) ;
$db->filter_fetch_value( sub { s/\0$//    } ) ;
$db->filter_store_value( sub { $_ .= "\0" } ) ;

$hash{"abc"} = "def" ;
my $a = $hash{"ABC"} ;
# ...
undef $db ;
untie %hash ;

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. 😀

Here is a DBM Filter that does it:

use strict ;
use BerkeleyDB ;
my %hash ;
my $filename = "filt.db" ;
unlink $filename ;

my $db = tie %hash, 'BerkeleyDB::Btree',
            -Filename   => $filename,
            -Flags      => DB_CREATE
  or die "Cannot open $filename: $!\n" ;

$db->filter_fetch_key  ( sub { $_ = unpack("i", $_) } ) ;
$db->filter_store_key  ( sub { $_ = pack ("i", $_) } ) ;
$hash{123} = "def" ;
# ...
undef $db ;
untie %hash ;

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. Efficient queen behavior. πŸ‘‘


🫢 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.

use strict ;
use BerkeleyDB ;
use MLDBM qw(BerkeleyDB::Btree) ;
use Data::Dumper;

my $filename = 'testmldbm' ;
my %o ;

unlink $filename ;
tie %o, 'MLDBM', -Filename => $filename,
                 -Flags    => DB_CREATE
                or die "Cannot open database '$filename: $!\n";

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. it's giving old money, respectfully. πŸ’€

How do I store Perl data structures with BerkeleyDB?

See "Using BerkeleyDB with MLDBM".


🌸 HISTORY 🌸

See the Changes file.


πŸ’– SUPPORT πŸ’–

General feedback/questions/bug reports should be sent to <https://github.com/pmqs/BerkeleyDB/issues> (preferred) or <https://rt.cpan.org/Public/Dist/Display.html?Name=BerkeleyDB>.


✨ 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.oracle.com/technology/products/berkeley-db/db/index.html.


Copyright (c) 1997-2026 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. See AGPL <https://www.oracle.com/downloads/licenses/berkeleydb-oslicense.html> for more details. Please take the time to read the Berkeley DB license and decide how it impacts your use of this Perl module. (fr fr, read the license, bestie 🫢)


πŸŽ€ AUTHOR πŸŽ€

Paul Marquess <pmqs@cpan.org>.


πŸ¦‹ SEE ALSO πŸ¦‹

perl(1), DB_File, Berkeley DB.


and that's the whole page, bestie β€” every last crumb of it πŸ’…βœ¨ This was perl v5.42.0, dated 2026-02-02, and it's the BerkeleyDB(3) manpage. You read the entire thing. Not everyone can say that. main character energy fr. πŸŽ€πŸ’–πŸ¦‹πŸŒΈπŸ‘‘

πŸ“¦ where this page comes from