BerkeleyDB - Perl extension for Berkeley DB version 2, 3 or 4
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::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 ;
$status = $db->db_get() $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);
$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() ;
$cursor = $db->db_join() ; $status = $cursor->c_get() ; $status = $cursor->c_close() ;
$status = $env->txn_checkpoint() $hash_ref = $env->txn_stat() $status = $env->setmutexlocks() $status = $env->set_flags() $status = $env->set_timeout() $status = $env->lsn_reset()
$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() ;
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 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.
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.
$env = new BerkeleyDB::Env [ -Home => $path, ] [ -Server => $name, ] [ -CacheSize => $number, ] [ -Config => { name => value, name => value }, ] [ -ErrFile => filename, ] [ -ErrPrefix => "string", ] [ -Flags => number, ] [ -SetFlags => bitmask, ] [ -LockDetect => number, ] [ -SharedMemKey => number, ] [ -Verbose => boolean, ] [ -Encrypt => { Password => "string", Flags => number }, ]
All the parameters to the BerkeleyDB::Env constructor are optional.
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 ...
-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.
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.
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 => *STDOUT
or
-ErrFile => *STDERR
Any of the following can be specified by OR'ing them:
DB_CREATE
If any of the files specified do not already exist, create them.
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 ...
DB_INIT_TXN
Initialise the ...
DB_MPOOL_PRIVATE
Initialise the ...
DB_INIT_MPOOL is also specified.
Initialise the ...
DB_NOMMAP
Initialise the ...
DB_RECOVER
DB_RECOVER_FATAL
DB_THREAD
DB_TXN_NOSYNC
DB_USE_ENVIRON
DB_USE_ENVIRON_ROOT
Only valid when Berkeley DB 3.x or better is used.
DB_LOCK_DEFAULT
DB_LOCK_OLDEST
DB_LOCK_RANDOM
DB_LOCK_YOUNGEST
This method is deprecated. Access the transaction methods using the txn_ methods below from the environment object directly.
This option requires Berkeley DB 4.2 or better.
Use the "-SharedMemKey" option when opening the environemt to set the base segment ID.
$status = BerkeleyDB::db_remove [OPTIONS] $status = BerkeleyDB::db_rename [OPTIONS] $status = BerkeleyDB::db_verify [OPTIONS]
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.
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.
Each of the database formats described above is accessed via a corresponding BerkeleyDB class. These will be described in turn in the next sections.
Two forms of constructor are supported:
$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 }, ], # BerkeleyDB::Hash specific [ -Ffactor => number,] [ -Nelem => number,] [ -Hash => code reference,] [ -DupCompare => code reference,]
and this
[$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 }, ], # BerkeleyDB::Hash specific [ -Ffactor => number,] [ -Nelem => number,] [ -Hash => code reference,] [ -DupCompare => code reference,]
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
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.
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.
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, ...
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
Note that the like ordinary associative arrays, the order of the keys retrieved from a Hash database are in an apparently random order.
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 ;
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
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
Two forms of constructor are supported:
$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 }, ], # BerkeleyDB::Btree specific [ -Minkey => number,] [ -Compare => code reference,] [ -DupCompare => code reference,] [ -Prefix => code reference,]
and this
[$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 }, ], # BerkeleyDB::Btree specific [ -Minkey => number,] [ -Compare => code reference,] [ -DupCompare => code reference,] [ -Prefix => code reference,]
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.
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, ...
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, ... =item DupCompare
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, ...
All the methods below return 0 to indicate success.
The proportion is returned as a double in the range 0.0 to 1.0.
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 ;
Here is the output from the code above. The keys have been sorted using Berkeley DB's default sorting algorithm.
Smith Wall mouse
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 ;
Here is the output from the code above.
mouse Smith Wall
There are a few point to bear in mind if you want to change the ordering in a BTREE database:
Two forms of constructor are supported:
$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
[$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,]
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 ;
Here is the output from the script:
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
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
[$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,]
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 }, ],
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.
DB_RDONLY
Opens the database in read-only mode.
DB_THREAD
Not supported by BerkeleyDB.
DB_TRUNCATE
If the database file already exists, remove all the data before opening it.
Defaults to no environment.
-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.
All the methods below return 0 to indicate success.
The $flags parameter is optional. If present, it must be set to one of the following values:
In addition, the following value may be set by bitwise OR'ing it into the $flags parameter:
The $flags parameter is optional. If present it must be set to one of the following values:
TODO.
The $flags parameter is optional and is currently unused.
The $flags parameter is optional. If present it must be set to one of the following values:
It is a fatal error to attempt to create a cds_lock if the Berkeley DB environment has not been opened in CDS mode.
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.
$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.
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
my %hash; $hash{compact_fillpercent} = 50; $db->commit(undef, undef, \%hash);
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".
A cursor object has the following methods available:
The $flags parameter is optional and can take the following value:
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.
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.
In addition, the following value may be set by bitwise OR'ing it into the $flags parameter:
When used with a Recno ... TODO
When used with a Recno ... TODO
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.
The $flags parameter is not used at present. This method needs Berkeley DB 3.1 or better.
Iterating from first to last, then in reverse.
examples of each of the flags.
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:
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.
$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.
$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.
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.
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 official web site for Berkeley DB is http://www.sleepycat.com.
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.
Questions about Berkeley DB may be addressed to <db@sleepycat.com>.
Закладки на сайте Проследить за страницей |
Created 1996-2024 by Maxim Chirkov Добавить, Поддержать, Вебмастеру |