Class DBFunctions
- java.lang.Object
-
- jetbrains.buildServer.serverSide.db.DBFunctions
-
- All Implemented Interfaces:
SQLExceptionConvertor
public abstract class DBFunctions extends Object implements SQLExceptionConvertor
Database functions. Provides useful functions for interacting with database.Connection
In order to get an instance of DBFunctions class, use aDBFunctionsProvider
. It is a safe way to perform database operations.Transactions
DBFunctions doesn nothing with transactions, except when it asked to execute DDL statements. It allows to work in both auto-committed and normal modes.
When it asked to execute select and DML queries only, it follows by the general rules for working with a jdbc connection. The client should manipulate with transactions by theirself.
When it asked to execute a DDL statement, it can commit the current transaction (if one exists), then execute the specified DDL statement, and then commit transaction if successfull or roll it back in case of exceptions.
Really transactions are handled by an implementation ofDBFunctionsProvider
that provided with an instance of DBFunctions.SQL macros
DBFunctions supports additional tokens inside SQL statements - macros. Each macro starts with the sharp (#) sign and consists of one word wich can be followed by parameters. Parameters are covered with braces and separated with semicolons.SQL parameters
Most of functions support two ways how SQL parameters:- sequential (each one is noted as a query (?) sign in SQL statenment), their values are passed by an array of values;
- named (each one is noted by a name prefixed with the colon (:
Results
Each function that performing a 'select' query retrieves all result rows internally, and returns a ready collection of values.Exceptions
Each function can produceDBException
s instead ofSQLException
s.Closing
Don't forget to call theclose()
function when you've finished to work with DBFunctions instance (to prevent resources loss). Use try..finally for it.- Author:
- Leonid Bushuev
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
DBFunctions.StatementAndQuery
static interface
DBFunctions.StatementTuner
-
Field Summary
Fields Modifier and Type Field Description static int
DEFAULT_FETCH_SIZE_FOR_MORE_THAN_ONE_ROW
protected Connection
myConnection
protected SQLDialect
myDialect
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
applyFetchSize(Statement st, int fetchSize)
void
applyParameters(PreparedStatement stmt, Object[] params)
protected abstract boolean
checkPermTableExists(String tableName)
Checks permanent table existence.boolean
checkQueryReturnsRows(String query, Object... params)
Executes the given query and checks whether it returns at least one row.boolean
checkQueryReturnsRows(String query, Map<String,Object> params)
Executes the given query and checks whether it returns at least one row.boolean
checkTableExistence(String tableName)
Checks whether the specified table exists.boolean
checkTableRowsExistence(String tableName, Map<String,Object> fields)
Checks whether the given row exists in the specified table.protected abstract boolean
checkTempTableExists(String tableName)
Checks temporary table existence.void
close()
Closes all allocated resources and returns the holded connection back.void
commit()
Performs commit if the connection is in the transactional mode, or does nothing if the connection is in the auto-commit mode.DBException
convertSQLException(String operation, SQLException sqle)
DBException
convertSQLException(String operation, SQLException sqle, String query)
static DBFunctions
create(SQLDialect dialect, DataSource dataSource)
Creates an instance of DBFunctions using the given data source.static DBFunctions
create(SQLDialect dialect, DataSource dataSource, DatabaseAccessChecker databaseAccessChecker)
Creates an instance of DBFunctions using the given data source.Statement
createStatement()
Deprecated.protected DBFunctions.StatementTuner
createStatementTunerForSimpleValuesQuery()
SQLDialect
dialect()
Returns anSQLDialect
instance appropriated for the current DBMS type.void
executeBatchForInts(String command, Collection<Integer> data)
Executes the specified DML statement several times (one time for each item given in data), reusing the same jdbc statement object.void
executeBatchForLongs(String command, Collection<Long> data)
Executes the specified DML statement several times (one time for each item given in data), reusing the same jdbc statement object.void
executeBatchForObjects(String command, Collection<?> data)
Executes the specified DML statement several times (one time for each item given in data), reusing the same jdbc statement object.void
executeBatchForStrings(String command, Collection<String> data)
Executes the specified DML statement several times (one time for each item given in data), reusing the same jdbc statement object.<T> void
executeBatchForTuples(String command, Class<T> clazz, Collection<? extends T> data, Object... plainParams)
Executes a SQL statement many times, one time for each data item.void
executeDdls(String... commands)
Executes one or several DDL commands.void
executeDdls(List<String> commands)
int
executeDml(String query, Object... params)
Executes the given DML statement.int
executeDml(String query, Map<String,Object> params)
Executes the given DML statement.int
executeDmls(String... queries)
Executes several DML statements without parameters.void
executeScript(String script)
Executes the specifies script without parameters.void
executeScript(String script, Map<String,Object> params)
Executes the specified script with parameters.protected void
executeSimpleInternal(QueryAndParams qnp)
void
expandStringColumn(String tableName, String columnName, int newWidth)
Increases the size of the specified string column.boolean
getAutoCommit()
abstract String
getCharacterSet()
Returns the character set of the underlying database schema, ornull
if none is available.String
getClientCharacterSet()
Returns the character set of the JDBC client (i. e. TeamCity) as seen by the database server, ornull
if none is known or the database server doesn't support this feature.abstract String
getCollation()
Returns the collation of the underlying database schema, ornull
if none is available.ResultSet
getColumns(String tableNamePattern, String columnNamePattern)
Retrieves a description of table columns available in the specified catalog.Connection
getConnection()
Please NEVER uses this getter! This getter is very dangerous and provided for backward compatibility only.String
getConnectionCharacterSet()
Returns the character set of the established JDBC connection, ornull
if none is known or the database server doesn't support this feature.String
getConnectionCollation()
Returns the collation of the established JDBC connection, ornull
if none is known or the database server doesn't support this feature.DatabaseAccessChecker
getDatabaseAccessChecker()
abstract String
getDatabaseName()
Returns the name of the current database.DatabaseType
getDatabaseType()
Returns the type of the database.ResultSet
getIndexInfo(String table, boolean unique, boolean approximate)
Retrieves a description of the given table's indices and statistics.TimeZone
getParsedServerTimeZone()
Returns the Java time zone which corresponds to that of the database server, ornull
if server time zone isnull
or unparseable.ResultSet
getPrimaryKeys(String table)
Retrieves a description of the given table's primary key columns.abstract String
getSchemaNameForMetadata()
Returns the schema for using in jdbc getMetadata.String
getServerCharacterSet()
Returns the character set of the database server (which, generally, may be different from that of the database), ornull
if none is known or the database server doesn't support this feature.String
getServerCollation()
Returns the collation of the database server (which, generally, may be different from that of the database), ornull
if none is known or the database server doesn't support this feature.String
getServerTimeZone()
Returns the time zone of the database server, ornull
if none is known or the database server doesn't support this feature.int
getTableColumnWidth(String tableName, String columnName)
Determines width of one table column.Map<String,Integer>
getTableColumnWidths(String tableName)
Retrieves column widths for the specified table.protected abstract String
getTableMandatoryColumnsQuery()
ResultSet
getTables(String tableNamePattern, String[] types)
Retrieves a description of the tables available in the given catalog.String
getUserName()
Determines the database user name.abstract boolean
isIdentifierNameCaseSensitive()
Checks whether indentifier names (table names, column names) are case sensitive in the current database.protected boolean
isMandatorityIsPreservedWhenColumnIsChanged()
Returns true if column mandatority is preserved when column is changed.boolean
isTableColumnExists(String tableName, String columnName)
Checks whether the table exists and has the specified column.boolean
isTableColumnMandatory(String tableName, String columnName)
Returns true if specified column is mandatory, false otherwise.Set<String>
listTableMandatoryColumns(String tableName, boolean toLowerCase)
boolean
namedIndexExists(String table, String indexName)
Returns true if index with specified name exists for the specified tablePreparedStatement
prepareStatement(String command)
Deprecated.protected String
preprocessQueryUsingConnection(String query, QueryKind queryKind)
Allows to preprocess the query depends on the current connection.protected String
preprocessTableNameAfterRetrieved(String tableName)
List<BigDecimal>
queryForBigDecimals(String query, Object... params)
Executes the specified query and expects rows with big decimal values in the first column.gnu.trove.list.TIntList
queryForIntList(String query, Object... params)
Executes the specified query and expects rows withTypes.INTEGER
values in the first column.gnu.trove.list.TIntList
queryForIntList(String query, Map<String,Object> params)
Executes the specified query and expects rows withTypes.INTEGER
values in the first column.List<Integer>
queryForInts(String query, Integer maxRows, Map<String,Object> params)
Executes the specified query and expects rows with integer values in the first column.List<Integer>
queryForInts(String query, Object... params)
Executes the specified query and expects rows with integer values in the first column.<D> List<D>
queryForListOf(Class<D> clazz, String query, Object... params)
gnu.trove.list.TLongList
queryForLongList(String query, Integer maxRows, Map<String,Object> params)
Executes the specified query and expects rows withTypes.BIGINT
values in the first column.gnu.trove.list.TLongList
queryForLongList(String query, Object... params)
Executes the specified query and expects rows withTypes.BIGINT
values in the first column.List<Long>
queryForLongs(String query, Integer maxRows, Map<String,Object> params)
Executes the specified query and expects rows with long integer values in the first column.List<Long>
queryForLongs(String query, Object... params)
Executes the specified query and expects rows with long integer values in the first column.<K,V>
Map<K,V>queryForMap(String query, Class<K> keyClass, Class<V> valueClass, Object... params)
Executes the specified query and expects rows with two columns: the first one will be threated as a key and the second one - as a value.<K,V>
SortedMap<K,V>queryForMap(String query, Comparator<K> keyComparator, Class<K> keyClass, Class<V> valueClass, Object... params)
Executes the specified query and expects rows with two columns: the first one will be threated as a key and the second one - as a value.boolean
queryForSingleBoolean(String query, boolean defaultValue, Object... params)
Performs a "select" query and expects one row with one boolean or integer column.int
queryForSingleInt(String query, int defaultValue, Object... params)
Performs a "select" query and expects one row with one integer column.long
queryForSingleLong(String query, long defaultValue, Object... params)
Performs a "select" query and expects one row with one long integer column.String
queryForSingleString(String query, String defaultValue, Object... params)
Performs a "select" query and expects one row with one column.String
queryForSingleString(String query, String defaultValue, Map<String,Object> params)
Performs a "select" query and expects one row with one column.Timestamp
queryForSingleTimestamp(String query, Timestamp defaultValue, Object... params)
Performs a "select" query and expects one row with one timestamp column.List<String>
queryForStrings(String query, Integer maxRows, Map<String,Object> params)
Executes the specified query and expects rows with string values in the first column.List<String>
queryForStrings(String query, Object... params)
Executes the specified query and expects rows with string values in the first column.<T,COLL extends Collection<? super T>>
COLLqueryForTuples(COLL result, Class<T> clazz, String methodName, String query, Object... params)
Performs the specified select query and retrieves result rows as tuples of the specified class.<T,COLL extends Collection<? super T>>
COLLqueryForTuples(COLL result, Class<T> clazz, String methodName, String query, Map<String,Object> params)
Performs the specified select query and retrieves result rows as tuples of the specified class.<T,COLL extends Collection<? super T>>
COLLqueryForTuples(COLL result, Integer maxTuplesToReturn, Class<T> clazz, String methodName, String query, Object... params)
Sames asqueryForTuples(Collection, Class, String, String, Object...)
but optionally can limit the results by the specified amount.<T> void
queryForTuples(T object, String methodName, String query, Object... params)
Performs the specified select query, retrieves result rows and calls the specified object method for each retrived row.<T> void
queryForTuples(T object, String methodName, String query, Map<String,Object> params)
Performs the specified select query, retrieves result rows and calls the specified object method for each retrived row.Pair<Long,Long>
queryForTwoLongsSingleRecord(String query, Object... params)
Performs a "select" query and expects one row with two long integer columns.<T> T
queryForValue(Class<T> clazz, String query, Object... params)
Performs a "select" query and expects one row with one column.<T> T
queryForValue(Class<T> clazz, String query, Map<String,Object> params)
Performs a "select" query and expects one row with one column.abstract Collection<String>
retrieveSchemasWithTables()
Retrieves all schema with tables, if the database support schemas.abstract Set<String>
retrieveSchemaTableNames(boolean includePerm, boolean includeTemp, boolean lowerCase)
Lists all tables of the current schema and returns their names.void
rollback()
Performs roll back if the connection is in the transactional mode, or does nothing if the connection is in the auto-commit mode.void
setAutoCommit(boolean autoCommit)
static void
setDefaultDatabaseAccessChecker(DatabaseAccessChecker databaseAccessChecker)
void
setFetchSize(int fetchSize)
Sets fetch size to use in prepared statements for subsequent SQL queries where more than one row is expected.
-
-
-
Field Detail
-
DEFAULT_FETCH_SIZE_FOR_MORE_THAN_ONE_ROW
public static final int DEFAULT_FETCH_SIZE_FOR_MORE_THAN_ONE_ROW
-
myConnection
@NotNull protected final Connection myConnection
-
myDialect
@NotNull protected final SQLDialect myDialect
-
-
Method Detail
-
create
@NotNull public static DBFunctions create(@NotNull SQLDialect dialect, @NotNull DataSource dataSource)
Creates an instance of DBFunctions using the given data source. After using don't forget to callclose()
to close the taken connection.- Parameters:
dataSource
- data source to take a connection from.- Returns:
- an instance of DBFunctions with just taken connection.
-
create
@NotNull public static DBFunctions create(@NotNull SQLDialect dialect, @NotNull DataSource dataSource, @Nullable DatabaseAccessChecker databaseAccessChecker)
Creates an instance of DBFunctions using the given data source. After using don't forget to callclose()
to close the taken connection.- Parameters:
dataSource
- data source to take a connection from.databaseAccessChecker
- database access checker to use for SQL queries- Returns:
- an instance of DBFunctions with just taken connection.
-
setDefaultDatabaseAccessChecker
public static void setDefaultDatabaseAccessChecker(@Nullable DatabaseAccessChecker databaseAccessChecker)
-
getDatabaseAccessChecker
@Nullable public final DatabaseAccessChecker getDatabaseAccessChecker()
-
queryForSingleString
@Nullable @Contract("_, !null, _ -> !null; ") public final String queryForSingleString(@NotNull String query, @Nullable String defaultValue, Object... params) throws DBException
Performs a "select" query and expects one row with one column.- Parameters:
query
- the "select" query to execute.defaultValue
- the value that will be returned when no rows are selected.params
- sequential parameters for the query.- Returns:
- the value of the first row first column, or the defaultValue if no rows selected.
- Throws:
DBException
-
queryForSingleString
@Nullable @Contract("_, !null, _ -> !null; ") public final String queryForSingleString(@NotNull String query, @Nullable String defaultValue, @NotNull Map<String,Object> params) throws DBException
Performs a "select" query and expects one row with one column.- Parameters:
query
- the "select" query to execute.defaultValue
- the value that will be returned when no rows are selected.params
- named parameters for the query.- Returns:
- the value of the first row first column, or the defaultValue if no rows selected.
- Throws:
DBException
-
queryForValue
@Nullable public final <T> T queryForValue(@NotNull Class<T> clazz, @NotNull String query, Object... params) throws DBException
Performs a "select" query and expects one row with one column.- Parameters:
query
- the "select" query to execute.params
- sequential parameters for the query.- Returns:
- the value of the first row first column, or the defaultValue if no rows selected.
- Throws:
DBException
- Since:
- 9.0
-
queryForValue
@Nullable public final <T> T queryForValue(@NotNull Class<T> clazz, @NotNull String query, @NotNull Map<String,Object> params) throws DBException
Performs a "select" query and expects one row with one column.- Parameters:
query
- the "select" query to execute.params
- named parameters for the query.- Returns:
- the value of the first row first column, or the defaultValue if no rows selected.
- Throws:
DBException
- Since:
- 9.0
-
queryForSingleBoolean
public final boolean queryForSingleBoolean(@NotNull String query, boolean defaultValue, Object... params) throws DBException
Performs a "select" query and expects one row with one boolean or integer column.Integer values also is interpreted as boolean: values 1 and greater means true, 0 and lessser - false.
- Parameters:
query
- the "select" query to execute.defaultValue
- the value that will be returned when no rows are selected.params
- sequential parameters for the query.- Returns:
- the value of the first row first column, or the defaultValue if no rows selected.
- Throws:
DBException
- Since:
- 8.0.5
-
queryForSingleInt
public final int queryForSingleInt(@NotNull String query, int defaultValue, Object... params) throws DBException
Performs a "select" query and expects one row with one integer column.- Parameters:
query
- the "select" query to execute.defaultValue
- the value that will be returned when no rows are selected.params
- sequential parameters for the query.- Returns:
- the value of the first row first column, or the defaultValue if no rows selected.
- Throws:
DBException
-
queryForSingleLong
public final long queryForSingleLong(@NotNull String query, long defaultValue, Object... params) throws DBException
Performs a "select" query and expects one row with one long integer column.- Parameters:
query
- the "select" query to execute.defaultValue
- the value that will be returned when no rows are selected.params
- sequential parameters for the query.- Returns:
- the value of the first row first column, or the defaultValue if no rows selected.
- Throws:
DBException
-
queryForTwoLongsSingleRecord
public final Pair<Long,Long> queryForTwoLongsSingleRecord(@NotNull String query, Object... params) throws DBException
Performs a "select" query and expects one row with two long integer columns.- Parameters:
query
- the "select" query to execute.params
- sequential parameters for the query.- Returns:
- a Pair object containing the two (usually minimum and maximum) values of the selected rows, or a Pair object with null values if no rows are selected.
- Throws:
DBException
- if there is an error executing the query.- Since:
- 2023.11
-
queryForSingleTimestamp
@Nullable public final Timestamp queryForSingleTimestamp(@NotNull String query, @Nullable Timestamp defaultValue, Object... params) throws DBException
Performs a "select" query and expects one row with one timestamp column.- Parameters:
query
- the "select" query to execute.defaultValue
- the value that will be returned when no rows are selected.params
- sequential parameters for the query.- Returns:
- the value of the first row first column, or the defaultValue if no rows selected.
- Throws:
DBException
-
queryForInts
@NotNull public final List<Integer> queryForInts(@NotNull String query, Object... params)
Executes the specified query and expects rows with integer values in the first column. Returns the first column as a list of integer values. Preserves the order.If you're concerned about performance, consider using
queryForIntList(String, Object...)
instead.- Parameters:
query
- a query to execute.params
- sequential parameters.- Returns:
- values from the first column of result set (db nulls are presented as java nulls).
- See Also:
queryForIntList(String, Object...)
-
queryForIntList
@NotNull public final gnu.trove.list.TIntList queryForIntList(@NotNull String query, Object... params)
Executes the specified query and expects rows with
Types.INTEGER
values in the first column. Returns the first column as a list ofint
values. Preserves the order.This method ignores any
SQL null
's encountered (i. e. the size of the list returned may be less than the result of the correspondingSELECT count(*) ...
query with the same predicates).- Parameters:
query
- the query to execute.params
- sequential parameters.- Returns:
- the values from the first column of the result set (
SQL null
's are ignored). - Since:
- 2017.2.4, 2018.1
- See Also:
queryForInts(String, Object...)
-
queryForInts
@NotNull public final List<Integer> queryForInts(@NotNull String query, @Nullable Integer maxRows, @NotNull Map<String,Object> params)
Executes the specified query and expects rows with integer values in the first column. Returns the first column as a list of integer values. Preserves the order.If you're concerned about performance, consider using
queryForIntList(String, Map)
instead.- Parameters:
query
- a query to execute.maxRows
- max rows to return or null if there is no limitparams
- named parameters.- Returns:
- values from the first column of result set (db nulls are presented as java nulls).
- See Also:
queryForIntList(String, Map)
-
queryForIntList
@NotNull public final gnu.trove.list.TIntList queryForIntList(@NotNull String query, @NotNull Map<String,Object> params)
Executes the specified query and expects rows with
Types.INTEGER
values in the first column. Returns the first column as a list ofint
values. Preserves the order.This method ignores any
SQL null
's encountered (i. e. the size of the list returned may be less than the result of the correspondingSELECT count(*) ...
query with the same predicates).- Parameters:
query
- the query to execute.params
- named parameters.- Returns:
- the values from the first column of the result set (
SQL null
's are ignored). - Since:
- 2017.2.4, 2018.1
- See Also:
#queryForInts(String, Map)
-
queryForLongs
@NotNull public final List<Long> queryForLongs(@NotNull String query, Object... params)
Executes the specified query and expects rows with long integer values in the first column. Returns the first column as a list of long integer values. Preserves the order.If you're concerned about performance, consider using
queryForLongList(String, Object...)
instead.- Parameters:
query
- a query to execute.params
- sequential parameters.- Returns:
- values from the first column of result set (db nulls are presented as java nulls).
- See Also:
queryForLongList(String, Object...)
-
queryForLongList
@NotNull public final gnu.trove.list.TLongList queryForLongList(@NotNull String query, Object... params)
Executes the specified query and expects rows with
Types.BIGINT
values in the first column. Returns the first column as a list of longlong
values. Preserves the order.This method ignores any
SQL null
's encountered (i. e. the size of the list returned may be less than the result of the correspondingSELECT count(*) ...
query with the same predicates).- Parameters:
query
- the query to execute.params
- sequential parameters.- Returns:
- the values from the first column of the result set (
SQL null
's are ignored). - Since:
- 2017.2.4, 2018.1
- See Also:
queryForLongs(String, Object...)
-
queryForLongs
@NotNull public final List<Long> queryForLongs(@NotNull String query, @Nullable Integer maxRows, @NotNull Map<String,Object> params)
Executes the specified query and expects rows with long integer values in the first column. Returns the first column as a list of long integer values. Preserves the order.If you're concerned about performance, consider using
#queryForLongList(String, Map)
instead.- Parameters:
query
- a query to execute.maxRows
- max rows to return or null if there is no limitparams
- named parameters.- Returns:
- values from the first column of result set (db nulls are presented as java nulls).
- See Also:
#queryForLongList(String, Map)
-
queryForLongList
@NotNull public final gnu.trove.list.TLongList queryForLongList(@NotNull String query, @Nullable Integer maxRows, @NotNull Map<String,Object> params)
Executes the specified query and expects rows with
Types.BIGINT
values in the first column. Returns the first column as a list of longlong
values. Preserves the order.This method ignores any
SQL null
's encountered (i. e. the size of the list returned may be less than the result of the correspondingSELECT count(*) ...
query with the same predicates).- Parameters:
query
- the query to execute.maxRows
- maximum number of rows to selectparams
- named parameters.- Returns:
- the values from the first column of the result set (
SQL null
's are ignored). - Since:
- 2017.2.4, 2018.1
- See Also:
#queryForLongs(String, Map)
-
queryForStrings
@NotNull public final List<String> queryForStrings(@NotNull String query, Object... params)
Executes the specified query and expects rows with string values in the first column. Returns the first column as a list of strings. Preserves the order.- Parameters:
query
- a query to execute.params
- sequential parameters.- Returns:
- values from the first column of result set (db nulls are presented as java nulls).
-
queryForBigDecimals
@NotNull public final List<BigDecimal> queryForBigDecimals(@NotNull String query, Object... params)
Executes the specified query and expects rows with big decimal values in the first column. Returns the first column as a list of big decimals. Preserves the order.- Parameters:
query
- a query to execute.params
- sequential parameters.- Returns:
- values from the first column of result set (db nulls are presented as java nulls).
-
queryForStrings
public final List<String> queryForStrings(@NotNull String query, @Nullable Integer maxRows, @NotNull Map<String,Object> params)
Executes the specified query and expects rows with string values in the first column. Returns the first column as a list of strings. Preserves the order.- Parameters:
query
- a query to execute.maxRows
- max rows to return or null if there is no limitparams
- named parameters.- Returns:
- values from the first column of result set (db nulls are presented as java nulls).
-
queryForListOf
@NotNull public final <D> List<D> queryForListOf(@NotNull Class<D> clazz, @NotNull String query, Object... params)
-
queryForMap
@NotNull public final <K,V> Map<K,V> queryForMap(@NotNull String query, @NotNull Class<K> keyClass, @NotNull Class<V> valueClass, Object... params)
Executes the specified query and expects rows with two columns: the first one will be threated as a key and the second one - as a value. All keys must be different. Returns a map built on the fetched keys and values.- Type Parameters:
K
- class of keys.V
- class of values.- Parameters:
query
- a query to execute.keyClass
- class of keys.valueClass
- class of values.params
- query parameters.- Returns:
- an immutable map.
-
queryForMap
@NotNull public final <K,V> SortedMap<K,V> queryForMap(@NotNull String query, @NotNull Comparator<K> keyComparator, @NotNull Class<K> keyClass, @NotNull Class<V> valueClass, Object... params)
Executes the specified query and expects rows with two columns: the first one will be threated as a key and the second one - as a value. All keys must be different (regarding to the given comparator). Returns a sorted map built on the fetched keys and values.- Type Parameters:
K
- class of keys.V
- class of values.- Parameters:
query
- a query to execute.keyComparator
- comparator for keys.keyClass
- class of keys.valueClass
- class of values.params
- query parameters.- Returns:
- an immutable sorted map based on the given comparator.
-
executeDdls
public final void executeDdls(@NotNull String... commands) throws DBException
Executes one or several DDL commands.Warning! - executing a DDL command may perform commit before execution, it depends on the DBMS type. Be sure that this session have no active transactions.
- Parameters:
commands
- ddl queries- Throws:
DBException
-
getAutoCommit
public final boolean getAutoCommit()
-
setAutoCommit
public final void setAutoCommit(boolean autoCommit)
-
executeSimpleInternal
protected void executeSimpleInternal(@NotNull QueryAndParams qnp)
-
executeDml
public final int executeDml(@NotNull String query, @NotNull Object... params)
Executes the given DML statement.- Parameters:
query
- the DML statement to execute.params
- sequential parameters.- Returns:
- count of affected rows.
-
executeDml
public final int executeDml(@NotNull String query, @NotNull Map<String,Object> params)
Executes the given DML statement.- Parameters:
query
- the DML statement to execute.params
- named parameters.- Returns:
- count of affected rows.
-
executeDmls
public final int executeDmls(@NotNull String... queries)
Executes several DML statements without parameters.- Parameters:
queries
- DML queries to execute.- Returns:
- number of affected rows (in all given statements).
-
executeScript
public final void executeScript(@NotNull String script)
Executes the specifies script without parameters. SQL statements in the script should be separated with semicolon that should be the last character in the string (however, spaces and single-line comments are accepted after this semicolon).Known problem: a semicolon inside a block comment can be treated incorrectly.
- Parameters:
script
- script to execute.- See Also:
executeScript(String, Map)
-
executeScript
public final void executeScript(@NotNull String script, @Nullable Map<String,Object> params)
Executes the specified script with parameters. SeeexecuteScript(String)
for details.- Parameters:
script
- script to execute.params
- named parameters.
-
executeBatchForInts
public final void executeBatchForInts(@NotNull String command, Collection<Integer> data)
Executes the specified DML statement several times (one time for each item given in data), reusing the same jdbc statement object.- Parameters:
command
- the DML command to execute.data
- collection of values - the specified statement will be executed one time for each item in this collection.
-
executeBatchForLongs
public final void executeBatchForLongs(@NotNull String command, Collection<Long> data)
Executes the specified DML statement several times (one time for each item given in data), reusing the same jdbc statement object.- Parameters:
command
- the DML command to execute.data
- collection of values - the specified statement will be executed one time for each item in this collection.
-
executeBatchForStrings
public final void executeBatchForStrings(@NotNull String command, Collection<String> data)
Executes the specified DML statement several times (one time for each item given in data), reusing the same jdbc statement object.- Parameters:
command
- the DML command to execute.data
- collection of values - the specified statement will be executed one time for each item in this collection.
-
executeBatchForObjects
public final void executeBatchForObjects(@NotNull String command, Collection<?> data)
Executes the specified DML statement several times (one time for each item given in data), reusing the same jdbc statement object.- Parameters:
command
- the DML command to execute.data
- collection of values - the specified statement will be executed one time for each item in this collection.
-
executeBatchForTuples
public final <T> void executeBatchForTuples(@NotNull String command, @NotNull Class<T> clazz, @NotNull Collection<? extends T> data, @Nullable Object... plainParams)
Executes a SQL statement many times, one time for each data item. // TODO document how should parameters be named- Type Parameters:
T
- type of data items.- Parameters:
command
- SQL statement to execute.clazz
- class of data item.data
- data items.plainParams
- auxiliary parameters (common for each items).
-
checkTableRowsExistence
public final boolean checkTableRowsExistence(@NotNull String tableName, @Nullable Map<String,Object> fields)
Checks whether the given row exists in the specified table.- Parameters:
tableName
- name of the table to insert row.fields
- fields names an values.- Returns:
- exists or not.
-
checkQueryReturnsRows
public final boolean checkQueryReturnsRows(@NotNull String query, Object... params) throws DBException
Executes the given query and checks whether it returns at least one row.- Parameters:
query
- the query to execute.params
- sequential parameters.- Returns:
- whether it returns at least one row.
- Throws:
DBException
-
checkQueryReturnsRows
public final boolean checkQueryReturnsRows(@NotNull String query, @NotNull Map<String,Object> params) throws DBException
Executes the given query and checks whether it returns at least one row.- Parameters:
query
- the query to execute.params
- named parameters.- Returns:
- whether it returns at least one row.
- Throws:
DBException
-
checkTableExistence
public final boolean checkTableExistence(@NotNull String tableName)
Checks whether the specified table exists.- Parameters:
tableName
- name of the table to check.- Returns:
- whether the table exists.
-
checkPermTableExists
protected abstract boolean checkPermTableExists(@NotNull String tableName)
Checks permanent table existence. This function is only to implement it by inheritors. Don't call it directly!- Parameters:
tableName
- table name already prepared for specific RDBMS.
-
checkTempTableExists
protected abstract boolean checkTempTableExists(@NotNull String tableName)
Checks temporary table existence. This function is only to implement it by inheritors. Don't call it directly!- Parameters:
tableName
- table name already prepared for specific RDBMS.
-
retrieveSchemaTableNames
@NotNull public abstract Set<String> retrieveSchemaTableNames(boolean includePerm, boolean includeTemp, boolean lowerCase)
Lists all tables of the current schema and returns their names. Method guarantees fetching all permanent tables for all database types. Fetching temporary tables is guaranteed only for Oracle and HSQL (where such kind of tables are true DB schema objects).- Parameters:
includePerm
- if true the result will include permanent tables as well.includeTemp
- if true the result will include temporary tables as well.lowerCase
- if true each table name will be turned to lower case.- Returns:
- set of table names in db-specific metadata style.
-
preprocessTableNameAfterRetrieved
@NotNull protected String preprocessTableNameAfterRetrieved(@NotNull String tableName)
-
queryForTuples
@NotNull public final <T,COLL extends Collection<? super T>> COLL queryForTuples(@NotNull COLL result, @NotNull Class<T> clazz, @Nullable String methodName, @NotNull String query, Object... params)
Performs the specified select query and retrieves result rows as tuples of the specified class.For each row, it invokes a class's constructor in order to instantiate an instance of tuple and pass result fileds as constructor arguments.
Which constructor to invoke is depend on the value of the methodName parameter. If the methodName is null then the first constructor that is not annotated as
Tuple
will be selected. If the methodName is specified then the constructor that annotated asTuple
(Tuple.method()
= "methodName") will be used.- Type Parameters:
T
- type of tuple.COLL
- type of tuple collection.- Parameters:
result
- collection where it will put retrieved tuples to.clazz
- class of tuples.methodName
- constructor name or null; empty strings are rejected.query
- the select query.params
- sequential query params.- Returns:
- the result collection given as result parameter.
-
queryForTuples
@NotNull public final <T,COLL extends Collection<? super T>> COLL queryForTuples(@NotNull COLL result, @Nullable Integer maxTuplesToReturn, @NotNull Class<T> clazz, @Nullable String methodName, @NotNull String query, Object... params)
Sames asqueryForTuples(Collection, Class, String, String, Object...)
but optionally can limit the results by the specified amount.- Type Parameters:
T
- type of tuple.COLL
- type of tuple collection.- Parameters:
result
- collection where it will put retrieved tuples to.maxTuplesToReturn
- max number of tuples to retrieve and add to the result (if null, then there is no limit)clazz
- class of tuples.methodName
- constructor name or null; empty strings are rejected.query
- the select query.params
- sequential query params.- Returns:
- the result collection given as result parameter.
- Since:
- 2017.1.3
-
queryForTuples
@NotNull public final <T,COLL extends Collection<? super T>> COLL queryForTuples(@NotNull COLL result, @NotNull Class<T> clazz, @Nullable String methodName, @NotNull String query, @NotNull Map<String,Object> params)
Performs the specified select query and retrieves result rows as tuples of the specified class.For each row, it invokes a class's constructor in order to instantiate an instance of tuple and pass result fileds as constructor arguments.
Which constructor to invoke is depend on the value of the methodName parameter. If the methodName is null then the first constructor that is not annotated as
Tuple
will be selected. If the methodName is specified then the constructor that annotated asTuple
(Tuple.method()
= "methodName") will be used.- Type Parameters:
T
- type of tuple.COLL
- type of tuple collection.- Parameters:
result
- collection where it will put retrieved tuples to.clazz
- class of tuples.methodName
- constructor name or null; empty strings are rejected.query
- the select query.params
- named query params.- Returns:
- the result collection given as result parameter.
-
queryForTuples
public final <T> void queryForTuples(@NotNull T object, @NotNull String methodName, @NotNull String query, Object... params)
Performs the specified select query, retrieves result rows and calls the specified object method for each retrived row.The method to call should accept parameters matched ones the given SQL query returns.
- Type Parameters:
T
- type of tuple.- Parameters:
object
- the object which method is to call.methodName
- the name of the method to call.query
- the select query.params
- sequential query params.
-
queryForTuples
public final <T> void queryForTuples(@NotNull T object, @NotNull String methodName, @NotNull String query, @NotNull Map<String,Object> params)
Performs the specified select query, retrieves result rows and calls the specified object method for each retrived row.The method to call should accept parameters matched ones the given SQL query returns.
- Type Parameters:
T
- type of tuple.- Parameters:
object
- the object which method is to call.methodName
- the name of the method to call.query
- the select query.params
- named query params.
-
isIdentifierNameCaseSensitive
public abstract boolean isIdentifierNameCaseSensitive()
Checks whether indentifier names (table names, column names) are case sensitive in the current database.Case sensitivity means DBMS tells names in different cases written without quotation as different ones.
Warning: in case of MySQL, it's unknown how to determine this option; so, for MySQL this function always returns true.
-
getDatabaseName
@Nullable public abstract String getDatabaseName()
Returns the name of the current database.Note: in case of Oracle it returns the name of schema.
- Returns:
- name of the current database.
-
getSchemaNameForMetadata
@Nullable public abstract String getSchemaNameForMetadata()
Returns the schema for using in jdbc getMetadata.
-
retrieveSchemasWithTables
@NotNull public abstract Collection<String> retrieveSchemasWithTables()
Retrieves all schema with tables, if the database support schemas. System and internal schemas aren't included.- Returns:
- schemas if they're supported by the database; an empty collection if not.
-
getUserName
@NotNull public final String getUserName()
Determines the database user name.- Returns:
- user name in the case returned by DBMS.
-
isTableColumnMandatory
public boolean isTableColumnMandatory(@NotNull String tableName, @NotNull String columnName)
Returns true if specified column is mandatory, false otherwise. Does not cache the result.- Parameters:
tableName
- name of the table.columnName
- name of the column.- Returns:
- true if specified column is mandatory, false otherwise.
-
listTableMandatoryColumns
public final Set<String> listTableMandatoryColumns(@NotNull String tableName, boolean toLowerCase)
-
getTableMandatoryColumnsQuery
@NotNull protected abstract String getTableMandatoryColumnsQuery()
-
getTableColumnWidth
public final int getTableColumnWidth(@NotNull String tableName, String columnName)
Determines width of one table column.For text columns - it returns size in chars. For raw byte stream columns - it returns size in bytes. For other columns it can return unpredictable values.
- Parameters:
tableName
- name of the table.columnName
- name of the column.- Returns:
- the width.
- See Also:
getTableColumnWidths(java.lang.String)
-
getTableColumnWidths
@NotNull public Map<String,Integer> getTableColumnWidths(@NotNull String tableName) throws DBException
Retrieves column widths for the specified table.For text columns - it returns size in chars. For raw byte stream columns - it returns size in bytes. For other columns it can return unpredictable values.
- Parameters:
tableName
- table name to look columns for.- Returns:
- map [column name -- column width], column names are in lower case, the order of columns in the map is undefined.
- Throws:
DBException
- See Also:
getTableColumnWidth(java.lang.String, java.lang.String)
-
isTableColumnExists
public final boolean isTableColumnExists(@NotNull String tableName, @NotNull String columnName)
Checks whether the table exists and has the specified column.- Parameters:
tableName
- table name.columnName
- column name (must be in lower case).- Returns:
- true if column exists, false if table doesn't exist or table has no such column.
-
expandStringColumn
public final void expandStringColumn(@NotNull String tableName, @NotNull String columnName, int newWidth)
Increases the size of the specified string column. Works only with string (varchar) columns; in other cases the behaviour of this procedure can be undeterminated.Determines the current size of the specified column and performs "alter table... modify..." if neccessary.
- Parameters:
tableName
- name of the table, in the lower case.columnName
- name of the column to change, in the lower case.newWidth
- the desired size.
-
isMandatorityIsPreservedWhenColumnIsChanged
protected boolean isMandatorityIsPreservedWhenColumnIsChanged()
Returns true if column mandatority is preserved when column is changed.- Returns:
- true if column mandatority is preserved when column is changed.
-
namedIndexExists
public boolean namedIndexExists(@NotNull String table, @NotNull String indexName)
Returns true if index with specified name exists for the specified table- Parameters:
table
- name of the tableindexName
- index name- Returns:
- see above
-
dialect
@NotNull public final SQLDialect dialect()
Returns anSQLDialect
instance appropriated for the current DBMS type.- Returns:
- an
SQLDialect
instance.
-
commit
public final void commit()
Performs commit if the connection is in the transactional mode, or does nothing if the connection is in the auto-commit mode.
-
rollback
public final void rollback()
Performs roll back if the connection is in the transactional mode, or does nothing if the connection is in the auto-commit mode.
-
close
public final void close()
Closes all allocated resources and returns the holded connection back.
-
getDatabaseType
@NotNull public final DatabaseType getDatabaseType()
Returns the type of the database.- Returns:
- the database type.
-
preprocessQueryUsingConnection
protected String preprocessQueryUsingConnection(String query, QueryKind queryKind)
Allows to preprocess the query depends on the current connection.- Parameters:
query
- query to preprocess; static macros already have been processed.queryKind
- kind of the query.- Returns:
- processed query.
-
applyFetchSize
public void applyFetchSize(@NotNull Statement st, int fetchSize) throws SQLException
- Throws:
SQLException
-
setFetchSize
public void setFetchSize(int fetchSize)
Sets fetch size to use in prepared statements for subsequent SQL queries where more than one row is expected.- Parameters:
fetchSize
- custom fetch size, use 0 to reset fetch size to default value
-
applyParameters
public final void applyParameters(@NotNull PreparedStatement stmt, @Nullable Object[] params) throws DBException
- Throws:
DBException
-
convertSQLException
@NotNull public final DBException convertSQLException(@NotNull String operation, @NotNull SQLException sqle)
- Specified by:
convertSQLException
in interfaceSQLExceptionConvertor
-
convertSQLException
@NotNull public final DBException convertSQLException(@NotNull String operation, @NotNull SQLException sqle, @Nullable String query)
- Specified by:
convertSQLException
in interfaceSQLExceptionConvertor
-
getConnection
@NotNull public final Connection getConnection()
Please NEVER uses this getter! This getter is very dangerous and provided for backward compatibility only. Please get rid of all usages of this getter and the remove it!
-
createStatement
@Deprecated public final Statement createStatement() throws SQLException
Deprecated.- Throws:
SQLException
-
prepareStatement
@Deprecated public final PreparedStatement prepareStatement(@NotNull String command) throws SQLException
Deprecated.- Throws:
SQLException
-
getCharacterSet
@Nullable public abstract String getCharacterSet()
Returns the character set of the underlying database schema, or
null
if none is available.- Returns:
- the character set of the underlying database schema, or
null
if none is available. - Throws:
DBException
- if a database access error occurs.- Since:
- 2017.2
-
getCollation
@Nullable public abstract String getCollation()
Returns the collation of the underlying database schema, or
null
if none is available.- Returns:
- the collation of the underlying database schema, or
null
if none is available. - Throws:
DBException
- if a database access error occurs.- Since:
- 2017.2
-
getServerCharacterSet
@Nullable public String getServerCharacterSet()
Returns the character set of the database server (which, generally, may be different from that of the database), or
null
if none is known or the database server doesn't support this feature.- Returns:
- the character set of the database server, or
null
if none is known or the database server doesn't support this feature. - Throws:
DBException
- if a database access error occurs.- Since:
- 2018.1.2
-
getServerCollation
@Nullable public String getServerCollation()
Returns the collation of the database server (which, generally, may be different from that of the database), or
null
if none is known or the database server doesn't support this feature.- Returns:
- the collation of the database server, or
null
if none is known or the database server doesn't support this feature. - Throws:
DBException
- if a database access error occurs.- Since:
- 2018.1.2
-
getConnectionCharacterSet
@Nullable public String getConnectionCharacterSet()
Returns the character set of the established JDBC connection, or
null
if none is known or the database server doesn't support this feature.- Returns:
- the character set of the established JDBC connection, or
null
if none is known or the database server doesn't support this feature. - Throws:
DBException
- if a database access error occurs.- Since:
- 2018.1.2
-
getConnectionCollation
@Nullable public String getConnectionCollation()
Returns the collation of the established JDBC connection, or
null
if none is known or the database server doesn't support this feature.- Returns:
- the collation of the established JDBC connection, or
null
if none is known or the database server doesn't support this feature. - Throws:
DBException
- if a database access error occurs.- Since:
- 2018.1.2
-
getClientCharacterSet
@Nullable public String getClientCharacterSet()
Returns the character set of the JDBC client (i. e. TeamCity) as seen by the database server, or
null
if none is known or the database server doesn't support this feature.- Returns:
- the character set of the JDBC client as seen by the database
server, or
null
if none is known or the database server doesn't support this feature. - Throws:
DBException
- if a database access error occurs.- Since:
- 2018.1.2
-
getServerTimeZone
@Nullable public String getServerTimeZone()
Returns the time zone of the database server, or
null
if none is known or the database server doesn't support this feature.- Returns:
- the time zone of the database server, or
null
if none is known or the database server doesn't support this feature. - Throws:
DBException
- if a database access error occurs.- Since:
- 2018.1.2
- See Also:
getParsedServerTimeZone()
-
getParsedServerTimeZone
@Nullable public TimeZone getParsedServerTimeZone()
Returns the Java time zone which corresponds to that of the database server, or
null
if server time zone isnull
or unparseable.- Returns:
- the Java time zone which corresponds to that of the
database server, or
null
if server time zone isnull
or unparseable. - Throws:
DBException
- if a database access error occurs.- Since:
- 2018.1.2
- See Also:
getServerTimeZone()
-
getTables
@NotNull public ResultSet getTables(@NotNull String tableNamePattern, @Nullable String[] types) throws SQLException
Retrieves a description of the tables available in the given catalog.
- Parameters:
tableNamePattern
- a table name pattern; must match the table name as it is stored in the database.types
- a list of table types, which must be from the list of table types returned fromDatabaseMetaData.getTableTypes()
, to include;null
returns all types.- Returns:
ResultSet
- each row is a table description.- Throws:
SQLException
- if a database access error occurs.- Since:
- 2017.2.4, 2018.1
- See Also:
DatabaseMetaData.getTables(String, String, String, String[])
-
getColumns
@NotNull public ResultSet getColumns(@NotNull String tableNamePattern, @Nullable String columnNamePattern) throws SQLException
Retrieves a description of table columns available in the specified catalog.
- Parameters:
tableNamePattern
- a table name pattern; must match the table name as it is stored in the database.columnNamePattern
- a column name pattern; must match the column name as it is stored in the database.- Returns:
ResultSet
- each row is a column description.- Throws:
SQLException
- if a database access error occurs.- Since:
- 2017.2.4, 2018.1
- See Also:
DatabaseMetaData.getColumns(String, String, String, String)
-
getPrimaryKeys
@NotNull public ResultSet getPrimaryKeys(@NotNull String table) throws SQLException
Retrieves a description of the given table's primary key columns.
- Parameters:
table
- a table name; must match the table name as it is stored in the database- Returns:
ResultSet
- each row is a primary key column description.- Throws:
SQLException
- if a database access error occurs.- Since:
- 2017.2.4, 2018.1
- See Also:
DatabaseMetaData.getPrimaryKeys(String, String, String)
-
getIndexInfo
@NotNull public ResultSet getIndexInfo(@NotNull String table, boolean unique, boolean approximate) throws SQLException
Retrieves a description of the given table's indices and statistics.
- Parameters:
table
- a table name; must match the table name as it is stored in this database.unique
- whentrue
, return only indices for unique values; whenfalse
, return indices regardless of whether unique or not.approximate
- whentrue
, result is allowed to reflect approximate or out of data values; whenfalse
, results are requested to be accurate.- Returns:
ResultSet
- each row is an index column description.- Throws:
SQLException
- if a database access error occurs.- Since:
- 2017.2.4, 2018.1
- See Also:
DatabaseMetaData.getIndexInfo(String, String, String, boolean, boolean)
-
createStatementTunerForSimpleValuesQuery
@Nullable protected DBFunctions.StatementTuner createStatementTunerForSimpleValuesQuery()
-
-