Class Client
- All Implemented Interfaces:
AutoCloseable
Client is the starting point for all interactions with ClickHouse.
Client.Builder is designed to construct a client object with required configuration:
Client client = new Client.Builder()
.addEndpoint(Protocol.HTTP, node.getHost(), node.getPort())
.addUsername("default")
.build();
When client object is created any operation method can be called on it:
if (client.ping()) {
QuerySettings settings = new QuerySettings().setFormat(ClickHouseFormat.RowBinaryWithNamesAndTypes);
try (QueryResponse response = client.query("SELECT * FROM " + table, settings).get(10, TimeUnit.SECONDS)) {
...
}
}
Client is thread-safe. It uses exclusive set of object to perform an operation.
-
Nested Class Summary
Nested Classes -
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Frees the resources associated with the client.Executes a SQL command and doesn't care response.execute(String sql, CommandSettings settings) Executes a SQL command and doesn't care response.Returns unmodifiable map of configuration options.Returns list of DB roles that should be applied to each query.Returns default database name that will be used by operations if not specified.Returns unmodifiable set of endpoints.protected intReturns operation timeout in secondsgetTableSchema(String table) Fetches schema of a table and returns complete information about each column.getTableSchema(String table, String database) Fetches schema of a table and returns complete information about each column.Creates table schema from a query.getUser()insert(String tableName, DataStreamWriter writer, ClickHouseFormat format, InsertSettings settings) Does an insert request to a server.insert(String tableName, InputStream data, ClickHouseFormat format) Sends write request to database.insert(String tableName, InputStream data, ClickHouseFormat format, InsertSettings settings) Sends write request to database.Sends write request to database.insert(String tableName, List<?> data, InsertSettings settings) Sends write request to database.voidLoads essential information about a server.newBinaryFormatReader(QueryResponse response) newBinaryFormatReader(QueryResponse response, TableSchema schema) Create an instance ofClickHouseBinaryFormatReaderbased on response.booleanping()Pings the server to check if it is alivebooleanping(long timeout) Pings the server to check if it is alive.Sends SQL query to server.query(String sqlQuery, QuerySettings settings) Sends SQL query to server.Sends SQL query to server with parameters.queryAll(String sqlQuery, QuerySettings settings) <T> List<T>queryAll(String sqlQuery, Class<T> clazz, TableSchema schema) <T> List<T>queryAll(String sqlQuery, Class<T> clazz, TableSchema schema, Supplier<T> allocator) WARNING: Experimental APIQueries data in descriptive format and reads result to a collection.queryRecords(String sqlQuery) Queries data in one of descriptive format and creates a reader out of the response stream.queryRecords(String sqlQuery, QuerySettings settings) Queries data in one of descriptive format and creates a reader out of the response stream.queryRecords(String sqlQuery, Map<String, Object> params) queryRecords(String sqlQuery, Map<String, Object> params, QuerySettings settings) Queries data in one of descriptive format and creates a reader out of the response stream.voidregister(Class<?> clazz, TableSchema schema) Registers a POJO class and maps its fields to a table schemavoidsetDBRoles(Collection<String> dbRoles) Sets list of DB roles that should be applied to each query.toString()voidupdateBearerToken(String bearer) voidupdateClientName(String name)
-
Field Details
-
clientVersion
-
CLIENT_USER_AGENT
- See Also:
-
VALUES_LIST_DELIMITER
- See Also:
-
-
Method Details
-
loadServerInfo
public void loadServerInfo()Loads essential information about a server. Should be called after client creation. -
getDefaultDatabase
Returns default database name that will be used by operations if not specified.- Returns:
- String - actual default database name.
-
close
public void close()Frees the resources associated with the client.- Shuts down the shared operation executor by calling
shutdownNow()
- Specified by:
closein interfaceAutoCloseable
- Shuts down the shared operation executor by calling
-
ping
public boolean ping()Pings the server to check if it is alive- Returns:
- true if the server is alive, false otherwise
-
ping
public boolean ping(long timeout) Pings the server to check if it is alive. Maximum timeout is 10 minutes.- Parameters:
timeout- timeout in milliseconds- Returns:
- true if the server is alive, false otherwise
-
register
Registers a POJO class and maps its fields to a table schema
Note: table schema will be stored in cache to be used while other operations. Cache key is
schemaId. Call this method to update cache.- Parameters:
clazz- - class of a POJOschema- - correlating table schema
-
insert
Sends write request to database. List of objects is converted into a most suitable format then it is sent to a server. Members of the list must be pre-registered using
register(Class, TableSchema)method:client.register(SamplePOJO.class, tableSchema); List<Object> input = new ArrayList<>(); // ... Insert some items into input list Future<InsertResponse> response = client.insert(tableName, simplePOJOs, settings);- Parameters:
tableName- - destination table namedata- - data stream to insert- Returns:
CompletableFuture<InsertResponse>- a promise to insert response
-
insert
public CompletableFuture<InsertResponse> insert(String tableName, List<?> data, InsertSettings settings) Sends write request to database. List of objects is converted into a most suitable format then it is sent to a server. Members of the list must be pre-registered using
register(Class, TableSchema)method:client.register(SamplePOJO.class, tableSchema); List<Object> input = new ArrayList<>(); // ... Insert some items into input list Future<InsertResponse> response = client.insert(tableName, simplePOJOs, settings);- Parameters:
tableName- - destination table namedata- - data stream to insertsettings- - insert operation settings- Returns:
CompletableFuture<InsertResponse>- a promise to insert response- Throws:
IllegalArgumentException- when data is empty or not registered
-
insert
public CompletableFuture<InsertResponse> insert(String tableName, InputStream data, ClickHouseFormat format) Sends write request to database. Input data is read from the input stream.
- Parameters:
tableName- - destination table namedata- - data stream to insertformat- - format of the data in the stream- Returns:
CompletableFuture<InsertResponse>- a promise to insert response
-
insert
public CompletableFuture<InsertResponse> insert(String tableName, InputStream data, ClickHouseFormat format, InsertSettings settings) Sends write request to database. Input data is read from the input stream.- Parameters:
tableName- - destination table namedata- - data stream to insertformat- - format of the data in the streamsettings- - insert operation settings- Returns:
CompletableFuture<InsertResponse>- a promise to insert response
-
insert
public CompletableFuture<InsertResponse> insert(String tableName, DataStreamWriter writer, ClickHouseFormat format, InsertSettings settings) Does an insert request to a server. Data is pushed when aDataStreamWriter.onOutput(OutputStream)is called.- Parameters:
tableName- - target table namewriter- -DataStreamWriterimplementationformat- - source formatsettings- - operation settings- Returns:
CompletableFuture<InsertResponse>- a promise to insert response
-
query
Sends SQL query to server. Default settings are applied.- Parameters:
sqlQuery- - complete SQL query.- Returns:
CompletableFuture<QueryResponse>- a promise to query response.
-
query
Sends SQL query to server.
Notes:- Server response format can be specified thru `settings` or in SQL query.
- If specified in both, the `sqlQuery` will take precedence.
- Parameters:
sqlQuery- - complete SQL query.settings- - query operation settings.- Returns:
CompletableFuture<QueryResponse>- a promise to query response.
-
query
public CompletableFuture<QueryResponse> query(String sqlQuery, Map<String, Object> queryParams, QuerySettings settings) Sends SQL query to server with parameters. The map `queryParams` should contain keys that match the placeholders in the SQL query.
For a parametrized query like:
SELECT * FROM table WHERE int_column = {id:UInt8} and string_column = {phrase:String}Code to set the queryParams would be:
Notes:Map<String, Object> queryParams = new HashMap<>(); queryParams.put("id", 1); queryParams.put("phrase", "hello");- Server response format can be specified thru
settingsor in SQL query. - If specified in both, the
sqlQuerywill take precedence.
- Parameters:
sqlQuery- - complete SQL query.settings- - query operation settings.queryParams- - query parameters that are sent to the server. (Optional)- Returns:
CompletableFuture<QueryResponse>- a promise to query response.
- Server response format can be specified thru
-
query
-
queryRecords
Queries data in one of descriptive format and creates a reader out of the response stream.
Format is selected internally so is ignored when passed in settings. If query contains format statement then it may cause incompatibility error.
- Parameters:
sqlQuery- - SQL statement- Returns:
- - a promise to a result
-
queryRecords
Queries data in one of descriptive format and creates a reader out of the response stream.
Format is selected internally so is ignored when passed in settings. If query contains format statement then it may cause incompatibility error.
- Parameters:
sqlQuery- - SQL statementsettings- - operation settings- Returns:
- - a promise to a result
-
queryRecords
public CompletableFuture<Records> queryRecords(String sqlQuery, Map<String, Object> params, QuerySettings settings) Queries data in one of descriptive format and creates a reader out of the response stream.
Format is selected internally so is ignored when passed in settings. If query contains format statement then it may cause incompatibility error.
Seequery(String, Map, QuerySettings)for parametrized queries.- Parameters:
sqlQuery- - SQL statementparams- - sql parameterssettings- - operation settings- Returns:
- - a promise to a result
-
queryRecords
-
queryAll
public List<GenericRecord> queryAll(String sqlQuery, Map<String, Object> params, QuerySettings settings) Queries data in descriptive format and reads result to a collection.
Use this method for queries that would return only a few records only because client will read whole dataset and convert it into a list of GenericRecord
Seequery(String, Map, QuerySettings)for parametrized queries.- Parameters:
sqlQuery- - SQL statementparams- - query parameterssettings- - operation settings- Returns:
- - complete list of records
-
queryAll
-
queryAll
-
queryAll
-
queryAll
-
queryAll
public <T> List<T> queryAll(String sqlQuery, Class<T> clazz, TableSchema schema, Supplier<T> allocator) WARNING: Experimental APIQueries data and returns collection with whole result. Data is read directly to a DTO to save memory on intermediate structures. DTO will be instantiated with default constructor or by using allocator
classshould be registered before calling this method usingregister(Class, TableSchema)Internally deserializer is compiled at the register stage. Compilation is done using ASM library by writing a bytecode
Note: this method will cache schema and it will use sql as a key for storage.
- Type Parameters:
T-- Parameters:
sqlQuery- - query to executeclazz- - class of the DTOallocator- - optional supplier to create new instances of the DTO.- Returns:
- List of POJOs filled with data
- Throws:
IllegalArgumentException- when class is not registered or no setters found
-
getTableSchema
Fetches schema of a table and returns complete information about each column. Information includes column name, type, default value, etc.
- Parameters:
table- - table name- Returns:
TableSchema- Schema of the table
-
getTableSchema
Fetches schema of a table and returns complete information about each column. Information includes column name, type, default value, etc.
- Parameters:
table- - table namedatabase- - database name- Returns:
TableSchema- Schema of the table
-
getTableSchemaFromQuery
Creates table schema from a query.
- Parameters:
sql- - SQL query which schema to return- Returns:
- table schema for the query
-
execute
Executes a SQL command and doesn't care response. Useful for DDL statements, like `CREATE`, `DROP`, `ALTER`. Method however returns execution errors from a server or summary in case of successful execution.
- Parameters:
sql- - SQL commandsettings- - execution settings- Returns:
CompletableFuture<CommandResponse>- a promise to command response
-
execute
Executes a SQL command and doesn't care response. Useful for DDL statements, like `CREATE`, `DROP`, `ALTER`. Method however returns execution errors from a server or summary in case of successful execution.
- Parameters:
sql- - SQL command- Returns:
CompletableFuture<CommandResponse>- a promise to command response
-
newBinaryFormatReader
public ClickHouseBinaryFormatReader newBinaryFormatReader(QueryResponse response, TableSchema schema) Create an instance of
ClickHouseBinaryFormatReaderbased on response. Table schema is option and only required forClickHouseFormat.RowBinaryWithNames,ClickHouseFormat.RowBinary. FormatClickHouseFormat.RowBinaryWithDefaultsis not supported for output (read operations).- Parameters:
response-schema-- Returns:
-
newBinaryFormatReader
-
toString
-
getConfiguration
Returns unmodifiable map of configuration options.- Returns:
- - configuration options
-
getOperationTimeout
protected int getOperationTimeout()Returns operation timeout in seconds -
getEndpoints
Returns unmodifiable set of endpoints.- Returns:
- - set of endpoints
-
getUser
-
getServerVersion
-
getClientVersion
-
setDBRoles
Sets list of DB roles that should be applied to each query.- Parameters:
dbRoles-
-
updateClientName
-
getDBRoles
Returns list of DB roles that should be applied to each query.- Returns:
- List of DB roles
-
updateBearerToken
-