Interface ExtendedConnection
-
- All Superinterfaces:
AutoCloseable
,Connection
,Wrapper
- All Known Subinterfaces:
ManagedExtendedConnection
public interface ExtendedConnection extends Connection
An extension toConnection
in order to provide further functionality to assist in writing vendor-independent database accessing code. This additional functionality is provided by an implementation ofDBAccessProvider
.
-
-
Field Summary
Fields Modifier and Type Field Description static int
DEFAULT_MAX_IN_OPERATOR_PARAMETER_COUNT
the default value forgetMaxInOperatorParameterCount()
static int
DEFAULT_MAX_PARAMETER_COUNT
the default value forgetMaxParameterCount()
static int
DEFAULT_MAX_STATEMENT_LENGTH
the default value forgetMaxStatementLength()
-
Fields inherited from interface java.sql.Connection
TRANSACTION_NONE, TRANSACTION_READ_COMMITTED, TRANSACTION_READ_UNCOMMITTED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE
-
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description void
addColumn(String tableName, String columnName, String correspondingDbType)
Adds an additional column to the designated table of the designated type.boolean
columnExists(String columnName, String tableName)
Returns whether the column with the provided name exists in the provided table.String
createRecursionTable(String[] selectAttributes, String[] rootAttributes, String tableName, String startCondition, ParentToChildConnection[] parentToChildConnections)
LikecreateRecursionTable(String[], String, String, ParentToChildConnection[], int)
but without a maximum depth.String
createRecursionTable(String[] selectAttributes, String tableName, String startCondition, ParentToChildConnection[] parentToChildConnections, int maxDepth)
Creates a (temporary) table or view containing tuples that match a recursive/hierarchical SQL-query which is based on the specified parameters.void
createSequence(String sequenceName, long start, long increment)
Creates a new sequence in the database.void
deregisterIterator()
Deregisters an iterator for thisExtendedConnection
which allows this connection to be reclaimed again in case it is not used any more.void
dropAllRecursionTables()
All tables that have been created viacreateRecursionTable(String[], String, String, String[], int)
are dropped.void
dropColumn(String tableName, String columnName)
Drops the specified column from the table which corresponds to anALTER TABLE DROP COLUMN
statement.void
dropRecursionTable(String tableName)
The specified table that has been created viacreateRecursionTable(String[], String, String, String[], int)
is dropped.void
dropSchemaVersion(String serviceName)
void
dropSequence(String sequenceName)
Drop the sequence with the given name.String
formatValue(Object value, int typeCode)
Formats the given value to a string that can be used in SQL statements and queries.String
getAddForeignKey(de.aristaflow.adept2.base.dbaccess.model.ForeignKey fk, boolean quoteIdentifiers)
Gets an SQL string forALTER TABLE
which adds the designated foreign key.Collection<String>
getAllTableNames()
Returns a collection of the names of all existing tables in the database.String[]
getColumnNames(String tableName)
Gets all column names of a specific table.int
getColumnType(String columnName, String tableName)
Gets the type of a specific column asjava.sql.Types
.String
getCorrespondingDBType(int jdbcTypeCode)
Converts the given JDBC type code and given size constraints into a vendor specific SQL type.String
getCorrespondingDBType(int jdbcTypeCode, int size)
Converts the given JDBC type code and given size constraints into a vendor specific SQL type.String
getCorrespondingDBType(int jdbcTypeCode, int size, int scale)
Converts the given JDBC type code and given size constraints into a vendor specific SQL type.Timestamp
getCurrentTime()
Gets the current time (as timestamp) from the underlying DBMS in UTC timezone.DatabaseName
getDatabaseName()
Gets the name of the underlying database.String
getDropForeignKeyConstraintKeyword()
To drop a foreign key constraint from table columns, there are two syntaxes available.String
getEXCEPTKeyword()
Gets the keyword that is interpreted as EXCEPT by the underlying database-management-system.int
getMaxInOperatorParameterCount()
Return the maximum number of parameters within the IN-operator.int
getMaxParameterCount()
Returns the maximum number of parameters in prepared statements.int
getMaxStatementLength()
Returns the maximum length for SQL statements.String
getNextIdString(String seqName)
Gets the string for usage as column in SELECT retrieving the next ID from the designated sequence.int
getSchemaVersion(String serviceName)
Returns the version number associated with the current database structure of the given service name.String
getStringComparison(String tableName, String columnName, String tableAlias, int type, int length, boolean equal)
Gets a string to be used in a WHERE-clause for comparing the designated column with another string.String
getTimeDifference(String column, long seconds)
Gets the string representing the timestamp value (to be calculated within the DBMS) based on the designated column having the designated difference (in seconds).boolean
isForeignKeyViolation(SQLException ex)
Returns true if the given exception was caused by a FOREIGN KEY constraint.boolean
isLockTimeout(SQLException ex)
Gets whether the designated exception indicates a lock timeout, e. g. while waiting for atable lock
.boolean
isSyntaxError(SQLException ex)
Gets whether the designated exception indicates syntax error.boolean
isTableMissing(SQLException ex)
Returns true if the given exception was caused by a missing table.boolean
isUniqueViolation(SQLException ex)
Returns true if the given exception was caused by a UNIQUE constraint.void
lockTable(String tableName, long timeout)
Locks the designated table exclusively until the end of the corresponding transaction.long
nextID(String sequenceName)
Returns the next ID from the sequence with the given name.de.aristaflow.adept2.base.dbaccess.ExtendedCallableStatement
prepareCall(String sql)
de.aristaflow.adept2.base.dbaccess.ExtendedCallableStatement
prepareCall(String sql, int resultSetType, int resultSetConcurrency)
de.aristaflow.adept2.base.dbaccess.ExtendedCallableStatement
prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement
prepareStatement(String sql)
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement
prepareStatement(String sql, int autoGeneratedKeys)
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement
prepareStatement(String sql, int[] columnIndexes)
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement
prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement
prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability)
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement
prepareStatement(String sql, String[] columnNames)
void
registerIterator()
Registers an iterator for thisExtendedConnection
which prevents this connection from being reclaimed in case it is pooled.void
renameColumn(String tableName, String oldColumnName, String newColumnName)
Renames the designated column from the table which corresponds to anALTER TABLE RENAME COLUMN
statement.void
renameTable(String oldName, String newName)
Renames the designated table using the designated new name.boolean
sequenceExists(String sequenceName)
Returns whether a sequence with the given name exists.void
setDefaultLockTimeout()
Sets the default value for the lock timeout for this connection.long
setLockTimeout(long timeout)
Sets the lock timeout for the current transaction in this connection to the designated timeout (in milliseconds) and returns the current lock timeout.void
setSchemaVersion(String serviceName, int version)
Sets the version number associated with the current database structure of the given service name.boolean
supportsIntersect()
Gets whether the underlying DBMS supports intersect.boolean
supportsSqlXml()
Gets whether the underlying DBMS supports the data typeTypes.SQLXML
.boolean
tableExists(String tableName)
Returns whether the table (or the view) with the provided name exists in the database.String
toUpperCase(String s)
Gets the designated string converted to upper case as suggested by the underlying database-management system.void
updateColumnDefault(String tableName, String columnName, Object defaultValue)
Sets the designated value as default value for the designated column.void
updateColumnsNullable(String tableName, boolean nullable, String... columns)
Sets the designated columns of the designated table nullable (not nullable).void
updateColumnsType(Map<String,Collection<String>> columns, String correspondingDbType)
Sets the type of the designated columns of the designated tables to the provided one.void
updateColumnType(String tableName, String columnName, String correspondingDbType)
Sets the type of the designated column of the designated table to the provided one.String
useLockTimeout(String query, long timeout)
Appends the designated lock timeout in milliseconds to the designated query (DDL and DML are not supported!).-
Methods inherited from interface java.sql.Connection
abort, beginRequest, clearWarnings, close, commit, createArrayOf, createBlob, createClob, createNClob, createSQLXML, createStatement, createStatement, createStatement, createStruct, endRequest, getAutoCommit, getCatalog, getClientInfo, getClientInfo, getHoldability, getMetaData, getNetworkTimeout, getSchema, getTransactionIsolation, getTypeMap, getWarnings, isClosed, isReadOnly, isValid, nativeSQL, releaseSavepoint, rollback, rollback, setAutoCommit, setCatalog, setClientInfo, setClientInfo, setHoldability, setNetworkTimeout, setReadOnly, setSavepoint, setSavepoint, setSchema, setShardingKey, setShardingKey, setShardingKeyIfValid, setShardingKeyIfValid, setTransactionIsolation, setTypeMap
-
Methods inherited from interface java.sql.Wrapper
isWrapperFor, unwrap
-
-
-
-
Field Detail
-
DEFAULT_MAX_STATEMENT_LENGTH
static final int DEFAULT_MAX_STATEMENT_LENGTH
the default value forgetMaxStatementLength()
- See Also:
- Constant Field Values
-
DEFAULT_MAX_PARAMETER_COUNT
static final int DEFAULT_MAX_PARAMETER_COUNT
the default value forgetMaxParameterCount()
- See Also:
- Constant Field Values
-
DEFAULT_MAX_IN_OPERATOR_PARAMETER_COUNT
static final int DEFAULT_MAX_IN_OPERATOR_PARAMETER_COUNT
the default value forgetMaxInOperatorParameterCount()
- See Also:
- Constant Field Values
-
-
Method Detail
-
prepareStatement
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
- Specified by:
prepareStatement
in interfaceConnection
- Throws:
SQLException
-
prepareCall
de.aristaflow.adept2.base.dbaccess.ExtendedCallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
- Specified by:
prepareCall
in interfaceConnection
- Throws:
SQLException
-
prepareStatement
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement prepareStatement(String sql) throws SQLException
- Specified by:
prepareStatement
in interfaceConnection
- Throws:
SQLException
-
prepareCall
de.aristaflow.adept2.base.dbaccess.ExtendedCallableStatement prepareCall(String sql) throws SQLException
- Specified by:
prepareCall
in interfaceConnection
- Throws:
SQLException
-
prepareStatement
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
- Specified by:
prepareStatement
in interfaceConnection
- Throws:
SQLException
-
prepareCall
de.aristaflow.adept2.base.dbaccess.ExtendedCallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
- Specified by:
prepareCall
in interfaceConnection
- Throws:
SQLException
-
prepareStatement
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
- Specified by:
prepareStatement
in interfaceConnection
- Throws:
SQLException
-
prepareStatement
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
- Specified by:
prepareStatement
in interfaceConnection
- Throws:
SQLException
-
prepareStatement
de.aristaflow.adept2.base.dbaccess.ExtendedPreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
- Specified by:
prepareStatement
in interfaceConnection
- Throws:
SQLException
-
getDatabaseName
DatabaseName getDatabaseName()
Gets the name of the underlying database. This avoids the need to parse the product name from the metadata which is rather arbitrary.- Returns:
- The name of the underlying database.
-
getEXCEPTKeyword
String getEXCEPTKeyword()
Gets the keyword that is interpreted as EXCEPT by the underlying database-management-system. This method is necessary since the systems of some vendors do not understand the SQL-keyword EXCEPT. For an SQL-compliant database-management-system this method returns "EXCEPT".- Returns:
- The string representing the keyword which is identical to EXCEPT in the underlying database-management-system.
-
toUpperCase
String toUpperCase(String s)
Gets the designated string converted to upper case as suggested by the underlying database-management system. If a locale is required,Locale.ENGLISH
will be used.
Implementations do not need to ask the DBMS but may create the upper case with best effort.- Parameters:
s
- The string which to convert to upper case.- Returns:
- The designated string converted to upper case corresponding to the conversion rules of the underlying database-management system.
-
supportsIntersect
boolean supportsIntersect()
Gets whether the underlying DBMS supports intersect. Some DBMS do not support this so callers have to handle this differently, e. g. by using an appropriate WHERE-clause.- Returns:
- Whether the underlying DBMS supports intersect.
-
supportsSqlXml
boolean supportsSqlXml()
Gets whether the underlying DBMS supports the data typeTypes.SQLXML
. Some DBMS do not support this so callers have to useTypes.CLOB
instead.- Returns:
- Whether the underlying DBMS supports
Types.SQLXML
.
-
getStringComparison
String getStringComparison(String tableName, String columnName, String tableAlias, int type, int length, boolean equal)
Gets a string to be used in a WHERE-clause for comparing the designated column with another string. Use the returned string in a prepared statement or replace the?
with the real content of the string.
Provide the JDBC data type of the column to prevent accessing the meta data, which is a rather complex operation. UsegetColumnType(String, String)
to determine it once and reuse it. Depending on the data type, the comparison is determined. For instance, most DBMS do not allow to compareCLOB
.Do not rely on the data type specified when creating the designated column! For instance long character columns may be
CLOB
instead of the data type provided when creating the column.Make sure that the provided string to compare is never
null
! Whilenull
in the designated column will be handled appropriately, providing anull
string will usually not work.- Parameters:
tableName
- The name of the table which contains the column.columnName
- The name of column which to compare.tableAlias
- The table alias to be used as prefix of the column in the statement. Do not provide the separating.
as this will be added appropriately by the method. Ifnull
is provided, the column name will have no prefix.type
- The JDBC data type of the designated column. UsegetColumnType(String, String)
for determining it.length
- The length of the string. When reusing the prepared statement for several strings, use the longest one. This allows the underlying database to cast toVARCHAR
for comparing.equal
- Whether to compare the strings for whether they are equal (or whether they are not).- Returns:
- The string to be used in the WHERE-clause of a prepared statement for comparing the designated column with a string.
-
getTimeDifference
String getTimeDifference(String column, long seconds)
Gets the string representing the timestamp value (to be calculated within the DBMS) based on the designated column having the designated difference (in seconds). Note that the designated column may need to be fully qualified. It may also be a pseudo-column likeCURRENT_TIMESTAMP
.
When using this, make sure the referenced column has been set by the database. If not, you may have the wrong timezone and therefore get the wrong results. For instance if the value of a time/date column has been set by the BPM platform, this will usually be UTC time. Then you must not useCURRENT_TIMESTAMP
to compare with that column.As stated before, the time difference includes a timezone and also daylight saving time. For instance, if you are on the day before daylight saving time with a daylight saving time of 1 h, and you want to add 24 hours (86400 seconds), the database will not add the complete 24 hours but only 23 hours. That is, it reduces the amount by the daylight saving time difference. So you will get the very same local time on the next day which is not the complete time difference.
- Parameters:
column
- The (fully-qualified) name of the column which contains the time/date/timestamp. This may also be a pseudo-column.seconds
- The difference in seconds (!!) which to add or remove from the time in the designated column.- Returns:
- A string to be inserted into a query specifying the designated time difference with respect to the designated column.
-
getDropForeignKeyConstraintKeyword
String getDropForeignKeyConstraintKeyword()
To drop a foreign key constraint from table columns, there are two syntaxes available. Each DBMS supports at least one of them, but none is supported by all:ALTER TABLE <tableName> DROP <b>CONSTRAINT</b> <constraintName>
ALTER TABLE <tableName> DROP <b>FOREIGN KEY</b> <constraintName>
- Returns:
CONSTRAINT
orFOREIGN KEY
, whichever is appropriate for the DBMS
-
getAddForeignKey
String getAddForeignKey(de.aristaflow.adept2.base.dbaccess.model.ForeignKey fk, boolean quoteIdentifiers) throws SQLException
Gets an SQL string forALTER TABLE
which adds the designated foreign key.- Parameters:
fk
- The definition of the foreign key to be added.quoteIdentifiers
- Whether identifiers should be quoted.- Returns:
- The SQL string for the
ALTER TABLE
statement for adding the designated foreign key. - Throws:
SQLException
- If there are problems retrieving the required meta data or the foreign key cannot be created, anSQLException
will be thrown.
-
getCorrespondingDBType
String getCorrespondingDBType(int jdbcTypeCode)
Converts the given JDBC type code and given size constraints into a vendor specific SQL type.A call to this method is equivalent to
getCorrespondingDBType(jdbcTypeCode, -1, -1)
. SeegetCorrespondingDBType(int, int, int)
.- Parameters:
jdbcTypeCode
- the JDBC type code that should be mapped to a vendor specific SQL type string- Returns:
- the best effort mapping of the JDBC type to a vendor specific type
-
getCorrespondingDBType
String getCorrespondingDBType(int jdbcTypeCode, int size)
Converts the given JDBC type code and given size constraints into a vendor specific SQL type.A call to this method is equivalent to
getCorrespondingDBType(jdbcTypeCode, size, -1)
. SeegetCorrespondingDBType(int, int, int)
.- Parameters:
jdbcTypeCode
- the JDBC type code that should be mapped to a vendor specific SQL type stringsize
- the desired size of the type (i.e. length for string and binary types, precision for number types or fractional seconds for time types); use negative value to indicate that size is not used- Returns:
- the best effort mapping of the JDBC type to a vendor specific type
-
getCorrespondingDBType
String getCorrespondingDBType(int jdbcTypeCode, int size, int scale)
Converts the given JDBC type code and given size constraints into a vendor specific SQL type. The matching isn't and can't be guaranteed to be exact but is performed on a best effort basis. If e.g. CHAR(300) is requested but the DB only supports a length of up to 254, a VARCHAR(300) might be returned if VARCHAR supports greater lengths.Please be aware that binary or character types may be mapped to their LOB variants if the specified size doesn't allow the smaller types. This might however lead to problems when setting or getting the values in the regular way. E.g.
ResultSet.getString(int)
might not always work for CLOBs or only up to a certain size.Character types will be translated to Unicode-capable data types if available. Generally, the following types are supported. Implementations are allowed to also support the remaining JDBC types but the requirements for those aren't very clear. E.g. are size and scale enough for them as parameters? Negative values for size and scale indicate that they are not specified.
- BOOLEAN: 1 bit
- BIT: 1 bit
- TINYINT: 1 byte
- SMALLINT: 2 bytes
- INTEGER: 4 bytes
- BIGINT: 8 bytes
- REAL: 24 bits for mantissa
- DOUBLE: 54 bits for mantissa
- FLOAT(precision): precision of mantissa is in bits (1 <= precision <= 53)
- DECIMAL(precision, scale): precision and scale are in digits
- NUMERIC(precision, scale): is used synonymously for DECIMAL
- CHAR(length): length is mandatory
- VARCHAR(length): length is mandatory
- LONGVARCHAR(length): length is optional; most DBs apparently don't support length here, so it's mainly used by DBAccess as an indicator in order to map to CLOB if size constraints make it necessary
- CLOB(length): length is optional and usually not considered by implementations if the underlying DB doesn't support it
- BINARY(length): length is mandatory
- VARBINARY(length): length is mandatory
- LONGVARBINARY(length): length is optional; most DBs apparently don't support length here, so it's mainly used by DBAccess as an indicator in order to map to BLOB if size constraints make it necessary; DBs that do support a length will use their default (e.g. the maximum) when no explicit length is specified
- BLOB(length): length is optional; very few databases support it and usually not considered by implementations if the underlying DB doesn't support it
- DATE
- TIME(fractional seconds): fractional seconds is in digits and optional; max precision or support at all is not guaranteed, but usually between 0 and 9; if not set an implementation default is used
- TIMESTAMP(fractional seconds): fractional seconds is in digits and optional; max precision or support at all is not guaranteed, but usually between 0 and 9; if not set an implementation default is used
TODO: Add support for size in CLOB and BLOB?
- Parameters:
jdbcTypeCode
- the JDBC type code that should be mapped to a vendor specific SQL type stringsize
- the desired size of the type (i.e. length for string and binary types, precision for number types or fractional seconds for time types); use negative value to indicate that size is not usedscale
- only used for some number types and determines the precision after the decimal point; use negative value to indicate that scale is not used- Returns:
- the best effort mapping of the JDBC type to a vendor specific type
or
null
if the type is not supported - Throws:
IllegalArgumentException
- if the combination of JDBC type code, size and scale is illegal, e.g. if scale or size is set forTypes.INTEGER
-
formatValue
String formatValue(Object value, int typeCode)
Formats the given value to a string that can be used in SQL statements and queries. The given JDBC type code (seeTypes
) determines the target type. The main intention for this method is to be an alternative where it is not easily possible to usePreparedStatement
s, e.g. in highly dynamic and complex queries.Please be aware that string escaping may not have been implemented in a 100% safe way due to lacking specifications for each database. So for strings it's much safer to use
PreparedStatements
to prevent any kind of SQL injection.This method may throw a runtime exception if object type of the value and type code don't fit together. However it does NOT guarantee to do so, which may result in improperly formatted or even illegal values.
For all date-related types (i.e. DATE, TIME and TIMESTAMP) not only
Date
is allowed, but alsoDate
,Time
andTimestamp
.A null value will result in the string "
null
".Booleans are properly formatted to
1
or0
if the target type isTypes.BIT
.- Parameters:
value
- the value to formattypeCode
- the JDBC type code of the target type- Returns:
- the value formatted according to the given type code
-
tableExists
boolean tableExists(String tableName) throws SQLException
Returns whether the table (or the view) with the provided name exists in the database.- Parameters:
tableName
- The name of the table (or the view) to look for.- Returns:
true
if the table exists in the database, otherwisefalse
.- Throws:
SQLException
- If a database access error occurs, aSQLException
will be thrown.
-
renameTable
void renameTable(String oldName, String newName) throws SQLException
Renames the designated table using the designated new name. This may drop the foreign key constraints intermediately.- Parameters:
oldName
- The name of the table which to rename.newName
- The new name of the table.- Throws:
SQLException
- If a database access error occurs, the specified table name is invalid, aSQLException
will be thrown.
-
getAllTableNames
Collection<String> getAllTableNames() throws SQLException
Returns a collection of the names of all existing tables in the database. The names will be returned as they are stored in the database. If no table exists, this collection would be empty.- Returns:
- A collection of all table names.
- Throws:
SQLException
- If a database access error occurs, aSQLException
will be thrown.
-
columnExists
boolean columnExists(String columnName, String tableName) throws SQLException
Returns whether the column with the provided name exists in the provided table.- Parameters:
columnName
- The name of the column to look for.tableName
- The name of the table in which to look for the column.- Returns:
true
if the column exists in the table, otherwisefalse
.- Throws:
SQLException
- If a database access error occurs or the specified table name is invalid, aSQLException
will be thrown.
-
addColumn
void addColumn(String tableName, String columnName, String correspondingDbType) throws SQLException
Adds an additional column to the designated table of the designated type. UsegetCorrespondingDBType(int)
or one of the overloaded methods to determine the database-specific type of the column.
The new column will be nullable. If this is not the desired behaviour, add values for all entries andupdate
the column afterwards.- Parameters:
tableName
- The name of the table to which to add a new column.columnName
- The name of column which to add.correspondingDbType
- The string representation of the desired type of the column. Use the string returned bygetCorrespondingDBType(int)
(or the overloaded methods).- Throws:
SQLException
- If a database access error occurs, the specified table name or column name is invalid, aSQLException
will be thrown.
-
updateColumnType
void updateColumnType(String tableName, String columnName, String correspondingDbType) throws SQLException
Sets the type of the designated column of the designated table to the provided one. UsegetCorrespondingDBType(int)
or one of the overloaded methods to determine the database-specific type of the column.Note that not all DBMS support shortening the type of a column, for instance Derby. This requires creating a new column, copying the data, dropping the old column and renaming the new one. Do not forget to handle indexes and key columns appropriately if required.
- Parameters:
tableName
- The table containing the column to change the data type.columnName
- The name of the column to change the data type.correspondingDbType
- The string representation of the desired type of the column. Use the string returned bygetCorrespondingDBType(int)
(or the overloaded methods).- Throws:
SQLException
- If a database access error occurs, the specified table name or column name is invalid, aSQLException
will be thrown.
-
updateColumnsType
void updateColumnsType(Map<String,Collection<String>> columns, String correspondingDbType) throws SQLException
Sets the type of the designated columns of the designated tables to the provided one. UsegetCorrespondingDBType(int)
or one of the overloaded methods to determine the database-specific type for all columns.Note that not all DBMS support shortening the type of a column, for instance Derby. This requires creating a new column, copying the data, dropping the old column and renaming the new one. Do not forget to handle indexes and key columns appropriately if required.
This is similar to
updateColumnType(String, String, String)
but allows to updates several columns of different tables at the same type. This is useful for DBMS which have a lot of overhead to change one column, e. g. temporarily remove column constraints, indexes and foreign keys of a changed column. When changing the type of a column referenced by a foreign key, the type of the referencing column also has to be changed.- Parameters:
columns
- The table names mapped to the names of the corresponding columns of which to change the data type.correspondingDbType
- The string representation of the desired type of the columns. Use the string returned bygetCorrespondingDBType(int)
(or the overloaded methods).- Throws:
SQLException
- If a database access error occurs, the specified table or column names are invalid, aSQLException
will be thrown.
-
updateColumnsNullable
void updateColumnsNullable(String tableName, boolean nullable, String... columns) throws SQLException
Sets the designated columns of the designated table nullable (not nullable). If the columns are already nullable (not nullable), no change will be made.
Note that only columns being not part of a key can be nullable. Vice versa only columns having no null value can be set to not nullable. Not respecting this will lead to anSQLException
.- Parameters:
tableName
- The table containing the columns to change the nullable-state.nullable
- Whether the columns should allow null values or not.columns
- The names of the columns to change the nullable-state.- Throws:
SQLException
- If there are problems checking the metadata or changing the nullable-state, anSQLException
will be thrown.
-
updateColumnDefault
void updateColumnDefault(String tableName, String columnName, Object defaultValue) throws SQLException
Sets the designated value as default value for the designated column.
Providingnull
as default value removes the default value.- Parameters:
tableName
- The table containing the column to change the default value.columnName
- The name of the column to change the default value.defaultValue
- The value which to set as default. This will formatted appropriately.- Throws:
SQLException
- If there are problems retrieving the metadata (if required) or changing the default value, anSQLException
will be thrown.
-
renameColumn
void renameColumn(String tableName, String oldColumnName, String newColumnName) throws SQLException
Renames the designated column from the table which corresponds to anALTER TABLE RENAME COLUMN
statement.- Parameters:
tableName
- The name of the table to which to rename a column.oldColumnName
- The old name of column which to rename.newColumnName
- The new name of the column.- Throws:
SQLException
- If a database access error occurs, the specified table name or column name is invalid, aSQLException
will be thrown.
-
dropColumn
void dropColumn(String tableName, String columnName) throws SQLException
Drops the specified column from the table which corresponds to anALTER TABLE DROP COLUMN
statement.Do not try to drop columns that are referenced in any (primary key, foreign key, unique, ...) constraints. This may have unpredictable results or even fail (in a data-destroying way).
- Parameters:
tableName
- The name of the table of which the column type is of interest.columnName
- The name of column of which the type is of interest.- Throws:
SQLException
- If a database access error occurs, the specified table name or column name is invalid, aSQLException
will be thrown.
-
getColumnNames
String[] getColumnNames(String tableName) throws SQLException
Gets all column names of a specific table.- Parameters:
tableName
- The name of the table of which the column names are of interest.- Returns:
- returns An array of strings with the names of the columns of the specified table.
- Throws:
SQLException
- If a database access error occurs or the specified table name is invalid, aSQLException
will be thrown.
-
getColumnType
int getColumnType(String columnName, String tableName) throws SQLException
Gets the type of a specific column asjava.sql.Types
.- Parameters:
tableName
- The name of the table of which the column type is of interest.columnName
- The name of column of which the type is of interest.- Returns:
- The SQL-type of the specified column as defined in
java.sql.Types
. - Throws:
SQLException
- If a database access error occurs or the specified table name or column name is invalid, aSQLException
will be thrown.- See Also:
Types
-
getMaxStatementLength
int getMaxStatementLength()
Returns the maximum length for SQL statements. This limit is not enforced, but should be respected when dynamically creating statements. This limit however should only be relevant for unusually long statements.- Returns:
- the maximum length for SQL statements
-
getMaxParameterCount
int getMaxParameterCount()
Returns the maximum number of parameters in prepared statements. This limit is not enforced, but should be respected when dynamically creating statements.- Returns:
- the maximum number of parameters in prepared statements
-
getMaxInOperatorParameterCount
int getMaxInOperatorParameterCount()
Return the maximum number of parameters within the IN-operator. This limit is not enforced, but should be respected when dynamically creating statements.- Returns:
- the maximum number of parameters within the IN-operator
-
isTableMissing
boolean isTableMissing(SQLException ex)
Returns true if the given exception was caused by a missing table.- Parameters:
ex
- the exception to be tested- Returns:
- true if the given exception was caused by a missing table
-
isUniqueViolation
boolean isUniqueViolation(SQLException ex)
Returns true if the given exception was caused by a UNIQUE constraint.- Parameters:
ex
- the exception to be tested- Returns:
- true if the given exception was caused by a UNIQUE constraint
-
isForeignKeyViolation
boolean isForeignKeyViolation(SQLException ex)
Returns true if the given exception was caused by a FOREIGN KEY constraint.- Parameters:
ex
- the exception to be tested- Returns:
- true if the given exception was caused by a FOREIGN KEY constraint
-
isLockTimeout
boolean isLockTimeout(SQLException ex)
Gets whether the designated exception indicates a lock timeout, e. g. while waiting for atable lock
.- Parameters:
ex
- The exception to be tested- Returns:
- Whether the designated exception was caused by a lock timeout.
-
isSyntaxError
boolean isSyntaxError(SQLException ex)
Gets whether the designated exception indicates syntax error.- Parameters:
ex
- The exception to be tested- Returns:
- Whether the designated exception was caused by a syntax error.
-
getCurrentTime
Timestamp getCurrentTime() throws SQLException
Gets the current time (as timestamp) from the underlying DBMS in UTC timezone. This may differ from the time provided by the current JVM and allows for using the same time across several nodes.- Returns:
- The current time (as timestamp) in UTC timezone from the underlying DBMS.
- Throws:
SQLException
- If there are problems retrieving the current time, anSQLException
will be thrown.
-
createSequence
void createSequence(String sequenceName, long start, long increment) throws SQLException
Creates a new sequence in the database. A sequence is a thread-safe way to generate IDs.- Parameters:
sequenceName
- the name of the sequence to be createdstart
- the initial value of the sequence, i.e. the first value that will be returned bynextID(String)
; may be negativeincrement
- the value by which to increment the ID after a call tonextID(String)
; may be negative- Throws:
SQLException
- if a database access error occurs
-
dropSequence
void dropSequence(String sequenceName) throws SQLException
Drop the sequence with the given name.- Parameters:
sequenceName
- the name of the sequence to be dropped- Throws:
SQLException
- if a database access error occurs or the specified sequence doesn't exist
-
sequenceExists
boolean sequenceExists(String sequenceName) throws SQLException
Returns whether a sequence with the given name exists.- Parameters:
sequenceName
- the sequence to be tested- Returns:
- whether a sequence with the given name exists
- Throws:
SQLException
- if a database access error occurs
-
nextID
long nextID(String sequenceName) throws SQLException
Returns the next ID from the sequence with the given name.- Parameters:
sequenceName
- the sequence from which to return the next ID- Returns:
- the next ID from the given sequence
- Throws:
SQLException
- if a database access error occurs
-
getNextIdString
String getNextIdString(String seqName) throws SQLException
Gets the string for usage as column in SELECT retrieving the next ID from the designated sequence.- Parameters:
seqName
- The name of the sequence from which to get (the string retrieving) the next ID.- Returns:
- The string retrieving the next ID from the sequence with the designated name.
- Throws:
SQLException
- If there are problems retrieving the string for the next ID from the designated sequence, anSQLException
will be thrown.
-
lockTable
void lockTable(String tableName, long timeout) throws SQLException, TimeoutException
Locks the designated table exclusively until the end of the corresponding transaction. The calling thread will wait for the designated amount of seconds for the lock.
While the wait time is provided in milliseconds, not all databases support this but only full seconds. In such a case if the value is not a full second, the next greater integer value will be used.This connection needs to have auto-commit disabled. The table lock is held until the end of the transaction! So be sure to not hold any other locks and usually use a separate transaction for locking the table unless modifying the very same table.
- Parameters:
tableName
- The name of the table which to lock. This table has to exist.timeout
- The wait time in milliseconds. Use 0 to not wait at all (just try to lock) or a negative value to wait forever.- Throws:
SQLException
- If there are problems locking the designated table, anSQLException
will be thrown.TimeoutException
- If the designated timeout elapsed before the lock can be acquired, aTimeoutException
will be thrown.
-
useLockTimeout
String useLockTimeout(String query, long timeout) throws SQLException
Appends the designated lock timeout in milliseconds to the designated query (DDL and DML are not supported!). This may also be aNOWAIT
as well as waiting forever.
While the wait time is provided in milliseconds, not all databases support this but only full seconds. In such a case if the value is not a full second, the next greater integer value will be used.Note that not all DBMS support a lock timeout for each query separately. These will return the designated query unchanged. In this case you need to set the lock timeout for the transaction temporarily using
setLockTimeout(long)
.DBMS not supporting a lock timeout will also return the designated query unchanged.
- Parameters:
query
- The query which should use a specific lock timeout.timeout
- The lock timeout in milliseconds. Use 0 to not wait at all, use -1 to wait forever.- Returns:
- The query with the corresponding lock timeout appended.
- Throws:
SQLException
- If there are problems appending the lock timeout, e.g. when accessing the meta data of the designated connection, anSQLException
will be thrown.
-
setLockTimeout
long setLockTimeout(long timeout) throws SQLException
Sets the lock timeout for the current transaction in this connection to the designated timeout (in milliseconds) and returns the current lock timeout. The lock timeout applies until the end of the active transaction. So make sure to reset it if no longer needed in afinally
.
While the wait time is provided in milliseconds, not all databases support this but only full seconds. In such a case if the value is not a full second, the next greater integer value will be used. However, the return value will be the appropriate amount of milliseconds.Note that not all DBMS support a lock timeout for a transaction but require the lock timeout for each query separately. So you need to
setLockTimeout(long)
as well asuseLockTimeout(String, long)
.Note that not all DBMS support a dynamic lock timeout. These will throw an
UnsupportedOperationException
.- Parameters:
timeout
- The lock timeout in milliseconds. Use 0 to not wait at all, use -1 to wait forever.- Returns:
- The timeout before changing it.
- Throws:
SQLException
- If there are problems setting the lock timeout, anSQLException
will be thrown.
-
setDefaultLockTimeout
void setDefaultLockTimeout() throws SQLException
Sets the default value for the lock timeout for this connection. This is required to reset pooled connections.- Throws:
SQLException
- If there are problems setting the lock timeout, anSQLException
will be thrown.
-
getSchemaVersion
int getSchemaVersion(String serviceName) throws SQLException
Returns the version number associated with the current database structure of the given service name. This allows services to automatically perform appropriate updates to tables and columns.- Parameters:
serviceName
- the service name (e.g. thesimple name
of the main interface)- Returns:
- The version number of the designated service or -1 there if the service has no version.
- Throws:
SQLException
-
setSchemaVersion
void setSchemaVersion(String serviceName, int version) throws SQLException
Sets the version number associated with the current database structure of the given service name.- Parameters:
serviceName
- the service name (e.g. thesimple name
of the main interface)version
- the new version- Throws:
SQLException
-
dropSchemaVersion
void dropSchemaVersion(String serviceName) throws SQLException
- Throws:
SQLException
-
createRecursionTable
String createRecursionTable(String[] selectAttributes, String tableName, String startCondition, ParentToChildConnection[] parentToChildConnections, int maxDepth) throws SQLException
Creates a (temporary) table or view containing tuples that match a recursive/hierarchical SQL-query which is based on the specified parameters. This method is necessary since recursive queries are completely different or even non-existing in some database-management-systems. If no recursion exists (for example in Derby), it will have to be implemented directly in Java.Therefore not all features are supported. The main restriction are the SELECT-attributes. They are always from the current recursion step which means a tuple always contains only values from the child tables. There are no tuples containing (joined) parent and child attributes. Further aggregation is not supported. This can be achieved by grouping all resulting tuples by their level.
Following are examples for translations of the method parameters to DB2- and Oracle-syntax. in DB2:
CREATE TABLE return AS WITH RecRel(Depth, selectAttributes[]) AS (SELECT 1, selectAttributes[] FROM tableName WHERE startCondition UNION ALL SELECT Parent.Depth + 1, Child.selectAttributes[] FROM RecRel AS Parent, tableName AS Child WHERE Parent.parentToChildConnection[0].getParentAttribute() parentToChildConnection[0].getOperator() Child.parentToChildConnection[0].getChildAttribute() AND Parent.parentToChildConnection[1].getParentAttribute() parentToChildConnection[1].getOperator() Child.parentToChildConnection[1].getChildAttribute() AND ... AND Parent.Depth < maxDepth ) SELECT * FROM RecRel
in Oracle:CREATE TABLE return AS SELECT Depth, selectAttributes[] FROM tableName START WITH startCondition CONNECT BY PRIOR parentToChildConnection[0] AND PRIOR parentToChildConnection[1] AND ... AND Depth <= maxDepth
- Parameters:
selectAttributes
- Array of the names of the columns to be in the created recursion table. The names have to be valid column names of the specified table.tableName
- The name of the table which contains the hierarchical data. If the hierarchical data spans several tables, a new temporary table will have to be created by joining these tables. Thus the name of the temporary table is to be used as parameter.startCondition
- A string forming a valid WHERE-condition which specifies the conditions which have to hold for the top-level tuples respectively the tuples for the start of the recursion. The string may be any valid WHERE-condition, even complex ones, as long as it is understood by all database-management-systems. The names have to be valid column names of the specified table.parentToChildConnections
- An array consisting of ParentToChildConnections that specify WHERE-conditions for joining the hierarchical data. The individual ParentToChildConnections are logically linked via AND. These can only contain columns that are part of theselectAttributes
.maxDepth
- The maximum depth of the recursion/hierarchical level which is needed. The recursions will stop when this depth is reached even if not all tuples are reached.- Returns:
- The name of the newly created relational table containing the result set of the recursive/hierarchical query.
- Throws:
SQLException
- If a database access error occurs or the specified attributes, the table name or the conditions are invalid, aSQLException
will be thrown.
-
createRecursionTable
String createRecursionTable(String[] selectAttributes, String[] rootAttributes, String tableName, String startCondition, ParentToChildConnection[] parentToChildConnections) throws SQLException
LikecreateRecursionTable(String[], String, String, ParentToChildConnection[], int)
but without a maximum depth. Here the recursion stops as soon as there are no more tuples in a recursion step.Following are examples for translations of the method parameters to DB2- and Oracle-syntax. in DB2:
CREATE TABLE return AS WITH RecRel(Depth, selectAttributes[]) AS (SELECT 1, selectAttributes[] FROM tableName WHERE startCondition UNION ALL SELECT Parent.Depth + 1, Parent.rootAttributes[], Child.selectAttributes[] FROM RecRel AS Parent, tableName AS Child WHERE Parent.parentToChildConnection[0].getParentAttribute() parentToChildConnection[0].getOperator() Child.parentToChildConnection[0].getChildAttribute() AND Parent.parentToChildConnection[1].getParentAttribute() parentToChildConnection[1].getOperator() Child.parentToChildConnection[1].getChildAttribute() AND ... ) SELECT * FROM RecRel
in Oracle:CREATE TABLE return AS SELECT Depth, CONNECT_BY_ROOT rootAttributes[], (additional) selectAttributes[] FROM tableName START WITH startCondition CONNECT BY PRIOR parentToChildConnection[0] AND PRIOR parentToChildConnection[1] AND ...
- Parameters:
selectAttributes
- Array of the names of the columns to be in the created recursion table. The names have to be valid column names of the specified table.rootAttributes
- Array of the names of columns of the root table, that is, these values will be constant in each recursion step and therefore stem from recursion initialisation. This is a subset of theselectAttributes
. If this isnull
, each tuple from a recursion step will have new attributes.tableName
- The name of the table which contains the hierarchical data. If the hierarchical data spans several tables, a new temporary table will have to be created by joining these tables. Thus the name of the temporary table is to be used as parameter.startCondition
- A string forming a valid WHERE-condition which specifies the conditions which have to hold for the top-level tuples respectively the tuples for the start of the recursion. The string may be any valid WHERE-condition, even complex ones, as long as it is understood by all database-management-systems. The names have to be valid column names of the specified table.parentToChildConnections
- An array consisting of ParentToChildConnections that specify WHERE-conditions for joining the hierarchical data. The individual ParentToChildConnections are logically linked via AND. These can only contain columns that are part of theselectAttributes
.- Returns:
- The name of the newly created relational table containing the result set of the recursive/hierarchical query.
- Throws:
SQLException
- If a database access error occurs or the specified attributes, the table name or the conditions are invalid, aSQLException
will be thrown.
-
dropAllRecursionTables
void dropAllRecursionTables() throws SQLException
All tables that have been created viacreateRecursionTable(String[], String, String, String[], int)
are dropped. This needs to be done to clean up the database. The corresponding table names are stored internally and need not be provided.- Throws:
SQLException
- If a database access error occurs, aSQLException
will be thrown.- See Also:
createRecursionTable(String[], String[], String, String, ParentToChildConnection[])
-
dropRecursionTable
void dropRecursionTable(String tableName) throws SQLException
The specified table that has been created viacreateRecursionTable(String[], String, String, String[], int)
is dropped. This needs to be done to clean up the database. If the provided table has not been created bycreateRecursionTable(String[], String, String, String[], int)
, the call will be ignored. If the table has been created bycreateRecursionTable(String[], String, String, String[], int)
but does not exists in the database any more, aDBException
will be raised.Implementors of this method have to take care not to drop the table again in
dropAllRecursionTables()
.- Parameters:
tableName
- The name of the created temporary table. If it has not been created bycreateRecursionTable(String[], String, String, String[], int)
, the call will be ignored. If the table does otherwise not exist in the database, aDBException
will be raised.- Throws:
SQLException
- If a database access error occurs, aSQLException
will be thrown, especially if the provided table does not exist.- See Also:
dropAllRecursionTables()
,createRecursionTable(String[], String, String, ParentToChildConnection[], int)
-
registerIterator
void registerIterator()
Registers an iterator for thisExtendedConnection
which prevents this connection from being reclaimed in case it is pooled. A pooled connection must not be reclaimed while an iterator is active.
-
deregisterIterator
void deregisterIterator()
Deregisters an iterator for thisExtendedConnection
which allows this connection to be reclaimed again in case it is not used any more.
-
-