com.sleepycat.je
Class Database

java.lang.Object
  extended by com.sleepycat.je.Database
Direct Known Subclasses:
SecondaryDatabase

public class Database
extends java.lang.Object

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 newlyCreateDb = env.openDatabase(txn, "mydatabase", dbConfig);
 


Nested Class Summary
(package private) static class Database.DbState
           
 
Field Summary
(package private) static Database.DbState CLOSED
           
(package private)  DatabaseConfig configuration
           
(package private)  Environment envHandle
           
(package private)  Locker handleLocker
           
(package private) static Database.DbState INVALID
           
(package private) static Database.DbState OPEN
           
 
Constructor Summary
protected Database(Environment env)
          Creates a database but does not open or fully initialize it.
 
Method Summary
(package private)  void addCursor(Cursor dbc)
           
(package private)  void addTrigger(DatabaseTrigger trigger, boolean insertAtFront)
          Adds a given trigger to the list of triggers.
(package private)  void checkEnv()
           
(package private)  void checkProhibitedDbState(Database.DbState prohibited, java.lang.String msg)
           
(package private)  void checkRequiredDbState(Database.DbState required, java.lang.String msg)
           
 void close()
          Discards the database handle.
 long count()
          Counts the key/data pairs in the database.
 OperationStatus delete(Transaction txn, DatabaseEntry key)
          Removes key/data pairs from the database.
(package private)  OperationStatus deleteInternal(Locker locker, DatabaseEntry key, DatabaseEntry data)
          Internal version of delete() that does no parameter checking.
 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.
(package private)  DatabaseImpl getDatabaseImpl()
          Returns the databaseImpl object instance.
 java.lang.String getDatabaseName()
          Returns the database name.
(package private)  java.lang.String getDebugName()
           
 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.
 java.util.List<SecondaryDatabase> getSecondaryDatabases()
          Returns a list of all SecondaryDatabase objects associated with a primary database.
 DatabaseStats getStats(StatsConfig config)
          Returns database statistics.
(package private)  boolean hasTriggers()
          Returns whether any triggers are currently associated with this primary.
(package private)  void initExisting(Environment env, Locker locker, DatabaseImpl databaseImpl, DatabaseConfig dbConfig)
          Opens a database, called by Environment.
(package private)  void initNew(Environment env, Locker locker, java.lang.String databaseName, DatabaseConfig dbConfig)
          Creates a database, called by Environment.
(package private)  void invalidate()
          Invalidates the handle, called by txn.abort by way of DbInternal.
(package private)  boolean isTransactional()
          Equivalent to getConfig().getTransactional() but cheaper.
(package private)  boolean isWritable()
          Returns true if the Database was opened read/write.
 JoinCursor join(Cursor[] cursors, JoinConfig config)
          Creates a specialized join cursor for use in performing equality or natural joins on secondary indices.
(package private)  Cursor newDbcInstance(Transaction txn, CursorConfig cursorConfig)
          Is overridden by SecondaryDatabase.
(package private)  void notifyTriggers(Locker locker, DatabaseEntry priKey, DatabaseEntry oldData, DatabaseEntry newData)
          Notifies associated triggers when a put() or delete() is performed on the primary.
 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.
(package private)  OperationStatus putInternal(Transaction txn, DatabaseEntry key, DatabaseEntry data, PutMode putMode)
          Internal version of put() that does no parameter checking.
 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.
(package private)  void removeCursor(Cursor dbc)
           
 void removeSequence(Transaction txn, DatabaseEntry key)
          Removes the sequence from the database.
(package private)  void removeTrigger(DatabaseTrigger trigger)
          Removes a given trigger from the list of triggers.
(package private)  void setHandleLocker(Locker locker)
          The handleLocker is the one that holds the db handle lock.
 void sync()
          Flushes any cached information for this database to disk; only applicable for deferred-write databases.
(package private)  void trace(java.util.logging.Level level, java.lang.String methodName, Transaction txn, CursorConfig config)
          Sends trace messages to the java.util.logger.
(package private)  void trace(java.util.logging.Level level, java.lang.String methodName, Transaction txn, DatabaseEntry key, DatabaseEntry data, LockMode lockMode)
          Sends trace messages to the java.util.logger.
 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

OPEN

static Database.DbState OPEN

CLOSED

static Database.DbState CLOSED

INVALID

static Database.DbState INVALID

envHandle

Environment envHandle

configuration

DatabaseConfig configuration

handleLocker

Locker handleLocker
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

initNew

void initNew(Environment env,
             Locker locker,
             java.lang.String databaseName,
             DatabaseConfig dbConfig)
       throws DatabaseException
Creates a database, called by Environment.

Throws:
DatabaseException

initExisting

void initExisting(Environment env,
                  Locker locker,
                  DatabaseImpl databaseImpl,
                  DatabaseConfig dbConfig)
            throws DatabaseException
Opens a database, called by Environment.

Throws:
DatabaseException

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.

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

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.

Throws:
DatabaseException - if a failure occurs.
See Also:
DatabaseConfig.setDeferredWrite

sync

public void sync()
          throws DatabaseException
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:
DatabaseException - if a failure occurs.
See Also:
DatabaseConfig.setDeferredWrite

openSequence

public Sequence openSequence(Transaction txn,
                             DatabaseEntry key,
                             SequenceConfig config)
                      throws DatabaseException
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 sequence handle.
Throws:
DatabaseException - if a failure occurs.

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

openCursor

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

Parameters:
txn - To use a cursor for writing to a transactional database, an explicit transaction must be specified. For read-only access to a transactional database, the transaction may be null. For a non-transactional database, the transaction must be null.

To transaction-protect cursor operations, cursors must be opened and closed within the context of a transaction, and the txn parameter specifies the transaction context in which the cursor will be used.

cursorConfig - The cursor attributes. If null, default attributes are used.
Returns:
A database cursor.
Throws:
DatabaseException - if a failure occurs.

newDbcInstance

Cursor newDbcInstance(Transaction txn,
                      CursorConfig cursorConfig)
                throws DatabaseException
Is overridden by SecondaryDatabase.

Throws:
DatabaseException

delete

public OperationStatus delete(Transaction txn,
                              DatabaseEntry key)
                       throws DatabaseException
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:
DeadlockException - if the operation was selected to resolve a deadlock.
DatabaseException - if a failure occurs.

deleteInternal

OperationStatus deleteInternal(Locker locker,
                               DatabaseEntry key,
                               DatabaseEntry data)
                         throws DatabaseException
Internal version of delete() that does no parameter checking. Notify triggers. Deletes all duplicates.

Throws:
DatabaseException

get

public OperationStatus get(Transaction txn,
                           DatabaseEntry key,
                           DatabaseEntry data,
                           LockMode lockMode)
                    throws DatabaseException
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.
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:
DeadlockException - if the operation was selected to resolve a deadlock.
java.lang.IllegalArgumentException - if an invalid parameter was specified.
DatabaseException - if a failure occurs.

getSearchBoth

public OperationStatus getSearchBoth(Transaction txn,
                                     DatabaseEntry key,
                                     DatabaseEntry data,
                                     LockMode lockMode)
                              throws DatabaseException
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 keyused as input. It must be initialized with a non-null byte array by the caller.
data - the dataused 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:
DeadlockException - if the operation was selected to resolve a deadlock.
java.lang.IllegalArgumentException - if an invalid parameter was specified.
DatabaseException - if a failure occurs.

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:
DeadlockException - if the operation was selected to resolve a deadlock.
DatabaseException - if a failure occurs.

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:
DeadlockException - if the operation was selected to resolve a deadlock.
DatabaseException - if any other failure occurs.

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:
true if the key/data pair already appears in the database, this method will return OperationStatus.KEYEXIST.
Throws:
DeadlockException - if the operation was selected to resolve a deadlock.
DatabaseException - if a failure occurs.

putInternal

OperationStatus putInternal(Transaction txn,
                            DatabaseEntry key,
                            DatabaseEntry data,
                            PutMode putMode)
                      throws DatabaseException
Internal version of put() that does no parameter checking.

Throws:
DatabaseException

join

public JoinCursor join(Cursor[] cursors,
                       JoinConfig config)
                throws DatabaseException
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.
config - The join attributes. If null, default attributes are used.
Returns:
a specialized cursor that returns the results of the equality join operation.
Throws:
DatabaseException - if a failure occurs. @see 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:
DatabaseException - if a failure occurs.

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:
DatabaseException - if a failure occurs.

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.

Parameters:
config - The PreloadConfig object that specifies the parameters of the preload.
Returns:
A PreloadStats object with various statistics about the preload() operation.
Throws:
DatabaseException - if a failure occurs.

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:
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:
DeadlockException - if the operation was selected to resolve a deadlock.
DatabaseException - if a failure occurs.

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:
java.lang.IllegalArgumentException - if an invalid parameter was specified.
DatabaseException - if a failure occurs.

getDatabaseName

public java.lang.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

getDebugName

java.lang.String getDebugName()

getConfig

public DatabaseConfig getConfig()
                         throws DatabaseException
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:
DatabaseException - if a failure occurs.

isTransactional

boolean isTransactional()
                  throws DatabaseException
Equivalent to getConfig().getTransactional() but cheaper.

Throws:
DatabaseException

getEnvironment

public Environment getEnvironment()
                           throws DatabaseException
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.
Throws:
DatabaseException - if a failure occurs.

getSecondaryDatabases

public java.util.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

isWritable

boolean isWritable()
Returns true if the Database was opened read/write.

Returns:
true if the Database was opened read/write.

getDatabaseImpl

DatabaseImpl getDatabaseImpl()
Returns the databaseImpl object instance.


setHandleLocker

void setHandleLocker(Locker locker)
The handleLocker is the one that holds the db handle lock.


removeCursor

void removeCursor(Cursor dbc)

addCursor

void addCursor(Cursor dbc)

checkRequiredDbState

void checkRequiredDbState(Database.DbState required,
                          java.lang.String msg)
                    throws DatabaseException
Throws:
DatabaseException - if the Database state is not this value.

checkProhibitedDbState

void checkProhibitedDbState(Database.DbState prohibited,
                            java.lang.String msg)
                      throws DatabaseException
Throws:
DatabaseException - if the Database state is this value.

checkEnv

void checkEnv()
        throws RunRecoveryException
Throws:
RunRecoveryException - if the underlying environment is invalid

invalidate

void invalidate()
Invalidates the handle, called by txn.abort by way of DbInternal. Note that this method (unlike close) does not call handleClosed, which performs sync and removal of DW DBs. A DW DB cannot be transactional.


trace

void trace(java.util.logging.Level level,
           java.lang.String methodName,
           Transaction txn,
           DatabaseEntry key,
           DatabaseEntry data,
           LockMode lockMode)
     throws DatabaseException
Sends trace messages to the java.util.logger. Don't rely on the logger alone to conditionalize whether we send this message, we don't even want to construct the message if the level is not enabled.

Throws:
DatabaseException

trace

void trace(java.util.logging.Level level,
           java.lang.String methodName,
           Transaction txn,
           CursorConfig config)
     throws DatabaseException
Sends trace messages to the java.util.logger. Don't rely on the logger alone to conditionalize whether we send this message, we don't even want to construct the message if the level is not enabled.

Throws:
DatabaseException

hasTriggers

boolean hasTriggers()
Returns whether any triggers are currently associated with this primary. Note that an update of the trigger list may be in progress and this method does not wait for that update to be completed.


addTrigger

void addTrigger(DatabaseTrigger trigger,
                boolean insertAtFront)
          throws DatabaseException
Adds a given trigger to the list of triggers. Called while opening a SecondaryDatabase.

Parameters:
insertAtFront - true to insert at the front, or false to append.
Throws:
DatabaseException

removeTrigger

void removeTrigger(DatabaseTrigger trigger)
             throws DatabaseException
Removes a given trigger from the list of triggers. Called by SecondaryDatabase.close().

Throws:
DatabaseException

notifyTriggers

void notifyTriggers(Locker locker,
                    DatabaseEntry priKey,
                    DatabaseEntry oldData,
                    DatabaseEntry newData)
              throws DatabaseException
Notifies associated triggers when a put() or delete() is performed on the primary. This method is normally called only if hasTriggers() has returned true earlier. This avoids acquiring a shared latch for primaries with no triggers. If a trigger is added during the update process, there is no requirement to immediately start updating it.

Parameters:
locker - the internal locker.
priKey - the primary key.
oldData - the primary data before the change, or null if the record did not previously exist.
newData - the primary data after the change, or null if the record has been deleted.
Throws:
DatabaseException


Copyright (c) 2004,2008 Oracle. All rights reserved.