Introduction

Berkeley DB 4.x Python Extension Package

Introduction

Types Provided

Exceptions Provided

DBError

Base class, all others derive from this

DBIncompleteError

DB_INCOMPLETE

DBKeyEmptyError

DB_KEYEMPTY

DBKeyExistError

DB_KEYEXIST

DBLockDeadlockError

DB_LOCK_DEADLOCK

DBLockNotGrantedError

DB_LOCK_NOTGRANTED

DBNotFoundError

DB_NOTFOUND (also derives from KeyError)

DBOldVersionError

DB_OLD_VERSION

DBRunRecoveryError

DB_RUNRECOVERY

DBVerifyBadError

DB_VERIFY_BAD

DBNoServerError

DB_NOSERVER

DBNoServerHomeError

DB_NOSERVER_HOME

DBNoServerIDError

DB_NOSERVER_ID

DBInvalidArgError

EINVAL

DBAccessError

EACCES

DBNoSpaceError

ENOSPC

DBNoMemoryError

ENOMEM

DBAgainError

EAGAIN

DBBusyError

EBUSY

DBFileExistsError

EEXIST

DBNoSuchFileError

ENOENT

DBPermissionsError

EPERM

Other Package Modules

Testing

Reference

DBEnv

DBEnv Attributes

DBEnv(flags=0)
database home directory (read-only)

DBEnv Methods

DBEnv(flags=0)

Constructor. More info...

set_rpc_server(host, cl_timeout=0, sv_timeout=0)

Establishes a connection for this dbenv to a RPC server. More info...

close(flags=0)

Close the database environment, freeing resources. More info...

open(homedir, flags=0, mode=0660)

Prepare the database environment for use. More info...

remove(homedir, flags=0)

Remove a database environment. More info...

dbremove(file, database=None, txn=None, flags=0)

Removes the database specified by the file and database parameters. If no database is specified, the underlying file represented by file is removed, incidentally removing all of the databases it contained. More info...

dbrename(file, database=None, newname, txn=None, flags=0)

Renames the database specified by the file and database parameters to newname. If no database is specified, the underlying file represented by file is renamed, incidentally renaming all of the databases it contained. More info...

set_encrypt(passwd, flags=0)

Set the password used by the Berkeley DB library to perform encryption and decryption. More info...

set_timeout(timeout, flags)

Sets timeout values for locks or transactions in the database environment. More info...

set_shm_key(key)

Specify a base segment ID for Berkeley DB environment shared memory regions created in system memory on VxWorks or systems supporting X/Open-style shared memory interfaces; for example, UNIX systems supporting shmget(2) and related System V IPC interfaces. More info...

set_cachesize(gbytes, bytes, ncache=0)

Set the size of the shared memory buffer pool. More info...

set_data_dir(dir)

Set the environment data directory. More info...

set_flags(flags, onoff)

Set additional flags for the DBEnv. The onoff parameter specifes if the flag is set or cleared. More info...

set_tmp_dir(dir)

Set the directory to be used for temporary files. More info...

set_get_returns_none(flag)
By default when DB.get or DBCursor.get, get_both, first, last, next or prev encounter a DB_NOTFOUND error they return None instead of raising DBNotFoundError. This behaviour emulates Python dictionaries and is convenient for looping.
  • You can use this method to toggle that behaviour for all of the aformentioned methods or extend it to also apply to the DBCursor.set, set_both, set_range, and set_recno methods. Supported values of flag:
    • 0 all DB and DBCursor get and set methods will raise a DBNotFoundError rather than returning None.

    • 1 Default in module version <4.2.4 The DB.get and DBCursor.get, get_both, first, last, next and prev methods return None.

    • 2 Default in module version >=4.2.4 Extends the behaviour of 1 to the DBCursor set, set_both, set_range and set_recno methods.

    The default of returning None makes it easy to do things like this without having to catch DBNotFoundError (KeyError):

  •    1 data = mydb.get(key)
       2 if data:
       3     doSomething(data)
    

       1 rec = cursor.first()
       2 while rec:
       3     print rec
       4     rec = cursor.next()
    

       1 rec = mydb.set()
       2 while rec:
       3     key, val = rec
       4     doSomething(key, val)
       5     rec = mydb.next()
    

    id

    Last allocated lock ID.

    cur_maxid

    The current maximum unused locker ID.

    nmodes

    Number of lock modes.

    maxlocks

    Maximum number of locks possible.

    maxlockers

    Maximum number of lockers possible.

    maxobjects

    Maximum number of objects possible.

    nlocks

    Number of current locks.

    maxnlocks

    Maximum number of locks at once.

    nlockers

    Number of current lockers.

    nobjects

    Number of current lock objects.

    maxnobjects

    Maximum number of lock objects at once.

    maxnlockers

    Maximum number of lockers at once.

    nrequests

    Total number of locks requested.

    nreleases

    Total number of locks released.

    nupgrade

    Total number of locks upgraded.

    ndowngrade

    Total number of locks downgraded.

    lock_wait

    The number of lock requests not immediately available due to conflicts, for which the thread of control waited.

    lock_nowait

    The number of lock requests not immediately available due to conflicts, for which the thread of control did not wait.

    ndeadlocks

    Number of deadlocks.

    locktimeout

    Lock timeout value.

    nlocktimeouts

    The number of lock requests that have timed out.

    txntimeout

    Transaction timeout value.

    ntxntimeouts

    The number of transactions that have timed out. This value is also a component of ndeadlocks, the total number of deadlocks detected.

    objs_wait

    The number of requests to allocate or deallocate an object for which the thread of control waited.

    objs_nowait

    The number of requests to allocate or deallocate an object for which the thread of control did not wait.

    lockers_wait

    The number of requests to allocate or deallocate a locker for which the thread of control waited.

    lockers_nowait

    The number of requests to allocate or deallocate a locker for which the thread of control did not wait.

    locks_wait

    The number of requests to allocate or deallocate a lock structure for which the thread of control waited.

    locks_nowait

    The number of requests to allocate or deallocate a lock structure for which the thread of control did not wait.

    hash_len

    Maximum length of a lock hash bucket.

    regsize

    Size of the region.

    region_wait

    Number of times a thread of control was forced to wait before obtaining the region lock.

    region_nowait

    Number of times a thread of control was able to obtain the region lock without waiting.

    magic

    The magic number that identifies a file as a log file.

    version

    The version of the log file type.

    ||mode|| The mode of any created log files.

    lg_bsize

    The in-memory log record cache size.

    lg_size

    The log file size.

    record

    The number of records written to this log.

    w_mbytes

    The number of megabytes written to this log.

    w_bytes

    The number of bytes over and above w_mbytes written to this log.

    wc_mbytes

    The number of megabytes written to this log since the last checkpoint.

    wc_bytes

    The number of bytes over and above wc_mbytes written to this log since the last checkpoint.

    wcount

    The number of times the log has been written to disk.

    wcount_fill

    The number of times the log has been written to disk because the in-memory log record cache filled up.

    rcount

    The number of times the log has been read from disk.

    scount

    The number of times the log has been flushed to disk.

    cur_file

    The current log file number.

    cur_offset

    The byte offset in the current log file.

    disk_file

    The log file number of the last record known to be on disk.

    disk_offset

    The byte offset of the last record known to be on disk.

    maxcommitperflush

    The maximum number of commits contained in a single log flush.

    mincommitperflush

    The minimum number of commits contained in a single log flush that contained a commit.

    regsize

    The size of the log region, in bytes.

    region_wait

    The number of times that a thread of control was forced to wait before obtaining the log region mutex.

    region_nowait The number of times that a thread of control was able to obtain the log region mutex without waiting.

    DBEnv Replication Manager Methods

    perm_failed

    The number of times a message critical for maintaining database integrity (for example, a transaction commit), originating at this site, did not receive sufficient acknowledgement from clients, according to the configured acknowledgement policy and acknowledgement timeout.

    msgs_queued

    The number of outgoing messages which could not be transmitted immediately, due to a full network buffer, and had to be queued for later delivery.

    msgs_dropped

    The number of outgoing messages that were completely dropped, because the outgoing message queue was full. (Berkeley DB replication is tolerant of dropped messages, and will automatically request retransmission of any missing messages as needed.)

    connection_drop

    The number of times an existing TCP/IP connection failed.

    connect_fail

    The number of times an attempt to open a new TCP/IP connection failed.

    DBEnv Replication Methods

    rep_elect(nsites, nvotes)

    Holds an election for the master of a replication group. More info...

    rep_set_transport(envid, transportFunc)

    Initializes the communication infrastructure for a database environment participating in a replicated application. More info...

    rep_process_messsage(control, rec, envid)
    Processes an incoming replication message sent by a member of the replication group to the local database environment.
  • Returns a two element tuple.

    More info...

    rep_start(flags, cdata=None)
    Configures the database environment as a client or master in a group of replicated database environments.

    The DB_ENV->rep_start method is not called by most replication applications. It should only be called by applications implementing their own network transport layer, explicitly holding replication group elections and handling replication messages outside of the replication manager framework. More info...

    rep_sync()

    Forces master synchronization to begin for this client. This method is the other half of setting the DB_REP_CONF_DELAYCLIENT flag via the DB_ENV->rep_set_config method. More info...

    rep_set_config(which, onoff)

    Configures the Berkeley DB replication subsystem. More info...

    rep_get_config(which)

    Returns whether the specified which parameter is currently set or not. More info...

    rep_set_limit(bytes)

    Sets a byte-count limit on the amount of data that will be transmitted from a site in response to a single message processed by the DB_ENV->rep_process_message method. The limit is not a hard limit, and the record that exceeds the limit is the last record to be sent. More info...

    rep_get_limit()

    Gets a byte-count limit on the amount of data that will be transmitted from a site in response to a single message processed by the DB_ENV->rep_process_message method. The limit is not a hard limit, and the record that exceeds the limit is the last record to be sent. More info...

    rep_set_request(minimum, maximum)

    Sets a threshold for the minimum and maximum time that a client waits before requesting retransmission of a missing message. Specifically, if the client detects a gap in the sequence of incoming log records or database pages, Berkeley DB will wait for at least min microseconds before requesting retransmission of the missing record. Berkeley DB will double that amount before requesting the same missing record again, and so on, up to a maximum threshold of max microseconds. More info...

    rep_get_request()

    Returns a tuple with the minimum and maximum number of microseconds a client waits before requesting retransmission. More info...

    rep_set_nsites(nsites)

    Specifies the total number of sites in a replication group. More info...

    rep_get_nsites()

    Returns the total number of sites in the replication group. More info...

    rep_set_priority(priority)

    Specifies the database environment’s priority in replication group elections. The priority must be a positive integer, or 0 if this environment cannot be a replication group master. More info...

    rep_get_priority()

    Returns the database environment priority. More info...

    rep_set_timeout(which, timeout)

    Specifies a variety of replication timeout values. More info...

    rep_get_timeout(which)

    Returns the timeout value for the specified which parameter. More info...

  • DB

    DB Methods

    DB(dbEnv=None, flags=0)

    Constructor. More info...

    append(data, txn=None)

    A convenient version of put() that can be used for Recno or Queue databases. The DB_APPEND flag is automatically used, and the record number is returned. More info...

    associate(secondaryDB, callback, txn=None, flags=0)

    Used to associate secondaryDB to act as a secondary index for this (primary) database. The callback parameter should be a reference to a Python callable object that will construct and return the secondary key or DB_DONOTINDEX if the item should not be indexed. The parameters the callback will receive are the primaryKey and primaryData values. More info...

    close(flags=0)

    Flushes cached data and closes the database. More info...

    consume(txn=None, flags=0)

    For a database with the Queue access method, returns the record number and data from the first available record and deletes it from the queue. More info...

    consume_wait(txn=None, flags=0)

    For a database with the Queue access method, returns the record number and data from the first available record and deletes it from the queue. If the Queue database is empty, the thread of control will wait until there is data in the queue before returning. More info...

    cursor(txn=None, flags=0)

    Create a cursor on the DB and returns a DBCursor object. If a transaction is passed then the cursor can only be used within that transaction and you must be sure to close the cursor before commiting the transaction. More info...

    delete(key, txn=None, flags=0)

    Removes a key/data pair from the database. More info...

    fd()

    Returns a file descriptor for the database. More info...

    get(key, default=None, txn=None, flags=0, dlen=-1, doff=-1)

    Returns the data object associated with key. If key is an integer then the DB_SET_RECNO flag is automatically set for BTree databases and the actual key and the data value are returned as a tuple. If default is given then it is returned if the key is not found in the database. Partial records can be read using dlen and doff, however be sure to not read beyond the end of the actual data or you may get garbage. More info...

    pget(key, default=None, txn=None, flags=0, dlen=-1, doff=-1)

    This method is available only on secondary databases. It will return the primary key, given the secondary one, and associated data. More info...

    set_private(object)
    Link an arbitrary object to the DB.
    get_private()
    Give the object linked to the DB.
    get_both(key, data, txn=None, flags=0)

    A convenient version of get() that automatically sets the DB_GET_BOTH flag, and which will be successful only if both the key and data value are found in the database. (Can be used to verify the presence of a record in the database when duplicate keys are allowed.) More info...

    get_byteswapped()

    May be used to determine if the database was created on a machine with the same endianess as the current machine. More info...

    get_size(key, txn=None)
    Return the size of the data object associated with key.
    get_type()

    Return the database’s access method type. More info...

    join(cursorList, flags=0)

    Create and return a specialized cursor for use in performing joins on secondary indices. More info...

    key_range(key, txn=None, flags=0)

    Returns an estimate of the proportion of keys that are less than, equal to and greater than the specified key. More info...

    open(filename, dbname=None, dbtype=DB_UNKNOWN, flags=0, mode=0660, txn=None)

    Opens the database named dbname in the file named filename. The dbname argument is optional and allows applications to have multiple logical databases in a single physical file. It is an error to attempt to open a second database in a file that was not initially created using a database name. In-memory databases never intended to be shared or preserved on disk may be created by setting both the filename and dbname arguments to None. More info...

    put(key, data, txn=None, flags=0, dlen=-1, doff=-1)

    Stores the key/data pair in the database. If the DB_APPEND flag is used and the database is using the Recno or Queue access method then the record number allocated to the data is returned. Partial data objects can be written using dlen and doff. More info...

    remove(filename, dbname=None, flags=0)

    Remove a database. More info...

    rename(filename, dbname, newname, flags=0)

    Rename a database. More info...

    set_encrypt(passwd, flags=0)

    Set the password used by the Berkeley DB library to perform encryption and decryption. Because databases opened within Berkeley DB environments use the password specified to the environment, it is an error to attempt to set a password in a database created within an environment. More info...

    set_bt_compare(compareFunc)

    Set the B-Tree database comparison function. This can only be called once before the database has been opened. compareFunc takes two arguments: (left key string, right key string) It must return a -1, 0, 1 integer similar to cmp. You can shoot your database in the foot, beware! Read the Berkeley DB docs for the full details of how the comparison function MUST behave. More info...

    set_bt_minkey(minKeys)

    Set the minimum number of keys that will be stored on any single BTree page. More info...

    set_cachesize(gbytes, bytes, ncache=0)

    Set the size of the database’s shared memory buffer pool. More info...

    set_get_returns_none(flag)
    Controls what get and related methods do when a key is not found.

    magic

    Magic number that identifies the file as a Hash database.

    version

    Version of the Hash database.

    nkeys

    Number of unique keys in the database.

    ndata

    Number of key/data pairs in the database.

    pagecnt

    The number of pages in the database.

    pagesize

    Underlying Hash database page (& bucket) size.

    nelem

    Estimated size of the hash table specified at database creation time.

    ffactor

    Desired fill factor (number of items per bucket) specified at database creation time.

    buckets

    Number of hash buckets.

    free

    Number of pages on the free list.

    bfree

    Number of bytes free on bucket pages.

    bigpages

    Number of big key/data pages.

    big_bfree

    Number of bytes free on big item pages.

    overflows

    Number of overflow pages (overflow pages are pages that contain items that did not fit in the main bucket page).

    ovfl_free

    Number of bytes free on overflow pages.

    dup

    Number of duplicate pages.

    dup_free

    Number of bytes free on duplicate pages.

    magic

    Magic number that identifies the file as a Btree database.

    version

    Version of the Btree database.

    nkeys

    For the Btree Access Method, the number of unique keys in the database.For the Recno Access Method, the number of records in the database. If the database has been configured to not re-number records during deletion, the number of records may include records that have been deleted.

    ndata

    For the Btree Access Method, the number of key/data pairs in the database.For the Recno Access Method, the number of records in the database. If the database has been configured to not re-number records during deletion, the number of records may include records that have been deleted.

    pagecnt

    The number of pages in the database.

    pagesize

    Underlying database page size.

    minkey

    Minimum keys per page.

    re_len

    Length of fixed-length records.

    re_pad

    Padding byte value for fixed-length records.

    levels

    Number of levels in the database.

    int_pg

    Number of database internal pages.

    leaf_pg

    Number of database leaf pages.

    dup_pg

    Number of database duplicate pages.

    over_pg

    Number of database overflow pages.

    empty_pg

    Number of empty database pages.

    free

    Number of pages on the free list.

    int_pgfree

    Num of bytes free in database internal pages.

    leaf_pgfree

    Number of bytes free in database leaf pages.

    dup_pgfree

    Num bytes free in database duplicate pages.

    over_pgfree

    Num of bytes free in database overflow pages.

    magic

    Magic number that identifies the file as a Queue database.

    version

    Version of the Queue file type.

    nkeys

    Number of records in the database.

    ndata

    Number of records in the database.

    pagesize

    Underlying database page size.

    extentsize

    Underlying database extent size, in pages.

    pages

    Number of pages in the database.

    re_len

    Length of the records.

    re_pad

    Padding byte value for the records.

    pgfree

    Number of bytes free in database pages.

    first_recno

    First undeleted record in the database.

    cur_recno

    Last allocated record number in the database.

    DB Mapping and Compatibility Methods

    DBCursor

    DBCursor Methods

    close()

    Discards the cursor. If the cursor is created within a transaction then you must be sure to close the cursor before commiting the transaction. More info...

    count(flags=0)

    Returns a count of the number of duplicate data items for the key referenced by the cursor. More info...

    delete(flags=0)

    Deletes the key/data pair currently referenced by the cursor. More info...

    dup(flags=0)

    Create a new cursor. More info...

    put(key, data, flags=0, dlen=-1, doff=-1)

    Stores the key/data pair into the database. Partial data records can be written using dlen and doff. More info...

    get(flags, dlen=-1, doff=-1)
    See get(key, data, flags, dlen=-1, doff=-1) below.
    get(key, flags, dlen=-1, doff=-1)
    See get(key, data, flags, dlen=-1, doff=-1) below.
    get(key, data, flags, dlen=-1, doff=-1)

    Retrieves key/data pairs from the database using the cursor. All the specific functionalities of the get method are actually provided by the various methods below, which are the preferred way to fetch data using the cursor. These generic interfaces are only provided as an inconvenience. Partial data records are returned if dlen and doff are used in this method and in many of the specific methods below. More info...

    pget(flags, dlen=-1, doff=-1)
    See pget(key, data, flags, dlen=-1, doff=-1) below.
    pget(key, flags, dlen=-1, doff=-1)
    See pget(key, data, flags, dlen=-1, doff=-1) below.
    pget(key, data, flags, dlen=-1, doff=-1)

    Similar to the already described get(). This method is available only on secondary databases. It will return the primary key, given the secondary one, and associated data More info...

    DBCursor Get Methods

    DBTxn

    DBTxn Methods

    abort()

    Aborts the transaction More info...

    commit(flags=0)

    Ends the transaction, committing any changes to the databases. More info...

    id()

    The txn_id function returns the unique transaction id associated with the specified transaction. More info...

    prepare(gid)

    Initiates the beginning of a two-phase commit. Begining with Berkeley DB 3.3 a global identifier paramater is required, which is a value unique across all processes involved in the commit. It must be a string of DB_XIDDATASIZE bytes. More info...

    discard()
    This method frees up all the per-process resources associated with the specified transaction, neither committing nor aborting the transaction. The transaction will be keep in “unresolved” state. This call may be used only after calls to “dbenv.txn_recover()”. A “unresolved” transaction will be returned again thru new calls to “dbenv.txn_recover()”.

    DBLock

    DBSequence

    DBSequence Methods

    DBSequence(db, flags=0)

    Constructor. More info...

    open(key, txn=None, flags=0)

    Opens the sequence represented by the key. More info...

    close(flags=0)

    Close a DBSequence handle. More info...

    initial_value(value)

    Set the initial value for a sequence. This call is only effective when the sequence is being created. More info...

    get(delta=1, txn=None, flags=0)

    Returns the next available element in the sequence and changes the sequence value by delta. More info...

    get_dbp()

    Returns the DB object associated to the DBSequence. More info...

    get_key()

    Returns the key for the sequence. More info...

    remove(txn=None, flags=0)

    Removes the sequence from the database. This method should not be called if there are other open handles on this sequence. More info...

    get_cachesize()

    Returns the current cache size. More info...

    set_cachesize(size)

    Configure the number of elements cached by a sequence handle. More info...

    get_flags()

    Returns the current flags. More info...

    set_flags(flags)

    Configure a sequence. More info...

    stat(flags=0)
    Returns a dictionary of sequence statistics with the following keys:

    wait

    The number of times a thread of control was forced to wait on the handle mutex.

    nowait

    The number of times that a thread of control was able to obtain handle mutex without waiting.

    current

    The current value of the sequence in the database.

    value

    The current cached value of the sequence.

    last_value

    The last cached value of the sequence.

    min

    The minimum permitted value of the sequence.

    max

    The maximum permitted value of the sequence.

    cache_size

    The number of values that will be cached in this handle.

    flags

    The flags value for the sequence.

    History

    PythonBindingsForBerkeleyDB4.0Thru4.7En (last edited 2009-12-25 07:16:19 by localhost)