Package db

Class DBHandle

java.lang.Object
db.DBHandle
Direct Known Subclasses:
PackedDBHandle

public class DBHandle extends Object
DBHandle provides access to an open database.
  • Field Details

  • Constructor Details

    • DBHandle

      public DBHandle() throws IOException
      Construct a temporary database handle. The saveAs method must be used to save the database.
      Throws:
      IOException - if a IO error occurs
    • DBHandle

      public DBHandle(int requestedBufferSize) throws IOException
      Construct a temporary database handle. The saveAs method must be used to save the database.
      Parameters:
      requestedBufferSize - requested buffer size. Actual buffer size may vary.
      Throws:
      IOException - if a IO error occurs
    • DBHandle

      public DBHandle(int requestedBufferSize, long approxCacheSize) throws IOException
      Construct a temporary database handle. The saveAs method must be used to save the database.
      Parameters:
      requestedBufferSize - requested buffer size. Actual buffer size may vary.
      approxCacheSize - approximate size of cache in Bytes.
      Throws:
      IOException - if a IO error occurs
    • DBHandle

      public DBHandle(BufferFile bufferFile) throws IOException
      Open the database contained within the specified bufferFile. The update mode is determined by the buffer file.
      Parameters:
      bufferFile - database buffer file
      Throws:
      IOException - if IO error occurs
    • DBHandle

      public DBHandle(BufferFile bufferFile, boolean recover, TaskMonitor monitor) throws IOException, CancelledException
      Open the database contained within the specified bufferFile. The update mode is determined by the buffer file.
      Parameters:
      bufferFile - database buffer file
      recover - if true an attempt will be made to recover unsaved data if the file is open for update
      monitor - recovery monitor
      Throws:
      IOException - if IO error occurs
      CancelledException - if buffer file recovery is cancelled
    • DBHandle

      public DBHandle(File file) throws IOException
      Open a specific buffer file containing a database for non-update use. This method is provided primarily for testing.
      Parameters:
      file - buffer file
      Throws:
      IOException - if IO error occurs
  • Method Details

    • isConsistent

      public boolean isConsistent(TaskMonitor monitor) throws CancelledException
      Check the consistency of this database.
      Parameters:
      monitor - task monitor
      Returns:
      true if consistency check passed, else false
      Throws:
      CancelledException - if consistency check is cancelled
    • rebuild

      public boolean rebuild(TaskMonitor monitor) throws CancelledException
      Rebuild database tables to resolve certain consistency problems. Use of this method does not recover lost data which may have occurred during original database corruption.
      Parameters:
      monitor - task monitor
      Returns:
      true if rebuild succeeded, else false
      Throws:
      CancelledException - if rebuild is cancelled
    • resetDatabaseId

      public static void resetDatabaseId(File file) throws IOException
      Reset the database ID contained within the specified database file. This method is intended to be used when unpacking a packed database to ensure that a duplicate database ID does not exist within the project. WARNING! Use with extreme caution since this modifies the original file and could destroy data if used improperly.
      Parameters:
      file - database buffer file to be updated
      Throws:
      IOException - if IO error occurs
    • getDatabaseId

      public long getDatabaseId()
      Returns:
      unique database ID or 0 if this is an older read-only database.
    • getRecoveryChangeSetFile

      public LocalBufferFile getRecoveryChangeSetFile() throws IOException
      Returns the recovery changeSet data file for reading or null if one is not available. The caller must dispose of the returned file before peforming generating any new recovery snapshots.
      Returns:
      recovery changeSet data file for reading or null if one is not available.
      Throws:
      IOException - if IO error occurs
    • takeRecoverySnapshot

      public boolean takeRecoverySnapshot(DBChangeSet changeSet, TaskMonitor monitor) throws CancelledException, IOException
      Request a recovery snapshot be taken of any unsaved changes;
      Parameters:
      changeSet - an optional database-backed change set which reflects changes made since the last version.
      monitor - task monitor
      Returns:
      true if snapshot successful or not needed, false if an active transaction prevented snapshot
      Throws:
      CancelledException - if cancelled by monitor
      IOException - if IO error occurs
    • getScratchPad

      public DBHandle getScratchPad() throws IOException
      Returns a shared temporary database handle. This temporary handle will remain open unitl either this handle is closed or closeScratchPad is invoked.
      Returns:
      shared temporary database handle.
      Throws:
      IOException - if IO error occurs
    • closeScratchPad

      public void closeScratchPad()
      Close the scratch-pad database handle if it open.
    • addListener

      public void addListener(DBListener listener)
      Add Database listener
      Parameters:
      listener - database listener
    • enablePreCache

      public void enablePreCache()
      Enable and start source file pre-cache if appropriate. WARNING! EXPERIMENTAL !!!
    • checkTransaction

      public void checkTransaction()
      Verify that a valid transaction has been started.
      Throws:
      NoTransactionException - if transaction has not been started
      TerminatedTransactionException - transaction was prematurely terminated
    • checkIsClosed

      public void checkIsClosed() throws ClosedException
      Check if the database is closed.
      Throws:
      ClosedException - if database is closed and further operations are unsupported
    • isTransactionActive

      public boolean isTransactionActive()
      Returns:
      true if transaction is currently active
    • openTransaction

      public Transaction openTransaction(ErrorHandler errorHandler) throws IllegalStateException
      Open new transaction. This should generally be done with a try-with-resources block:
       try (Transaction tx = dbHandle.openTransaction(dbErrorHandler)) {
              // ... Do something
       }
       
      Parameters:
      errorHandler - handler resposible for handling an IOException which may result during transaction processing. In general, a RuntimeException should be thrown by the handler to ensure continued processing is properly signaled/interupted.
      Returns:
      transaction object
      Throws:
      IllegalStateException - if transaction is already active or this DBHandle has already been closed.
    • startTransaction

      public long startTransaction()
      Start a new transaction
      Returns:
      transaction ID
    • endTransaction

      public boolean endTransaction(long id, boolean commit) throws IOException
      End current transaction. If commit is false a rollback may occur followed by DBListener.dbRestored(DBHandle) notification to listeners.
      Parameters:
      id - transaction ID
      commit - if true a new checkpoint will be established for active transaction, if false all changes since the previous checkpoint will be discarded.
      Returns:
      true if new checkpoint established, false if nothing to commit or commit parameter specified as false and active transaction is terminated with rollback.
      Throws:
      IOException - if IO error occurs
    • hasUncommittedChanges

      public boolean hasUncommittedChanges()
      Returns true if there are uncommitted changes to the database.
      Returns:
      true if there are uncommitted changes to the database.
    • setDBVersionedSourceFile

      public void setDBVersionedSourceFile(BufferFile versionedSourceBufferFile) throws IOException
      Set the DB source buffer file with a newer local buffer file version. Intended for use following a merge or commit operation only where a local checkout has been retained.
      Parameters:
      versionedSourceBufferFile - updated local DB source buffer file opened for versioning update (NOTE: file itself is read-only). File must be an instance of LocalManagedBufferFile.
      Throws:
      IOException - if an IO error occurs
    • terminateTransaction

      public void terminateTransaction(long id, boolean commit) throws IOException
      Terminate current transaction. If commit is false a rollback may occur followed by DBListener.dbRestored(DBHandle) notification to listeners. This method is very similar to endTransaction(long, boolean) with the added behavior of setting the internal DBHandle state such that any subsequent invocations of checkTransaction() will throw a TerminatedTransactionException until a new transaction is started.
      Parameters:
      id - transaction ID
      commit - if true a new checkpoint will be established for active transaction, if false all changes since the previous checkpoint will be discarded.
      Throws:
      IOException - if IO error occurs
    • canUndo

      public boolean canUndo()
      Determine if there are any changes which can be undone.
      Returns:
      true if an undo can be performed.
    • undo

      public boolean undo() throws IOException
      Undo changes made during the previous transaction checkpoint. All upper-levels must clear table-based cached data prior to invoking this method.
      Returns:
      true if an undo was successful, else false if not allowed
      Throws:
      IOException - if IO error occurs
    • getAvailableUndoCount

      public int getAvailableUndoCount()
      Returns:
      number of undo-able transactions
    • getAvailableRedoCount

      public int getAvailableRedoCount()
      Returns:
      the number of redo-able transactions
    • canRedo

      public boolean canRedo()
      Determine if there are any changes which can be redone
      Returns:
      true if a redo can be performed.
    • redo

      public boolean redo() throws IOException
      Redo previously undone transaction checkpoint. Moves forward by one checkpoint only. All upper-levels must clear table-based cached data prior to invoking this method.
      Returns:
      boolean if redo is successful, else false if undo not allowed
      Throws:
      IOException - if IO error occurs
    • setMaxUndos

      public void setMaxUndos(int maxUndos)
      Set the maximum number of undo transaction checkpoints maintained by the underlying buffer manager.
      Parameters:
      maxUndos - maximum number of undo checkpoints. An illegal value restores the default value.
    • getTableCount

      public int getTableCount()
      Return the number of tables defined within the master table.
      Returns:
      int number of tables.
    • close

      public void close()
      Close the database and dispose of the underlying buffer manager. Any existing recovery data will be discarded.
    • close

      public void close(boolean keepRecoveryData)
      Close the database and dispose of the underlying buffer manager.
      Parameters:
      keepRecoveryData - true if existing recovery data should be retained or false to remove any recovery data
    • isChanged

      public boolean isChanged()
      Returns:
      true if unsaved changes have been made.
    • isClosed

      public boolean isClosed()
      Returns:
      true if this database handle has been closed.
    • save

      public void save(String comment, DBChangeSet changeSet, TaskMonitor monitor) throws IOException, CancelledException
      Save this database to a new version.
      Parameters:
      comment - if version history is maintained, this comment will be associated with the new version.
      changeSet - an optional database-backed change set which reflects changes made since the last version.
      monitor - progress monitor
      Throws:
      CancelledException - if task monitor cancelled operation.
      IOException - thrown if an IO error occurs.
    • saveAs

      public void saveAs(BufferFile outFile, boolean associateWithNewFile, TaskMonitor monitor) throws IOException, CancelledException
      Save the database to the specified buffer file.
      Parameters:
      outFile - buffer file open for writing
      associateWithNewFile - if true the outFile will be associated with this DBHandle as the current source file, if false no change will be made to this DBHandle's state and the outFile will be written and set as read-only. The caller is responsbile for disposing the outFile if this parameter is false.
      monitor - progress monitor
      Throws:
      IOException - if IO error occurs
      CancelledException - if monitor cancels operation
    • saveAs

      protected void saveAs(BufferFile outFile, Long newDatabaseId, boolean associateWithNewFile, TaskMonitor monitor) throws IOException, CancelledException
      Save the database to the specified buffer file and a newDatabaseId. Open handle will always be associated with the new file. NOTE: This method is intended for use in transforming one database to match another existing database.
      Parameters:
      outFile - buffer file open for writing
      newDatabaseId - database ID to be forced for new database or null to generate new database ID
      associateWithNewFile - if true the outFile will be associated with this DBHandle as the current source file, if false no change will be made to this DBHandle's state and the outFile will be written and set as read-only. The caller is responsbile for disposing the outFile if this parameter is false.
      monitor - progress monitor
      Throws:
      IOException - if IO error occurs
      CancelledException - if monitor cancels operation
    • saveAs

      public void saveAs(File file, boolean associateWithNewFile, TaskMonitor monitor) throws IOException, CancelledException
      Save the database to the specified buffer file.
      Parameters:
      file - buffer file to be created
      associateWithNewFile - if true the outFile will be associated with this DBHandle as the current source file, if false no change will be made to this DBHandle's state and the outFile will be written and set as read-only. The caller is responsbile for disposing the outFile if this parameter is false.
      monitor - progress monitor
      Throws:
      DuplicateFileException - if file already exists.
      IOException - if IO error occurs
      CancelledException - if monitor cancels operation
    • createBuffer

      public DBBuffer createBuffer(int length) throws IOException
      Create a new buffer with the specified length. This method may only be invoked while a database transaction is in progress. A database transaction must also be in progress when invoking the various put, delete and setSize methods on the returned buffer.
      Parameters:
      length - the size of the buffer to create
      Returns:
      Buffer the newly created buffer
      Throws:
      IOException - if an I/O error occurs while creating the buffer.
    • createBuffer

      public DBBuffer createBuffer(DBBuffer shadowBuffer) throws IOException
      Create a new buffer that layers on top of another buffer. This buffer will return values from the shadowBuffer unless they have been changed in this buffer. This method may only be invoked while a database transaction is in progress. A database transaction must also be in progress when invoking the various put, delete and setSize methods on the returned buffer.
      Parameters:
      shadowBuffer - the source of the byte values to use unless they have been changed.
      Returns:
      Buffer the newly created buffer
      Throws:
      IOException - if an I/O error occurs while creating the buffer.
    • getBuffer

      public DBBuffer getBuffer(int id) throws IOException
      Get an existing buffer. This method should be used with care to avoid providing an improper id. A database transaction must be in progress when invoking the various put, delete and setSize methods on the returned buffer.
      Parameters:
      id - the buffer id.
      Returns:
      Buffer the buffer associated with the given id.
      Throws:
      IOException - if an I/O error occurs while getting the buffer.
    • getBuffer

      public DBBuffer getBuffer(int id, DBBuffer shadowBuffer) throws IOException
      Get an existing buffer that uses a shadowBuffer for byte values if they haven't been explicitly changed in this buffer. This method should be used with care to avoid providing an improper id. A database transaction must be in progress when invoking the various put, delete and setSize methods on the returned buffer.
      Parameters:
      id - the buffer id.
      shadowBuffer - the buffer to use for byte values if they haven't been changed in this buffer.
      Returns:
      Buffer the buffer associated with the given id.
      Throws:
      IOException - if an I/O error occurs while getting the buffer.
    • canUpdate

      public boolean canUpdate()
      Determine if this database can be updated.
      Returns:
      true if this database handle is intended for update
    • getTable

      public Table getTable(String name)
      Returns the Table that was created with the given name or null if no such table exists.
      Parameters:
      name - of requested table
      Returns:
      table instance or null if not found
    • getTables

      public Table[] getTables()
      Get all tables defined within the database.
      Returns:
      Table[] tables
    • createTable

      public Table createTable(String name, Schema schema) throws IOException
      Creates a new table with the given name and schema.
      Parameters:
      name - table name
      schema - table schema
      Returns:
      new table instance
      Throws:
      IOException - if IO error occurs during table creation
    • createTable

      public Table createTable(String name, Schema schema, int[] indexedColumns) throws IOException
      Creates a new table with the given name and schema. Create secondary indexes as specified by the array of column indexes.
      Parameters:
      name - table name
      schema - table schema
      indexedColumns - array of column indices which should have an index associated with them
      Returns:
      new table instance
      Throws:
      IOException - if IO error occurs during table creation
    • setTableName

      public boolean setTableName(String oldName, String newName) throws DuplicateNameException
      Changes the name of an existing table.
      Parameters:
      oldName - the old name of the table
      newName - the new name of the table
      Returns:
      true if the name was changed successfully
      Throws:
      DuplicateNameException - if a table with the new name already exists
    • deleteTable

      public void deleteTable(String name) throws IOException
      Delete the specified table from the database.
      Parameters:
      name - table name
      Throws:
      IOException - if there is an I/O error or the table does not exist
    • getCacheHits

      public long getCacheHits()
      Returns:
      number of buffer cache hits
    • getCacheMisses

      public long getCacheMisses()
      Returns:
      number of buffer cache misses
    • getLowBufferCount

      public int getLowBufferCount()
      Returns:
      low water mark (minimum buffer pool size)
    • finalize

      protected void finalize() throws Throwable
      Overrides:
      finalize in class Object
      Throws:
      Throwable
    • getBufferSize

      public int getBufferSize()
      Returns size of buffers utilized within the underlying buffer file. This may be larger than than the requested buffer size. This value may be used to instatiate a new BufferFile which is compatible with this database when using the saveAs method.
      Returns:
      buffer size utilized by this database