Class Client

java.lang.Object
com.clickhouse.client.api.Client
All Implemented Interfaces:
AutoCloseable

public class Client extends Object implements 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.

  • Field Details

  • Method Details

    • loadServerInfo

      public void loadServerInfo()
      Loads essential information about a server. Should be called after client creation.
    • getDefaultDatabase

      public String 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:
      close in interface AutoCloseable
    • 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

      public void register(Class<?> clazz, TableSchema schema)

      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 POJO
      schema - - correlating table schema
    • insert

      public CompletableFuture<InsertResponse> insert(String tableName, List<?> data)

      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 name
      data - - 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 name
      data - - data stream to insert
      settings - - 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 name
      data - - data stream to insert
      format - - 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 name
      data - - data stream to insert
      format - - format of the data in the stream
      settings - - 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 a DataStreamWriter.onOutput(OutputStream) is called.
      Parameters:
      tableName - - target table name
      writer - - DataStreamWriter implementation
      format - - source format
      settings - - operation settings
      Returns:
      CompletableFuture<InsertResponse> - a promise to insert response
    • query

      public CompletableFuture<QueryResponse> query(String sqlQuery)
      Sends SQL query to server. Default settings are applied.
      Parameters:
      sqlQuery - - complete SQL query.
      Returns:
      CompletableFuture<QueryResponse> - a promise to query response.
    • query

      public CompletableFuture<QueryResponse> query(String sqlQuery, QuerySettings settings)

      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:

      
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("id", 1);
            queryParams.put("phrase", "hello");
            
       
      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.
      queryParams - - query parameters that are sent to the server. (Optional)
      Returns:
      CompletableFuture<QueryResponse> - a promise to query response.
    • query

      public CompletableFuture<QueryResponse> query(String sqlQuery, Map<String,Object> queryParams)
    • queryRecords

      public CompletableFuture<Records> queryRecords(String sqlQuery)

      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

      public CompletableFuture<Records> queryRecords(String sqlQuery, 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.

      Parameters:
      sqlQuery - - SQL statement
      settings - - 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.

      See query(String, Map, QuerySettings) for parametrized queries.
      Parameters:
      sqlQuery - - SQL statement
      params - - sql parameters
      settings - - operation settings
      Returns:
      - a promise to a result
    • queryRecords

      public CompletableFuture<Records> queryRecords(String sqlQuery, Map<String,Object> params)
    • 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

      See query(String, Map, QuerySettings) for parametrized queries.
      Parameters:
      sqlQuery - - SQL statement
      params - - query parameters
      settings - - operation settings
      Returns:
      - complete list of records
    • queryAll

      public List<GenericRecord> queryAll(String sqlQuery, QuerySettings settings)
    • queryAll

      public List<GenericRecord> queryAll(String sqlQuery, Map<String,Object> params)
    • queryAll

      public List<GenericRecord> queryAll(String sqlQuery)
    • queryAll

      public <T> List<T> queryAll(String sqlQuery, Class<T> clazz, TableSchema schema)
    • queryAll

      public <T> List<T> queryAll(String sqlQuery, Class<T> clazz, TableSchema schema, Supplier<T> allocator)
      WARNING: Experimental API

      Queries 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

      class should be registered before calling this method using register(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 execute
      clazz - - class of the DTO
      allocator - - 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

      public TableSchema getTableSchema(String table)

      Fetches schema of a table and returns complete information about each column. Information includes column name, type, default value, etc.

      See register(Class, TableSchema)

      Parameters:
      table - - table name
      Returns:
      TableSchema - Schema of the table
    • getTableSchema

      public TableSchema getTableSchema(String table, String database)

      Fetches schema of a table and returns complete information about each column. Information includes column name, type, default value, etc.

      See register(Class, TableSchema)

      Parameters:
      table - - table name
      database - - database name
      Returns:
      TableSchema - Schema of the table
    • getTableSchemaFromQuery

      public TableSchema getTableSchemaFromQuery(String sql)

      Creates table schema from a query.

      Parameters:
      sql - - SQL query which schema to return
      Returns:
      table schema for the query
    • execute

      public CompletableFuture<CommandResponse> execute(String sql, CommandSettings settings)

      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
      settings - - execution settings
      Returns:
      CompletableFuture<CommandResponse> - a promise to command response
    • execute

      public CompletableFuture<CommandResponse> execute(String sql)

      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 ClickHouseBinaryFormatReader based on response. Table schema is option and only required for ClickHouseFormat.RowBinaryWithNames, ClickHouseFormat.RowBinary. Format ClickHouseFormat.RowBinaryWithDefaults is not supported for output (read operations).

      Parameters:
      response -
      schema -
      Returns:
    • newBinaryFormatReader

      public ClickHouseBinaryFormatReader newBinaryFormatReader(QueryResponse response)
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • getConfiguration

      public Map<String,String> getConfiguration()
      Returns unmodifiable map of configuration options.
      Returns:
      - configuration options
    • getOperationTimeout

      protected int getOperationTimeout()
      Returns operation timeout in seconds
    • getEndpoints

      public Set<String> getEndpoints()
      Returns unmodifiable set of endpoints.
      Returns:
      - set of endpoints
    • getUser

      public String getUser()
    • getServerVersion

      public String getServerVersion()
    • getClientVersion

      public String getClientVersion()
    • setDBRoles

      public void setDBRoles(Collection<String> dbRoles)
      Sets list of DB roles that should be applied to each query.
      Parameters:
      dbRoles -
    • updateClientName

      public void updateClientName(String name)
    • getDBRoles

      public Collection<String> getDBRoles()
      Returns list of DB roles that should be applied to each query.
      Returns:
      List of DB roles
    • updateBearerToken

      public void updateBearerToken(String bearer)