# The Java Connection Class

Connection provides the interface for all threads interacting with a Database object.

### For an overview see page Java Classes

### Class Definition

        public class Connection implements java.io.Closeable
        {
            /* Constructors */
            public Connection(Database db)
            {
                this.db = db;
                id = connect(db.name, null);
            }
            public Connection(Database db, byte[] context)
            {
                this.db = db;
                id = connect(db.name, context);
            }
            protected Connection(Connection con) {
                db = con.db;
                id = con.id;
            }
            /* Close - disconnect methods */
            public void disconnect()
            {
                if (id != 0)
                {
                    disconnect(id);
                    id = 0;
                }
            }
            public void close()
            {
                disconnect();
            }

            /* Transaction methods */
            public void startTransaction(Database.TransactionType type)
            {
                startTransaction(type, Database.TransactionPriority.Foreground,
                            Database.IsolationLevel.Default);
            }

            public void startTransaction(Database.TransactionType type,
                                Database.TransactionPriority pri,
                                Database.IsolationLevel level)
            {
                startTransaction(id, type.ordinal(), pri.ordinal(), level.ordinal());
            }
            public boolean commitTransaction()
            {
                return commitTransaction(id);
            }
            public boolean commitTransaction(int phase)
            {
                if (phase != 1 && phase != 2)
                {
                    throw new IllegalArgumentException("Invalid phase: " + phase);
                }
                return commitTransactionPhase(id, phase);
            }
            public void setCommitPolicy(Database.CommitPolicy policy)
            {
                setCommitPolicy(id, policy.ordinal());
            }
            public void diskFlush()
            {
                diskFlush(id);
            }
            public void rollbackTransaction()
            {
                rollbackTransaction(id);
            }
            public boolean checkpointTransaction()
            {
                return checkpointTransaction(id);
            }

            /* Database operation methods */
            public long insert(Object obj)
            {
                ...
            }
            public long count(Class cls)
            {
                return count(id, db.getClassDescriptor(cls).classNo);
            }
            public void removeAll(Class cls)
            {
                removeAll(id, db.getClassDescriptor(cls).classNo);
            }
            public boolean saveSnapshot(String databaseSnapshotFilePath)
            {
                return save(id, databaseSnapshotFilePath);
            }
            public boolean saveMetadata(String databaseMetadataFilePath, boolean saveDefaults)
            {
                return saveMetadata(id, databaseMetadataFilePath, saveDefaults);
            }
            public boolean saveDictionary(String databaseDictionaryFilePath)
            {
                return saveDictionary(id, databaseDictionaryFilePath);
            }
            public boolean saveClass(String filePath, Class cls)
            {
                return saveClass(id, filePath, db.getClassDescriptor(cls).classNo);
            }
            public boolean loadClass(String filePath, Class cls, boolean doMerge)
            {
                return loadClass(id, filePath, (cls != null) ? db.getClassDescriptor(cls).classNo : 0, doMerge);
            }
            public boolean loadClass(String filePath)
            {
                return loadClass(id, filePath, 0, false);
            }

            /* Event methods */
            public void waitEvent(String name)
            {
                waitEvent(id, db.findEvent(name));
            }
            public void releaseEvent(String name)
            {
                releaseEvent(id, db.findEvent(name));
            }
            public void releaseAllEvents()
            {
                releaseAllEvents(id);
            }

            /* Statistics methods */
            public int getFreePages()
            {
                return getFreePages(id);
            }
            public int getTotalPages()
            {
                return getTotalPages(id);
            }
            public short getDbPageSize()
            {
                return getDbPageSize(id);
            }
            public Statistic.ClassStat getClassStat(int classCode)
            {
                return getClassStat(id, classCode);
            }
            public short getIndexStatCount()
            {
                return getIndexStatCount(id);
            }
            public Statistic.IndexStat getIndexStat(short index)
            {
                ...
            }
            public Statistic.DiskInfo getDiskInfo()
            {
                return getDiskInfo(id);
            }

            /* Incremental Backup methods */
            public void createBackup(String fileName, String label, Database.BackupType type)
            {
                createBackup(id, fileName, label, type.ordinal(), 0, null);
            }
            public void createBackup(String fileName, String label, Database.BackupType type,
                            int compressionLevel, String cipher)
            {
                createBackup(id, fileName, label, type.ordinal(), compressionLevel, cipher);
            }
            public void restoreBackup(String fileName, String label)
            {
                restoreBackup(id, fileName, label, null);
            }
            public void restoreBackup(String fileName, String label, String cipher)
            {
                restoreBackup(id, fileName, label, cipher);
            }
            public Database.BackupInfo [] listBackup(String fileName)
            {
                return listBackup(id, fileName);
            }
        }

### Public Interface

Constructors
`public Connection(Database db)` | Constructor; parameters:
db | An opened Database
Returns: a Connection instance
`public Connection(Database db, byte[] context)` | Constructor; parameters:
db | An opened Database
context | A database context
Returns: a Connection instance
`protected Connection(Connection con)` | Constructor; parameters:
con | An existing Connection
Returns: a Connection instance
Close - disconnect
`public void disconnect()` | Close this connection
`public void close()` | Close this connection (Same as `disconnect()`)
Transaction control
`public void startTransaction(Database.TransactionType type)` | Start a database transaction; parameters:
type | A valid transaction type
(Note that nested transactions are supported.)
`public void startTransaction(Database.TransactionType type,` `Database.TransactionPriority pri, Database.IsolationLevel level)` | Start a database transaction; parameters:
type | A valid transaction type
pri | A valid transaction priority
level | A valid transaction isolation level
(Note that nested transactions are supported.)
`public boolean commitTransaction()` | Commit a database transaction Returns: `False` in case of an MVCC error; otherwise `True`
`public boolean commitTransaction(int phase)` | Commit phase 1 or 2 of a two-phase database transaction; parameters:
phase | A value of `1` or `2`
Returns: `False` in case of an MVCC error; otherwise `True`
`public void setCommitPolicy(Database.CommitPolicy policy)` | Set the transaction commit policy for this connection; parameters:
policy | A valid transaction commit policy
`public void diskFlush()` | Flush to the persistent storage all changes made by committed transactions. (This method can be used to flush changes when the `MCO_COMMIT_BUFFERED` transaction policy is used.)
`public void rollbackTransaction()` | Rollback a transaction. (Note that any nested transactions are aborted.)
`public boolean checkpointTransaction()` | Checkpoint the current transaction: insert all objects updated by the current transaction in indexes Returns: `False` in case of an MVCC error; otherwise `True`
Database operations
`public long insert(Object obj)` | Insert a new object into the database; parameters:
obj | An object of one of the classes enumerated in the Database.Parameters.classes list
Returns: the `AUTOID` of the created object if the `autoid` attribute is set in the `Persistent` annotation for this class, or `0` if class has not associated `AUTOID` index
`public long count(Class cls)` | Return the number of instances of this class stored in the database; parameters:
cls | The class for which the instances will be counted
`public void removeAll(Class cls)` | Remove all instances of the specified class. (Note that class inheritance is not considered.) Parameters:
cls | The class from which the instances will be removed
`public boolean saveSnapshot(String databaseSnapshotFilePath)` | Save a database snapshot to the specified file.( This snapshot can later be loaded by the Database method `open()` if the corresponding file path is specified in `Database.Parameters.databaseSnapshotFilePath` ; parameters:
`databaseSnapshotFilePath` | The path to the file where the snapshot will be saved
Returns: `True` if the snapshot file was successfully saved; `False` if the specified file cannot be opened
`public boolean saveMetadata(String databaseMetadataFilePath, boolean saveDefaults)` | Save a database metadata to the specified file. (This metadata can later be loaded as an xSQL configuration file); parameters:
`databaseMetadataFilePath` | The path to the file where the metadata will be saved (a file is always created or overwritten if it exists)
saveDefaults | If `true`, save default values
Returns: `True` if the metadata file was successfully saved; `False` if the specified file cannot be opened
`public boolean saveDictionary(String databaseDictionaryFilePath)` | Save a database dictionary to the specified file; parameters:
`databaseDictionaryFilePath` | The path to the file where the dictionary will be saved (a file is always created or overwritten if it exists)
Returns: `True` if the dictionary file was successfully saved; `False` if the specified file cannot be opened
`public boolean saveClass(String filePath, Class cls)` | Save table content to the specified file.This snapshot can later be loaded by the Database `open()` or Connection `loadClass()`; parameters:
`filePath` | The path to the file where the table content will be saved (a file is always created or overwritten if it exists)
cls | The class for which the contents will be saved
Returns: `True` if the file was successfully saved; `False` if the specified file cannot be opened
`public boolean loadClass(String filePath, Class cls, boolean doMerge)` | Load the table contents from the file previously created by Connection `saveClass()` or `saveSnapshot()`; parameters:
`filePath` | The path to the file from which the table content will be loaded
cls | The class for which the contents will be loaded
doMerge | If `False` the content of the table is cleared before loading from image file; if `True` the loaded objects are "added" to the table
Returns: `True` if the file was successfully loaded; `False` if the specified file cannot be opened
`public boolean loadClass(String filePath)` | Load the table contents from the file previously created by Connection `saveClass()` or `saveSnapshot()`using the class `id` of 0 and `doMerge` of `False`; parameters:
`filePath` | The path to the file from which the table content will be loaded
Returns: `True` if the file was successfully loaded; `False` if the specified file cannot be opened
Event Methods
`public void waitEvent(String name)` | Wait for signaling of the specified asynchronous event; parameters:
`name` | The event name
`public void releaseEvent(String name)` | Release the specified asynchronous event; parameters:
`name` | The event name
`public void releaseAllEvents()` | Release all asynchronous events
Statistics Methods
`public int getFreePages()` | Returns the total number of free pages
`public int getTotalPages()` | Returns the total number of available (originally allocated) pages
`public short getDbPageSize()` | Returns the current page size for this database connection
`public Statistic.ClassStat getClassStat(int classCode)` | Allows collecting of statistics on the database at runtime; parameters:
classCode | The class code of the class for which the statistics are desired
Returns: Statistics data for the class
`public short getIndexStatCount()` | Returns the number of indexes in the database. (Note that it must be called in the context of a read-only transaction and is often used in conjunction with `getIndexStat()` to obtain index statistics at runtime
`public Statistic.IndexStat getIndexStat(short index)` | Obtains index statistics at runtime; parameters:
index | The zero-based index number. (Note that the total count of indexes can be obtained by calling `getIndexStatCount()`
Returns: Index statistics data
`public Statistic.DiskInfo getDiskInfo()` | Returns information about the current state of the database and log file: the size of the log file in bytes, the size of the database file in bytes, and the amount of space that is actually used in the database file
Incremental Backup Methods
`public void createBackup(String fileName, String label, Database.BackupType type)` | Create a backup record of the database; parameters:
`fileName` | The name of the backup file where the backup record will be created
label | The backup's label
type | The type of backup record (see the C API page `mco_backup_create()` for details)
`public void createBackup(String fileName, String label, Database.BackupType type, int compressionLevel level, String cipher)` | Create a backup record of the database using compression and/or encryption; parameters:
`fileName` | The name of the backup file where the backup record will be created
label | The backup's label
type | The type of backup record (see the C API page `mco_backup_create()` for details)
level | An optional backup compression level 1 to 9; (1 indicates the fastest, but the lowest compression level)
cipher | An optional cipher to encrypt the backup
`public void restoreBackup(String fileName, String label)` | Restore backup records starting from the latest snapshot record in the specified file up to the specified label; parameters:
`fileName` | The name of the backup file where the backup record will be created
label | The backup's label
`public void restoreBackup(String fileName, String label, String cipher)` | Restore backup records starting from the latest snapshot record in the specified file up to the specified label using compression and/or encryption; parameters:
`fileName` | The name of the backup file to use for the restoration procedure
label | The backup's label to restore
cipher | An optional cipher to decrypt the backup
public Database.BackupInfo [] listBackup(String fileName) | List the contents of a backup file; parameters:
`fileName` | The name of the backup file to list