Berkeley DB Java Edition
version 5.0.34

com.sleepycat.je
Class Database

java.lang.Object
  extended by com.sleepycat.je.Database
All Implemented Interfaces:
Closeable
Direct Known Subclasses:
SecondaryDatabase

public class Database
extends Object
implements Closeable

A database handle.

Database attributes are specified in the DatabaseConfig class. Database handles are free-threaded and may be used concurrently by multiple threads.

To open an existing database with default attributes:

     Environment env = new Environment(home, null);
     Database myDatabase = env.openDatabase(null, "mydatabase", null);
 

To create a transactional database that supports duplicates:

     DatabaseConfig dbConfig = new DatabaseConfig();
     dbConfig.setTransactional(true);
     dbConfig.setAllowCreate(true);
     dbConfig.setSortedDuplicates(true);
     Database db = env.openDatabase(txn, "mydatabase", dbConfig);
 


Field Summary
protected  Logger logger
           
 
Constructor Summary
protected Database(Environment env)
          Creates a database but does not open or fully initialize it.
 
Method Summary
 void close()
          Discards the database handle.
 int compareDuplicates(DatabaseEntry entry1, DatabaseEntry entry2)
          Compares two data elements using either the default comparator if no duplicate comparator has been set or the duplicate comparator if one has been set.
 int compareKeys(DatabaseEntry entry1, DatabaseEntry entry2)
          Compares two keys using either the default comparator if no BTree comparator has been set or the BTree comparator if one has been set.
 long count()
          Counts the key/data pairs in the database.
 OperationStatus delete(Transaction txn, DatabaseEntry key)
          Removes key/data pairs from the database.
 OperationStatus get(Transaction txn, DatabaseEntry key, DatabaseEntry data, LockMode lockMode)
          Retrieves the key/data pair with the given key.
 DatabaseConfig getConfig()
          Returns this Database object's configuration.
 String getDatabaseName()
          Returns the database name.
 Environment getEnvironment()
          Returns the Environment handle for the database environment underlying the Database.
 OperationStatus getSearchBoth(Transaction txn, DatabaseEntry key, DatabaseEntry data, LockMode lockMode)
          Retrieves the key/data pair with the given key and data value, that is, both the key and data items must match.
 List<SecondaryDatabase> getSecondaryDatabases()
          Returns a list of all SecondaryDatabase objects associated with a primary database.
 DatabaseStats getStats(StatsConfig config)
          Returns database statistics.
 JoinCursor join(Cursor[] cursors, JoinConfig config)
          Creates a specialized join cursor for use in performing equality or natural joins on secondary indices.
 DiskOrderedCursor openCursor(DiskOrderedCursorConfig cursorConfig)
          Create a ForwardCursor to iterate over the records in 'this'.
 Cursor openCursor(Transaction txn, CursorConfig cursorConfig)
          Returns a cursor into the database.
 Sequence openSequence(Transaction txn, DatabaseEntry key, SequenceConfig config)
          Opens a sequence in the database.
 void preload(long maxBytes)
          Deprecated. As of JE 2.0.83, replaced by preload(PreloadConfig).

 void preload(long maxBytes, long maxMillisecs)
          Deprecated. As of JE 2.0.101, replaced by preload(PreloadConfig).

 PreloadStats preload(PreloadConfig config)
          Preloads the cache.
 OperationStatus put(Transaction txn, DatabaseEntry key, DatabaseEntry data)
          Stores the key/data pair into the database.
 OperationStatus putNoDupData(Transaction txn, DatabaseEntry key, DatabaseEntry data)
          Stores the key/data pair into the database if it does not already appear in the database.
 OperationStatus putNoOverwrite(Transaction txn, DatabaseEntry key, DatabaseEntry data)
          Stores the key/data pair into the database if the key does not already appear in the database.
 void removeSequence(Transaction txn, DatabaseEntry key)
          Removes the sequence from the database.
 void sync()
          Flushes any cached information for this database to disk; only applicable for deferred-write databases.
 DatabaseStats verify(VerifyConfig config)
          Verifies the integrity of the database.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

logger

protected final Logger logger
Constructor Detail

Database

protected Database(Environment env)
Creates a database but does not open or fully initialize it. Is protected for use in compat package.

Parameters:
env -
Method Detail

close

public void close()
           throws DatabaseException
Discards the database handle.

When closing the last open handle for a deferred-write database, any cached database information is flushed to disk as if sync() were called.

The database handle should not be closed while any other handle that refers to it is not yet closed; for example, database handles should not be closed while cursor handles into the database remain open, or transactions that include operations on the database have not yet been committed or aborted. Specifically, this includes Cursor and Transaction handles.

When multiple threads are using the Database handle concurrently, only a single thread may call this method.

When called on a database that is the primary database for a secondary index, the primary database should be closed only after all secondary indices which reference it have been closed.

The database handle may not be accessed again after this method is called, regardless of the method's success or failure.

WARNING: To guard against memory leaks, the application should discard all references to the closed handle. While BDB makes an effort to discard references from closed objects to the allocated memory for an environment, this behavior is not guaranteed. The safe course of action for an application is to discard all references to closed BDB objects.

Specified by:
close in interface Closeable
Throws:
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if cursors associated with this database are still open.
DatabaseException
See Also:
DatabaseConfig.setDeferredWrite

sync

public void sync()
          throws DatabaseException,
                 UnsupportedOperationException
Flushes any cached information for this database to disk; only applicable for deferred-write databases.

Note that deferred-write databases are automatically flushed to disk when the close() method is called.

Throws:
DatabasePreemptedException - in a replicated environment if the master has truncated, removed or renamed the database.
OperationFailureException - if this exception occurred earlier and caused the transaction to be invalidated.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
UnsupportedOperationException - if this is not a deferred-write database, or this database is read-only.
IllegalStateException - if the database has been closed.
DatabaseException
See Also:
DatabaseConfig.setDeferredWrite

openSequence

public Sequence openSequence(Transaction txn,
                             DatabaseEntry key,
                             SequenceConfig config)
                      throws SequenceNotFoundException,
                             SequenceExistsException
Opens a sequence in the database.

Parameters:
txn - For a transactional database, an explicit transaction may be specified, or null may be specified to use auto-commit. For a non-transactional database, null must be specified.
key - The key DatabaseEntry of the sequence.
config - The sequence attributes. If null, default attributes are used.
Returns:
a new Sequence handle.
Throws:
SequenceExistsException - if the sequence record already exists and the SequenceConfig ExclusiveCreate parameter is true.
SequenceNotFoundException - if the sequence record does not exist and the SequenceConfig AllowCreate parameter is false.
OperationFailureException - if one of the Read Operation Failures occurs. If the sequence does not exist and the AllowCreate parameter is true, then one of the Write Operation Failures may also occur.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
UnsupportedOperationException - if this database is read-only, or this database is configured for duplicates.
IllegalStateException - if the Sequence record is deleted by another thread during this method invocation, or the database has been closed.
IllegalArgumentException - if an invalid parameter is specified, for example, an invalid SequenceConfig parameter.

removeSequence

public void removeSequence(Transaction txn,
                           DatabaseEntry key)
                    throws DatabaseException
Removes the sequence from the database. This method should not be called if there are open handles on this sequence.

Parameters:
txn - For a transactional database, an explicit transaction may be specified, or null may be specified to use auto-commit. For a non-transactional database, null must be specified.
key - The key DatabaseEntry of the sequence.
Throws:
OperationFailureException - if one of the Write Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
UnsupportedOperationException - if this database is read-only.
DatabaseException

openCursor

public Cursor openCursor(Transaction txn,
                         CursorConfig cursorConfig)
                  throws DatabaseException,
                         IllegalArgumentException
Returns a cursor into the database.

Parameters:
txn - the transaction used to protect all operations performed with the cursor, or null if the operations should not be transaction protected. If the database is non-transactional, null must be specified. For a transactional database, the transaction is optional for read-only access and required for read-write access.
cursorConfig - The cursor attributes. If null, default attributes are used.
Returns:
A database cursor.
Throws:
DatabasePreemptedException - in a replicated environment if the master has truncated, removed or renamed the database.
OperationFailureException - if this exception occurred earlier and caused the transaction to be invalidated.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
IllegalArgumentException - if an invalid parameter is specified, for example, an invalid CursorConfig parameter.
DatabaseException

openCursor

public DiskOrderedCursor openCursor(DiskOrderedCursorConfig cursorConfig)
                             throws DatabaseException,
                                    IllegalArgumentException
Create a ForwardCursor to iterate over the records in 'this'. Because the retrieval is based on Log Sequence Number (LSN) order rather than key order, records are returned in unsorted order in exchange for generally faster retrieval. LSN order approximates disk sector order. The records returned by the scan correspond to the state of the data at the beginning of the scan plus some, but not all, changes made by the application after the start of the scan. The user should not rely on the scan returning any changes made after the start of the scan. Specifically, if the record referred to by the ForwardCursor in a DiskOrderedScan is deleted after the ForwardCursor is positioned at that record, getCurrent() will still return the key and value of that record and OperationStatus.SUCCESS. As with a READ_UNCOMMITTED scan, changes made by all transactions, including uncommitted transactions, may be returned by the scan. Also, a record returned by the scan is not locked, and may be modified or deleted by the application after it is returned, including modification or deletion of the record at the cursor position. If a transactionally correct data set is required, the application must ensure that all transactions that write to the key range are committed before the beginning of the scan, and that during the scan no records in the key range of the scan are inserted, deleted, or modified.

WARNING: After calling this method, deletion of log files by the JE log cleaner will be disabled until ForwardCursor.close() is called. To prevent unbounded growth of disk usage, be sure to call ForwardCursor.close() to re-enable log file deletion.

WARNING: During initialization of a Disk Ordered Scan, the internal nodes of the btree are latched for read and this may cause reduced performance for concurrent update operations. This pause may be limited using DiskOrderedCursorConfig.setMaxSeedMillisecs(long) or DiskOrderedCursorConfig.setMaxSeedNodes(long).

Throws:
DatabaseException
IllegalArgumentException

delete

public OperationStatus delete(Transaction txn,
                              DatabaseEntry key)
                       throws DeleteConstraintException,
                              LockConflictException,
                              DatabaseException,
                              UnsupportedOperationException,
                              IllegalArgumentException
Removes key/data pairs from the database.

The key/data pair associated with the specified key is discarded from the database. In the presence of duplicate key values, all records associated with the designated key will be discarded.

The key/data pair is also deleted from any associated secondary databases.

Parameters:
txn - For a transactional database, an explicit transaction may be specified, or null may be specified to use auto-commit. For a non-transactional database, null must be specified.
key - the key DatabaseEntry operated on.
Returns:
The method will return OperationStatus.NOTFOUND if the specified key is not found in the database; otherwise the method will return OperationStatus.SUCCESS.
Throws:
OperationFailureException - if one of the Write Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
UnsupportedOperationException - if this database is read-only.
IllegalStateException - if the database has been closed.
IllegalArgumentException - if an invalid parameter is specified.
DeleteConstraintException
LockConflictException
DatabaseException

get

public OperationStatus get(Transaction txn,
                           DatabaseEntry key,
                           DatabaseEntry data,
                           LockMode lockMode)
                    throws LockConflictException,
                           DatabaseException,
                           IllegalArgumentException
Retrieves the key/data pair with the given key. If the matching key has duplicate values, the first data item in the set of duplicates is returned. Retrieval of duplicates requires the use of Cursor operations.

Parameters:
txn - For a transactional database, an explicit transaction may be specified to transaction-protect the operation, or null may be specified to perform the operation without transaction protection. For a non-transactional database, null must be specified.
key - the key used as input. It must be initialized with a non-null byte array by the caller.
data - the data returned as output. Its byte array does not need to be initialized by the caller. A partial data item may be specified to optimize for key only or partial data retrieval.
lockMode - the locking attributes; if null, default attributes are used.
Returns:
OperationStatus.NOTFOUND if no matching key/data pair is found; otherwise, OperationStatus.SUCCESS.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
IllegalArgumentException - if an invalid parameter is specified.
LockConflictException
DatabaseException

getSearchBoth

public OperationStatus getSearchBoth(Transaction txn,
                                     DatabaseEntry key,
                                     DatabaseEntry data,
                                     LockMode lockMode)
                              throws LockConflictException,
                                     DatabaseException,
                                     IllegalArgumentException
Retrieves the key/data pair with the given key and data value, that is, both the key and data items must match.

Parameters:
txn - For a transactional database, an explicit transaction may be specified to transaction-protect the operation, or null may be specified to perform the operation without transaction protection. For a non-transactional database, null must be specified.
key - the key used as input. It must be initialized with a non-null byte array by the caller.
data - the data used as input. It must be initialized with a non-null byte array by the caller.
lockMode - the locking attributes; if null, default attributes are used.
Returns:
OperationStatus.NOTFOUND if no matching key/data pair is found; otherwise, OperationStatus.SUCCESS.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
IllegalArgumentException - if an invalid parameter is specified.
LockConflictException
DatabaseException

put

public OperationStatus put(Transaction txn,
                           DatabaseEntry key,
                           DatabaseEntry data)
                    throws DatabaseException
Stores the key/data pair into the database.

If the key already appears in the database and duplicates are not configured, the data associated with the key will be replaced. If the key already appears in the database and sorted duplicates are configured, the new data value is inserted at the correct sorted location.

Parameters:
txn - For a transactional database, an explicit transaction may be specified, or null may be specified to use auto-commit. For a non-transactional database, null must be specified.
key - the key DatabaseEntry operated on.
data - the data DatabaseEntry stored.
Returns:
OperationStatus.SUCCESS if the operation succeeds.
Throws:
OperationFailureException - if one of the Write Operation Failures occurs.
OperationFailureException - if this exception occurred earlier and caused the transaction to be invalidated.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
UnsupportedOperationException - if this database is read-only.
IllegalStateException - if the database has been closed.
DatabaseException

putNoOverwrite

public OperationStatus putNoOverwrite(Transaction txn,
                                      DatabaseEntry key,
                                      DatabaseEntry data)
                               throws DatabaseException
Stores the key/data pair into the database if the key does not already appear in the database.

This method will return OpeationStatus.KEYEXIST if the key already exists in the database, even if the database supports duplicates.

Parameters:
txn - For a transactional database, an explicit transaction may be specified, or null may be specified to use auto-commit. For a non-transactional database, null must be specified.
key - the key DatabaseEntry operated on.
data - the data DatabaseEntry stored.
Returns:
OperationStatus.KEYEXIST if the key already appears in the database, else OperationStatus.SUCCESS
Throws:
OperationFailureException - if one of the Write Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
UnsupportedOperationException - if this database is read-only.
IllegalStateException - if the database has been closed.
DatabaseException

putNoDupData

public OperationStatus putNoDupData(Transaction txn,
                                    DatabaseEntry key,
                                    DatabaseEntry data)
                             throws DatabaseException
Stores the key/data pair into the database if it does not already appear in the database.

This method may only be called if the underlying database has been configured to support sorted duplicates.

Parameters:
txn - For a transactional database, an explicit transaction may be specified, or null may be specified to use auto-commit. For a non-transactional database, null must be specified.
key - the key DatabaseEntry operated on.
data - the data DatabaseEntry stored.
Returns:
OperationStatus.KEYEXIST if the key/data pair already appears in the database, else OperationStatus.SUCCESS
Throws:
OperationFailureException - if one of the Write Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
UnsupportedOperationException - if this database is not configured for duplicates, or this database is read-only.
IllegalStateException - if the database has been closed.
DatabaseException

join

public JoinCursor join(Cursor[] cursors,
                       JoinConfig config)
                throws DatabaseException,
                       IllegalArgumentException
Creates a specialized join cursor for use in performing equality or natural joins on secondary indices.

Each cursor in the cursors array must have been initialized to refer to the key on which the underlying database should be joined. Typically, this initialization is done by calling Cursor.getSearchKey.

Once the cursors have been passed to this method, they should not be accessed or modified until the newly created join cursor has been closed, or else inconsistent results may be returned. However, the position of the cursors will not be changed by this method or by the methods of the join cursor.

Parameters:
cursors - an array of cursors associated with this primary database. In a replicated environment, an explicit transaction must be specified when opening each cursor, unless read-uncommitted isolation is isolation is specified via the CursorConfig or LockMode parameter.
config - The join attributes. If null, default attributes are used.
Returns:
a specialized cursor that returns the results of the equality join operation.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
IllegalArgumentException - if an invalid parameter is specified, for example, an invalid JoinConfig parameter.
DatabaseException
See Also:
JoinCursor

preload

public void preload(long maxBytes)
             throws DatabaseException
Deprecated. As of JE 2.0.83, replaced by preload(PreloadConfig).

Preloads the cache. This method should only be called when there are no operations being performed on the database in other threads. Executing preload during concurrent updates may result in some or all of the tree being loaded into the JE cache. Executing preload during any other types of operations may result in JE exceeding its allocated cache size. preload() effectively locks the entire database and therefore will lock out the checkpointer, cleaner, and compressor, as well as not allow eviction to occur.

Parameters:
maxBytes - The maximum number of bytes to load. If maxBytes is 0, je.evictor.maxMemory is used.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
DatabaseException

preload

public void preload(long maxBytes,
                    long maxMillisecs)
             throws DatabaseException
Deprecated. As of JE 2.0.101, replaced by preload(PreloadConfig).

Preloads the cache. This method should only be called when there are no operations being performed on the database in other threads. Executing preload during concurrent updates may result in some or all of the tree being loaded into the JE cache. Executing preload during any other types of operations may result in JE exceeding its allocated cache size. preload() effectively locks the entire database and therefore will lock out the checkpointer, cleaner, and compressor, as well as not allow eviction to occur.

Parameters:
maxBytes - The maximum number of bytes to load. If maxBytes is 0, je.evictor.maxMemory is used.
maxMillisecs - The maximum time in milliseconds to use when preloading. Preloading stops once this limit has been reached. If maxMillisecs is 0, preloading can go on indefinitely or until maxBytes (if non-0) is reached.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
DatabaseException

preload

public PreloadStats preload(PreloadConfig config)
                     throws DatabaseException
Preloads the cache. This method should only be called when there are no operations being performed on the database in other threads. Executing preload during concurrent updates may result in some or all of the tree being loaded into the JE cache. Executing preload during any other types of operations may result in JE exceeding its allocated cache size. preload() effectively locks the entire database and therefore will lock out the checkpointer, cleaner, and compressor, as well as not allow eviction to occur.

While this method preloads a single database, Environment.preload(com.sleepycat.je.Database[], com.sleepycat.je.PreloadConfig) lets you preload multiple databases.

Parameters:
config - The PreloadConfig object that specifies the parameters of the preload.
Returns:
A PreloadStats object with various statistics about the preload() operation.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
IllegalArgumentException - if PreloadConfig.getMaxBytes is greater than size of the JE cache.
DatabaseException

count

public long count()
           throws DatabaseException
Counts the key/data pairs in the database. This operation is faster than obtaining a count from a cursor based scan of the database, and will not perturb the current contents of the cache. However, the count is not guaranteed to be accurate if there are concurrent updates.

A count of the key/data pairs in the database is returned without adding to the cache. The count may not be accurate in the face of concurrent update operations in the database.

Returns:
The count of key/data pairs in the database.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
DatabaseException

getStats

public DatabaseStats getStats(StatsConfig config)
                       throws DatabaseException
Returns database statistics.

If this method has not been configured to avoid expensive operations (using the StatsConfig.setFast method), it will access some of or all the pages in the database, incurring a severe performance penalty as well as possibly flushing the underlying cache.

In the presence of multiple threads or processes accessing an active database, the information returned by this method may be out-of-date.

Parameters:
config - The statistics returned; if null, default statistics are returned.
Returns:
Database statistics.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
DatabaseException

verify

public DatabaseStats verify(VerifyConfig config)
                     throws DatabaseException
Verifies the integrity of the database.

Verification is an expensive operation that should normally only be used for troubleshooting and debugging.

Parameters:
config - Configures the verify operation; if null, the default operation is performed.
Returns:
Database statistics.
Throws:
OperationFailureException - if one of the Read Operation Failures occurs.
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.
IllegalStateException - if the database has been closed.
IllegalArgumentException - if an invalid parameter is specified.
DatabaseException

getDatabaseName

public String getDatabaseName()
                       throws DatabaseException
Returns the database name.

This method may be called at any time during the life of the application.

Returns:
The database name.
Throws:
DatabaseException

getConfig

public DatabaseConfig getConfig()
Returns this Database object's configuration.

This may differ from the configuration used to open this object if the database existed previously.

Returns:
This Database object's configuration.
Throws:
EnvironmentFailureException - if an unexpected, internal or environment-wide failure occurs.

getEnvironment

public Environment getEnvironment()
Returns the Environment handle for the database environment underlying the Database.

This method may be called at any time during the life of the application.

Returns:
The Environment handle for the database environment underlying the Database.

getSecondaryDatabases

public List<SecondaryDatabase> getSecondaryDatabases()
                                              throws DatabaseException
Returns a list of all SecondaryDatabase objects associated with a primary database.

If no secondaries are associated or this is itself a secondary database, an empty list is returned.

Returns:
A list of all SecondaryDatabase objects associated with a primary database.
Throws:
DatabaseException

compareKeys

public int compareKeys(DatabaseEntry entry1,
                       DatabaseEntry entry2)
Compares two keys using either the default comparator if no BTree comparator has been set or the BTree comparator if one has been set.

Returns:
-1 if entry1 compares less than entry2, 0 if entry1 compares equal to entry2, 1 if entry1 compares greater than entry2
Throws:
IllegalArgumentException - if either entry is a partial DatabaseEntry, or is null.

compareDuplicates

public int compareDuplicates(DatabaseEntry entry1,
                             DatabaseEntry entry2)
Compares two data elements using either the default comparator if no duplicate comparator has been set or the duplicate comparator if one has been set.

Returns:
-1 if entry1 compares less than entry2, 0 if entry1 compares equal to entry2, 1 if entry1 compares greater than entry2
Throws:
IllegalArgumentException - if either entry is a partial DatabaseEntry, or is null.

Berkeley DB Java Edition
version 5.0.34

Copyright (c) 2004-2011 Oracle. All rights reserved.