### Complete Client Implementation Example Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/endpoint.md A full example demonstrating client initialization with primary and backup endpoints, connection verification, and error handling. ```cpp #include #include namespace ch = clickhouse; int main() { ch::ClientOptions opts; // Set primary endpoint opts.SetHost("ch-primary.example.com") .SetPort(9000) .SetUser("analytics") .SetPassword("secret"); // Set backup endpoints std::vector backups{ {"ch-backup-1.example.com", 9000}, {"ch-backup-2.example.com", 9000}, {"ch-backup-3.example.com", 9000} }; opts.SetEndpoints(backups); try { ch::Client client(opts); // Show which endpoint we connected to if (auto ep = client.GetCurrentEndpoint()) { std::cout << "Connected to: " << ep->host << ":" << ep->port << "\n"; } // Execute query ch::Query q("SELECT COUNT(*) FROM events"); client.Execute(q); } catch (const ch::ProtocolError& e) { std::cerr << "Failed to connect to any endpoint: " << e.what() << "\n"; return 1; } catch (const ch::Error& e) { std::cerr << "Error: " << e.what() << "\n"; return 1; } return 0; } ``` -------------------------------- ### Interactive Query Execution Example Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Demonstrates starting a select query and iterating through result blocks. ```cpp client.BeginSelect("SELECT * FROM table"); while (auto block = client.NextBlock()) { // process block } ``` -------------------------------- ### Production Configuration Example Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/configuration.md A comprehensive example combining connection, failover, compression, retry, TCP, timeout, and TLS settings. ```cpp ch::ClientOptions opts; // Connection opts.SetHost("clickhouse.example.com") .SetPort(9440) .SetDefaultDatabase("analytics") .SetUser("data_analyst") .SetPassword("secure_password"); // Add failover endpoints opts.SetEndpoints({ {{"clickhouse-backup1.example.com", 9440}}, {{"clickhouse-backup2.example.com", 9440}} }); // Compression opts.SetCompressionMethod(ch::CompressionMethod::ZSTD) .SetMaxCompressionChunkSize(131072); // Retries opts.SetSendRetries(3) .SetRetryTimeout(std::chrono::seconds(5)) .SetPingBeforeQuery(true); // TCP options opts.TcpKeepAlive(true) .SetTcpKeepAliveIdle(std::chrono::seconds(60)) .SetTcpKeepAliveInterval(std::chrono::seconds(15)) .SetTcpKeepAliveCount(9) .TcpNoDelay(true); // Timeouts opts.SetConnectionConnectTimeout(std::chrono::seconds(10)) .SetConnectionRecvTimeout(std::chrono::seconds(300)) .SetConnectionSendTimeout(std::chrono::seconds(300)); // TLS with custom CA ch::ClientOptions::SSLOptions ssl_opts; ssl_opts.SetPathToCAFiles({ "/etc/ssl/certs/company-ca.crt" }) .SetUseSNI(true); opts.SetSSLOptions(ssl_opts); // Error handling opts.SetRethrowException(true); ch::Client client(opts); ``` -------------------------------- ### Initialize Client with Options Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Example of configuring and instantiating a Client instance. ```cpp #include namespace ch = clickhouse; int main() { ch::ClientOptions opts; opts.SetHost("localhost").SetPort(9000).SetUser("default"); ch::Client client(opts); // client is ready to use } ``` -------------------------------- ### Install header files Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/clickhouse/CMakeLists.txt Installs the library header files to the specified include directory. ```cmake INSTALL(FILES types/bignum.h DESTINATION include/clickhouse/types/) INSTALL(FILES types/type_parser.h DESTINATION include/clickhouse/types/) INSTALL(FILES types/types.h DESTINATION include/clickhouse/types/) ``` -------------------------------- ### Usage of ColumnArray Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Example showing how to instantiate and populate a ColumnArray. ```cpp auto col_int = std::make_shared(); auto col_array = std::make_shared(col_int); col_int->Append(1); col_int->Append(2); col_int->Append(3); col_array->Append(...); ``` -------------------------------- ### Initialize Endpoints Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/endpoint.md Examples of initializing Endpoint objects with various host formats. ```cpp ch::Endpoint ep1{"clickhouse.example.com"}; ch::Endpoint ep2{"192.168.1.100"}; ch::Endpoint ep3{"::1", 9000}; ``` -------------------------------- ### Usage of ColumnArrayT Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Example showing how to instantiate a typed ColumnArrayT. ```cpp auto nested = std::make_shared(); auto col = std::make_shared>(nested); ``` -------------------------------- ### Configure Endpoints for Various Environments Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/endpoint.md Examples for setting up client endpoints for local development, production, TLS-enabled clusters, and Kubernetes service discovery. ```cpp ch::Endpoint ep{"localhost", 9000}; // or ch::ClientOptions opts; opts.SetHost("localhost").SetPort(9000); ``` ```cpp ch::Endpoint ep{"clickhouse.prod.example.com", 9000}; ``` ```cpp ch::ClientOptions opts; opts.SetHost("ch-0.clickhouse.example.com") .SetPort(9440) .SetEndpoints({ {{"ch-1.clickhouse.example.com", 9440}}, {{"ch-2.clickhouse.example.com", 9440}}, {{"ch-3.clickhouse.example.com", 9440}} }); ch::ClientOptions::SSLOptions ssl_opts; ssl_opts.SetUseDefaultCALocations(true); opts.SetSSLOptions(ssl_opts); ``` ```cpp // Connect to ClickHouse cluster via Kubernetes service ch::ClientOptions opts; opts.SetHost("clickhouse.default.svc.cluster.local") .SetPort(9000); ``` -------------------------------- ### Basic C++ Application Example Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/README.md A simple application demonstrating how to connect to a ClickHouse instance and execute a query. ```cpp #include #include namespace ch = clickhouse; int main() { ch::Client client{ch::ClientOptions{}.SetHost("localhost")}; client.BeginSelect("SELECT 'Hello from ClickHouse :)"); while (auto block = client.NextBlock()) { auto col_msg = block->At(0)->AsStrict(); for (size_t i = 0; i < block->GetRowCount(); ++i) { std::cout << col_msg->At(i) << "\n"; } } } ``` -------------------------------- ### BeginExecute Method Signature Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Starts execution of a query for interactive reading. This is an experimental API. ```cpp void BeginExecute(const Query& query); ``` -------------------------------- ### Example Server Information Output Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/server-info.md Sample data structures representing server information for different ClickHouse versions. ```text name: "ClickHouse" timezone: "UTC" display_name: "ClickHouse 24.8.4 release" version_major: 24 version_minor: 8 version_patch: 4 revision: 54474 (approx) ``` ```text name: "ClickHouse" timezone: "UTC" display_name: "ClickHouse 23.11.1.1 release" version_major: 23 version_minor: 11 version_patch: 1 revision: 54380 (approx) ``` -------------------------------- ### ColumnString Usage Example Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Demonstrates appending strings and iterating through a ColumnString instance. ```cpp auto col_str = std::make_shared(); col_str->Append("Hello"); col_str->Append("World"); col_str->Append("ClickHouse"); for (size_t i = 0; i < col_str->Size(); ++i) { std::cout << col_str->At(i) << "\n"; } ``` -------------------------------- ### BeginExecute(const Query& query) Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Starts execution of a query for interactive reading with NextBlock(). ```APIDOC ## void BeginExecute(const Query& query) ### Description Starts execution of a query for interactive reading with NextBlock(). This is an experimental API. ### Parameters - **query** (const Query&) - Required - Query to execute ``` -------------------------------- ### Configure Port for Protocols Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/endpoint.md Examples of setting ports for standard native protocol and TLS-encrypted connections. ```cpp ch::Endpoint ep1{"localhost", 9000}; // Native protocol ch::Endpoint ep2{"localhost", 9440}; // TLS ``` -------------------------------- ### ColumnFixedString Usage Example Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Demonstrates initializing a fixed-length string column and appending values. ```cpp auto col_fixed = std::make_shared(32); col_fixed->Append("abc"); col_fixed->Append("xyz"); ``` -------------------------------- ### Use numeric columns Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Example of creating and appending data to integer and floating-point columns. ```cpp auto col_int = std::make_shared(); col_int->Append(1); col_int->Append(2); col_int->Append(-3); std::cout << col_int->At(0) << "\n"; // 1 auto col_double = std::make_shared(); col_double->Append(3.14); col_double->Append(2.71); ``` -------------------------------- ### BeginInsert(const Query& query) Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Starts a batch insertion session. Returns a block pre-configured with the table's columns. Allows sending multiple batches before finishing with EndInsert(). ```APIDOC ## BeginInsert(const Query& query) ### Description Starts a batch insertion session. Returns a block pre-configured with the table's columns. Allows sending multiple batches before finishing with EndInsert(). ### Parameters - **query** (const Query& or const std::string&) - Required - INSERT statement ending with VALUES (no actual values) - **query_id** (const std::string&) - Optional - Unique query identifier ### Returns A Block with columns ready for data insertion. ### Throws - ValidationError if query has event callbacks set. ``` -------------------------------- ### Executing a Query with External Data Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Example showing how to construct an external table block and pass it to the client for a SELECT query. ```cpp auto ext_block = ch::Block(); ext_block.AppendColumn("id", std::make_shared()); auto col = ext_block[0]->As(); col->Append(1); ch::ExternalTables tables{{ch::ExternalTable{"ext_table", ext_block}}}; client.SelectWithExternalData( "SELECT * FROM ext_table", tables, [](const ch::Block& block) { /* handle result */ } ); ``` -------------------------------- ### BeginSelect(const Query& query) Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Alias for BeginExecute(). Starts interactive SELECT query execution. ```APIDOC ## void BeginSelect(const Query& query) ### Description Alias for BeginExecute(). Starts interactive SELECT query execution. ### Parameters - **query** (const Query&, const char*, or const std::string&) - Required - Query text or Query object - **query_id** (const std::string&) - Optional - Unique query identifier (Default: Query::default_query_id) ``` -------------------------------- ### Begin Batch Insertion Session (C++) Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Starts a session for multi-batch insertions. The query string must be an INSERT statement ending with VALUES. ```cpp Block BeginInsert(const Query& query); Block BeginInsert(const std::string& query, const std::string& query_id); ``` ```cpp auto block = client.BeginInsert("INSERT INTO users (id, name) VALUES"); auto col_id = block[0]->As(); auto col_name = block[1]->As(); col_id->Append(1); col_name->Append("Alice"); block.RefreshRowCount(); client.SendInsertBlock(block); // Send more batches block.Clear(); col_id->Append(2); col_name->Append("Bob"); block.RefreshRowCount(); client.SendInsertBlock(block); client.EndInsert(); ``` -------------------------------- ### Usage of ColumnNullable Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Example showing how to instantiate and append values to a ColumnNullable. ```cpp auto col_nested = std::make_shared(); auto col_nulls = std::make_shared(); auto col_nullable = std::make_shared(col_nested, col_nulls); col_nullable->Append(false); // Not null col_nullable->Append(true); // Null ``` -------------------------------- ### NextBlock Usage Example Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Retrieves result blocks and processes row counts. ```cpp client.BeginSelect("SELECT * FROM table"); while (auto block = client.NextBlock()) { size_t row_count = block->GetRowCount(); std::cout << "Got " << row_count << " rows\n"; } ``` -------------------------------- ### Full Iterator Usage Example Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/block.md Demonstrates accessing index, name, type, and column data during iteration. ```cpp ch::Block block; // ... populate block ... for (auto it = block.begin(); it != block.end(); ++it) { std::cout << "Index: " << it.ColumnIndex() << "\n"; std::cout << "Name: " << it.Name() << "\n"; std::cout << "Type: " << it.Type()->GetName() << "\n"; auto col = it.Column(); std::cout << "Size: " << col->Size() << "\n"; } ``` -------------------------------- ### Usage of ColumnNullableT Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Example showing how to use std::optional with ColumnNullableT. ```cpp auto nested = std::make_shared(); auto col = std::make_shared>(nested); col->Append(std::optional(42)); col->Append(std::optional{}); // null ``` -------------------------------- ### Get query settings Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Retrieves the current map of query settings. ```cpp const QuerySettings& GetQuerySettings() const; ``` -------------------------------- ### BeginSelect Method Signatures Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Alias for BeginExecute used to start interactive SELECT query execution. ```cpp void BeginSelect(const Query& query); void BeginSelect(const char* query); void BeginSelect(const std::string& query); void BeginSelect(const std::string& query, const std::string& query_id); ``` -------------------------------- ### Get query text Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Retrieves the SQL query text as a string reference. ```cpp const std::string& GetText() const; ``` -------------------------------- ### Configure Client Options Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Demonstrates setting up a secure client connection with SSL, compression, timeouts, and fallback endpoints. ```cpp #include #include #include namespace ch = clickhouse; int main() { // Create options with secure connection ch::ClientOptions opts; opts.SetHost("analytics.company.com") .SetPort(9440) .SetUser("data_analyst") .SetPassword("mypassword") .SetDefaultDatabase("metrics") .SetCompressionMethod(ch::CompressionMethod::LZ4) .SetConnectionConnectTimeout(std::chrono::seconds(10)) .SetConnectionRecvTimeout(std::chrono::seconds(30)) .TcpKeepAlive(true); // Configure SSL ch::ClientOptions::SSLOptions ssl_opts; ssl_opts.SetUseDefaultCALocations(true) .SetUseSNI(true); opts.SetSSLOptions(ssl_opts); // Add fallback endpoints opts.SetEndpoints({ {{"backup1.company.com", 9440}}, {{"backup2.company.com", 9440}} }); try { ch::Client client(opts); client.Ping(); std::cout << "Connected successfully\n"; } catch (const ch::OpenSSLError& e) { std::cerr << "SSL error: " << e.what() << "\n"; } catch (const ch::ProtocolError& e) { std::cerr << "Connection error: " << e.what() << "\n"; } return 0; } ``` -------------------------------- ### Execute Query with Callbacks and Settings in C++ Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Demonstrates configuring a client, setting query parameters, applying settings, and registering progress/data callbacks. ```cpp #include #include namespace ch = clickhouse; int main() { ch::ClientOptions opts; opts.SetHost("localhost").SetUser("default"); ch::Client client(opts); // Create a query with callbacks and settings ch::Query q("SELECT user_id, COUNT(*) as cnt FROM events GROUP BY user_id LIMIT ?"); // Set parameter q.SetParam("limit_value", std::optional("100")); // Set query settings q.SetSetting("max_rows_to_read", ch::QuerySettingsField{"1000000", 0}); // Set callbacks q.OnData([](const ch::Block& block) { std::cout << "Got " << block.GetRowCount() << " rows\n"; }) .OnProgress([](const ch::Progress& progress) { std::cout << "Read " << progress.rows << " rows so far\n"; }) .OnProfile([](const ch::Profile& profile) { std::cout << "Profile: " << profile.rows << " rows in " << profile.blocks << " blocks\n"; }); try { client.Execute(q); } catch (const ch::ServerException& e) { std::cerr << "Query failed: " << e.what() << "\n"; } return 0; } ``` -------------------------------- ### HasEventCallbacks() Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Checks if any event callbacks are currently installed on the query object. ```APIDOC ## HasEventCallbacks() const ### Description Checks if any event callbacks are installed. ### Signature `bool HasEventCallbacks() const;` ### Returns `bool` - `true` if any callback is set, `false` if all callbacks are empty. ``` -------------------------------- ### Configure Authentication and Database Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Sets credentials and the default database for the client session. ```cpp ch::ClientOptions opts; opts.SetUser("analyst") .SetPassword("secret123") .SetDefaultDatabase("analytics"); ``` -------------------------------- ### Get query parameters Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Retrieves the current map of query parameters. ```cpp const QueryParams& GetParams() const; ``` -------------------------------- ### Retrieve Server Information with C++ Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/server-info.md Demonstrates establishing a client connection and accessing the ServerInfo object to print server details. ```cpp #include #include namespace ch = clickhouse; int main() { ch::ClientOptions opts; opts.SetHost("localhost").SetPort(9000); ch::Client client(opts); const auto& info = client.GetServerInfo(); std::cout << "Connected to: " << info.display_name << "\n" << "Version: " << info.version_major << "." << info.version_minor << "." << info.version_patch << "\n" << "Revision: " << info.revision << "\n" << "Timezone: " << info.timezone << "\n"; return 0; } ``` -------------------------------- ### Load ClientOptions from Environment Variables Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/configuration.md Wraps ClientOptions creation to populate connection settings from environment variables with fallback defaults. ```cpp #include #include #include ch::ClientOptions LoadFromEnvironment() { auto get_env = [](const char* key, const char* default_val = "") { const char* val = std::getenv(key); return val ? std::string(val) : std::string(default_val); }; ch::ClientOptions opts; opts.SetHost(get_env("CLICKHOUSE_HOST", "localhost")) .SetPort(std::stoi(get_env("CLICKHOUSE_PORT", "9000"))) .SetUser(get_env("CLICKHOUSE_USER", "default")) .SetPassword(get_env("CLICKHOUSE_PASSWORD", "")) .SetDefaultDatabase(get_env("CLICKHOUSE_DATABASE", "default")); if (get_env("CLICKHOUSE_COMPRESSION", "") == "lz4") { opts.SetCompressionMethod(ch::CompressionMethod::LZ4); } return opts; } int main() { auto opts = LoadFromEnvironment(); ch::Client client(opts); // ... } ``` -------------------------------- ### Configuring Compression Methods Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/README.md Defines available compression methods and shows how to apply them to client options. ```cpp enum class CompressionMethod : int8_t { None = -1, // No compression (default) LZ4 = 1, // LZ4 compression ZSTD = 2, // Zstandard compression }; // Usage opts.SetCompressionMethod(ch::CompressionMethod::LZ4); opts.SetMaxCompressionChunkSize(131072); // 128 KB chunks ``` -------------------------------- ### Initialize ClickHouse Client Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/docs/index.mdx Establish a connection to a ClickHouse instance using ClientOptions. ```cpp #include clickhouse::Client client{clickhouse::ClientOptions().SetHost("localhost")}; ``` ```cpp #include clickhouse::Client client{ clickhouse::ClientOptions{} .SetHost("your.instance.clickhouse.cloud") .SetUser("default") .SetPassword("your-password") .SetSSLOptions({}) // Enable SSL .SetPort(9440) // for connections over SSL ClickHouse Cloud uses port 9440 }; ``` -------------------------------- ### Get OpenTelemetry Tracing Context Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Retrieves the current tracing context if it has been set. ```cpp const std::optional& GetTracingContext() const; ``` -------------------------------- ### Retrieve and display server information in C++ Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/server-info.md Demonstrates connecting to a server and accessing the ServerInfo object to retrieve version, timezone, and display name details. ```cpp #include #include #include namespace ch = clickhouse; std::string FormatVersion(const ch::ServerInfo& info) { std::stringstream ss; ss << info.version_major << "." << info.version_minor << "." << info.version_patch; return ss.str(); } int main() { ch::ClientOptions opts; opts.SetHost("analytics.example.com") .SetPort(9440) .SetUser("analyst"); try { ch::Client client(opts); const auto& info = client.GetServerInfo(); std::cout << "=== ClickHouse Server Information ===\n" << "Display Name: " << info.display_name << "\n" << "Version: " << FormatVersion(info) << "\n" << "Revision: " << info.revision << "\n" << "Timezone: " << info.timezone << "\n" << "Name: " << info.name << "\n"; // Compatibility check if (info.version_major < 21) { std::cerr << "Warning: This application requires ClickHouse 21+\n"; } } catch (const ch::Error& e) { std::cerr << "Connection error: " << e.what() << "\n"; return 1; } return 0; } ``` -------------------------------- ### Define and Populate Columns in C++ Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Demonstrates creating various column types, appending data, and iterating through a block of columns. ```cpp #include #include namespace ch = clickhouse; int main() { // Create columns auto col_id = std::make_shared(); auto col_name = std::make_shared(); auto col_tags = std::make_shared( std::make_shared() ); auto col_score = std::make_shared >>(std::make_shared>()); // Add data col_id->Append(1); col_name->Append("Alice"); col_score->Append(std::optional(95.5f)); col_id->Append(2); col_name->Append("Bob"); col_score->Append(std::optional{}); // NULL // Create block ch::Block block; block.AppendColumn("id", col_id); block.AppendColumn("name", col_name); block.AppendColumn("score", col_score); // Print results for (size_t i = 0; i < block.GetRowCount(); ++i) { auto ids = block[0]->AsStrict(); auto names = block[1]->AsStrict(); std::cout << ids->At(i) << ": " << names->At(i) << "\n"; } return 0; } ``` -------------------------------- ### Get query ID Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Retrieves the unique query ID assigned to the query instance. ```cpp const std::string& GetQueryID() const; ``` -------------------------------- ### Client Constructor Signature Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Standard constructor for initializing a client with configuration options. ```cpp Client(const ClientOptions& opts); ``` -------------------------------- ### Retrieve column count Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/block.md Get the total number of columns currently stored in the block. ```cpp std::cout << "Block has " << block.GetColumnCount() << " columns\n"; ``` -------------------------------- ### EndInsert() Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Finalizes an INSERT session started with BeginInsert(). Must be called after all batches are sent. ```APIDOC ## EndInsert() ### Description Finalizes an INSERT session started with BeginInsert(). Must be called after all batches are sent. ### Throws - ProtocolError on protocol violations. ``` -------------------------------- ### Establish TLS connections Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/README.md Configure SSLOptions with CA file paths and SNI settings to secure the client connection. ```cpp ch::ClientOptions opts; opts.SetHost("secure.example.com").SetPort(9440); ch::ClientOptions::SSLOptions ssl_opts; ssl_opts.SetPathToCAFiles({"/etc/ssl/certs/ca.crt"}) .SetUseSNI(true); opts.SetSSLOptions(ssl_opts); ch::Client client(opts); ``` -------------------------------- ### Configure Client with Builder Pattern Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/configuration.md Use the ClientOptions builder to chain setter methods for configuring connection parameters before initializing the client. ```cpp ch::ClientOptions opts; opts.SetHost("localhost") .SetPort(9000) .SetUser("default") .SetPassword("password") .SetDefaultDatabase("mydb"); ch::Client client(opts); ``` -------------------------------- ### Configure SSL with Default CA Locations Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Initializes a client with default CA locations for SSL verification. ```cpp ch::ClientOptions opts; opts.SetHost("secure.clickhouse.example.com") .SetPort(9440); opts.SetSSLOptions(ch::ClientOptions::SSLOptions{}); ch::Client client(opts); ``` -------------------------------- ### SendInsertBlock(const Block& block) Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Sends a batch of data during an INSERT session started with BeginInsert(). ```APIDOC ## SendInsertBlock(const Block& block) ### Description Sends a batch of data during an INSERT session started with BeginInsert(). ### Parameters - **block** (const Block&) - Required - Block with data to send ### Throws - ProtocolError on transmission errors. ``` -------------------------------- ### Insert Data Using Block API Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/block.md Demonstrates initializing a client, defining a block schema with columns, appending rows, and performing an insert operation. ```cpp #include #include namespace ch = clickhouse; int main() { ch::ClientOptions opts; opts.SetHost("localhost").SetUser("default"); ch::Client client(opts); // Create block structure ch::Block block; auto col_id = std::make_shared(); auto col_name = std::make_shared(); auto col_age = std::make_shared(); block.AppendColumn("id", col_id); block.AppendColumn("name", col_name); block.AppendColumn("age", col_age); // Add rows col_id->Append(1); col_name->Append("Alice"); col_age->Append(30); col_id->Append(2); col_name->Append("Bob"); col_age->Append(25); col_id->Append(3); col_name->Append("Charlie"); col_age->Append(35); // Insert into ClickHouse try { client.Insert("users", block); std::cout << "Inserted " << block.GetRowCount() << " rows\n"; } catch (const ch::ServerException& e) { std::cerr << "Insert failed: " << e.what() << "\n"; } return 0; } ``` -------------------------------- ### Configure query parameters and settings Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/README.md Bind parameters using SetParam and apply query-specific settings via SetSetting before execution. ```cpp ch::Query q("SELECT * FROM events WHERE date >= ? AND status = ?"); // Set parameters q.SetParam("date", std::optional("2024-01-01")) .SetParam("status", std::optional("active")); // Set query settings q.SetSetting("max_rows_to_read", ch::QuerySettingsField{"1000000", 0}); q.SetSetting("read_overflow_mode", ch::QuerySettingsField{"throw", 0}); client.Execute(q); ``` -------------------------------- ### Check for Event Callbacks in C++ Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Verifies if any event callbacks are currently installed. This is primarily used for internal validation during BeginInsert operations. ```cpp bool HasEventCallbacks() const; ``` -------------------------------- ### Configure TCP Socket Options Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Demonstrates how to enable TCP keep-alive and customize its probe intervals and count using ClientOptions. ```cpp ch::ClientOptions opts; opts.TcpKeepAlive(true) .SetTcpKeepAliveIdle(std::chrono::seconds(30)) .SetTcpKeepAliveInterval(std::chrono::seconds(10)) .SetTcpKeepAliveCount(5); ``` -------------------------------- ### Configure Host and Port Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Sets the primary connection target using the builder pattern. ```cpp ch::ClientOptions opts; opts.SetHost("clickhouse.example.com").SetPort(9000); ``` -------------------------------- ### Configure Query Retry Settings Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Demonstrates how to enable server pings and adjust retry behavior for network requests. ```cpp ch::ClientOptions opts; opts.SetPingBeforeQuery(true) .SetSendRetries(3) .SetRetryTimeout(std::chrono::seconds(10)); ``` -------------------------------- ### Integrate with FetchContent Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/README.md Configuration for downloading and linking the library automatically during CMake configuration. ```cmake cmake_minimum_required(VERSION 3.14) project(application-example LANGUAGES CXX) include(FetchContent) set(CH_USE_ABSEIL_FOR_BIGNUM OFF) set(CH_MAP_BOOL_TO_UINT8 OFF) FetchContent_Declare( clickhouse_cpp GIT_REPOSITORY https://github.com/ClickHouse/clickhouse-cpp.git GIT_TAG v2.6.2 ) FetchContent_MakeAvailable(clickhouse_cpp) add_executable(application-example app.cpp) target_link_libraries(application-example PRIVATE clickhouse-cpp-lib) ``` -------------------------------- ### Default Client Configuration Values Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/configuration.md Lists the default settings for connection parameters, timeouts, and protocol options. ```text host = "" port = 9000 user = "default" password = "" default_database = "default" compression_method = None rethrow_exceptions = true ping_before_query = false send_retries = 1 retry_timeout = 5 seconds tcp_keepalive = false tcp_nodelay = true connection_connect_timeout = 5 seconds connection_recv_timeout = 0 (unlimited) connection_send_timeout = 0 (unlimited) ssl_options = std::nullopt (TLS disabled) ``` -------------------------------- ### Client(const ClientOptions& opts) Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Constructs a new ClickHouse client instance using the provided configuration options. ```APIDOC ## Client(const ClientOptions& opts) ### Description Constructs a client with the given options. Throws a ValidationError if SSL options are set but the library was built without SSL support. ### Parameters - **opts** (const ClientOptions&) - Required - Client configuration options (host, port, credentials, etc.) ### Example ```cpp #include namespace ch = clickhouse; int main() { ch::ClientOptions opts; opts.SetHost("localhost").SetPort(9000).SetUser("default"); ch::Client client(opts); } ``` -------------------------------- ### Connect and Query with ClickHouse C++ Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/README.md Establishes a connection to a ClickHouse instance and executes a query using a callback to process results. ```cpp #include #include namespace ch = clickhouse; int main() { // Configure connection ch::ClientOptions opts; opts.SetHost("localhost") .SetPort(9000) .SetUser("default"); // Create client ch::Client client(opts); // Execute query with callback client.Select("SELECT 'Hello from ClickHouse'", [](const ch::Block& block) { for (size_t i = 0; i < block.GetRowCount(); ++i) { auto col = block[0]->AsStrict(); std::cout << col->At(i) << "\n"; } }); return 0; } ``` -------------------------------- ### Initialize Query from std::string Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Creates a Query instance using a std::string for the SQL text and an optional query identifier. ```cpp Query(const std::string& query, const std::string& query_id = default_query_id); ``` ```cpp ch::Query q("SELECT * FROM users WHERE age > 18"); ch::Query q2("SELECT COUNT(*) FROM events", "query_count_events_123"); ``` -------------------------------- ### Create and verify ClickHouse types in C++ Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/types.md Demonstrates the creation of simple, string, array, and nullable types, along with equality checking and column vector usage. ```cpp #include #include namespace ch = clickhouse; int main() { // Create various types auto type_int = ch::Type::CreateSimple(); auto type_string = ch::Type::CreateString(); auto type_array = ch::Type::CreateArray(type_string); auto type_nullable = ch::Type::CreateNullable(type_int); std::cout << "Int32: " << type_int->GetName() << "\n"; std::cout << "String: " << type_string->GetName() << "\n"; std::cout << "Array(String): " << type_array->GetName() << "\n"; std::cout << "Nullable(Int32): " << type_nullable->GetName() << "\n"; // Check type equality auto type_int2 = ch::Type::CreateSimple(); if (*type_int == *type_int2) { std::cout << "Types are equal\n"; } // Use with columns auto column = std::make_shared>(); column->Append(42); return 0; } ``` -------------------------------- ### Initialize Query from C string Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Creates a Query instance using a C-style string for the SQL text and an optional query identifier. ```cpp Query(const char* query, const char* query_id = nullptr); ``` -------------------------------- ### Include clickhouse-cpp with CMake FetchContent Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/docs/index.mdx Use the FetchContent module to download and build the library as part of your CMake project. Enabling WITH_OPENSSL is recommended for TLS support. ```cmake include(FetchContent) set(WITH_OPENSSL YES CACHE BOOL "Enable OpenSSL in clickhouse-cpp" FORCE) FetchContent_Declare( clickhouse-cpp GIT_REPOSITORY https://github.com/ClickHouse/clickhouse-cpp.git GIT_TAG v2.6.0 # can also be `master` or other banch ) FetchContent_MakeAvailable(clickhouse-cpp) ``` -------------------------------- ### Create Test Executable and Link Libraries Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/ut/CMakeLists.txt Defines the executable target and links it against the library and Google Test. ```cmake ADD_EXECUTABLE (clickhouse-cpp-ut ${clickhouse-cpp-ut-src} ) TARGET_LINK_LIBRARIES (clickhouse-cpp-ut clickhouse-cpp-lib gtest-lib ) ``` -------------------------------- ### Execute Query with Client Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client.md Executes an arbitrary query using a configured Query object. Supports settings, parameters, and data callbacks. ```cpp void Execute(const Query& query); ``` ```cpp ch::Query query("SELECT 1"); query.OnData([](const ch::Block& block) { std::cout << "Received " << block.GetRowCount() << " rows\n"; }); client.Execute(query); ``` -------------------------------- ### GetQuerySettings() Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Retrieves all current query-specific settings. ```APIDOC ## GetQuerySettings() ### Description Returns all query settings. ### Signature `const QuerySettings& GetQuerySettings() const;` ### Returns - **QuerySettings** - Reference to QuerySettings map (alias for std::unordered_map). ``` -------------------------------- ### Select and Iterate Data Blocks in C++ Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/block.md Demonstrates executing a query and processing the resulting data blocks by iterating through columns and accessing specific column types. ```cpp #include #include namespace ch = clickhouse; int main() { ch::ClientOptions opts; opts.SetHost("localhost").SetUser("default"); ch::Client client(opts); // Execute query and process results ch::Query q("SELECT id, name, age FROM users LIMIT 10"); q.OnData([](const ch::Block& block) { std::cout << "Block with " << block.GetRowCount() << " rows:\n"; // Iterate over columns for (auto it = block.begin(); it != block.end(); ++it) { std::cout << " Column " << it.ColumnIndex() << ": " << it.Name() << " (" << it.Type()->GetName() << ")\n"; } // Or access by index if (block.GetColumnCount() >= 3) { auto ids = block[0]->AsStrict(); auto names = block[1]->AsStrict(); auto ages = block[2]->AsStrict(); for (size_t i = 0; i < block.GetRowCount(); ++i) { std::cout << " " << ids->At(i) << ": " << names->At(i) << " (age " << ages->At(i) << ")\n"; } } }); client.Execute(q); return 0; } ``` -------------------------------- ### Perform batch insertions Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/README.md Use BeginInsert to initialize a block, append data to columns, and finalize with SendInsertBlock and EndInsert. ```cpp auto block = client.BeginInsert("INSERT INTO users (id, name) VALUES"); auto col_id = block[0]->As(); auto col_name = block[1]->As(); for (int i = 0; i < 100; ++i) { col_id->Append(i); col_name->Append("user_" + std::to_string(i)); } block.RefreshRowCount(); client.SendInsertBlock(block); client.EndInsert(); ``` -------------------------------- ### Build clickhouse-cpp with CMake Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/README.md Recommended build commands for configuring and compiling the library with legacy defaults disabled. ```sh $ mkdir build . $ cd build $ cmake .. -DCH_USE_ABSEIL_FOR_BIGNUM=NO -DCH_MAP_BOOL_TO_UINT8=NO $ make ``` -------------------------------- ### Handling ServerException Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/errors.md Demonstrates catching a ServerException and accessing its error code, type, and stack trace. ```cpp try { ch::Query q("SELECT * FROM non_existent_table"); client.Execute(q); } catch (const ch::ServerException& e) { std::cerr << "Server error " << e.GetCode() << ": " << e.what() << "\n"; const auto& ex = e.GetException(); std::cerr << "Exception type: " << ex.name << "\n"; if (!ex.stack_trace.empty()) { std::cerr << "Stack trace:\n" << ex.stack_trace << "\n"; } } ``` -------------------------------- ### Initialize empty Query Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/query.md Creates a Query instance without initial text or identifier. ```cpp Query(); ``` -------------------------------- ### Thread Safety Implementation for Client Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/README.md Demonstrates the correct approach to handling Client instances in multi-threaded environments to avoid data corruption. ```cpp // WRONG - will corrupt data if used from multiple threads ch::Client client(opts); // RIGHT - create separate client per thread thread1: ch::Client client1(opts); thread2: ch::Client client2(opts); ``` -------------------------------- ### Perform batch insertion with clickhouse-cpp Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/README.md Use the BeginInsert, SendInsertBlock, and EndInsert pattern to manage large data sets efficiently without loading everything into memory at once. ```cpp // Start the insertion. auto block = client->BeginInsert("INSERT INTO foo (id, name) VALUES"); // Grab the columns from the block. auto col1 = block[0]->As(); auto col2 = block[1]->As(); // Add a couple of records to the block. col1.Append(1); col1.Append(2); col2.Append("holden"); col2.Append("naomi"); // Send those records. block.RefreshRowCount(); client->SendInsertBlock(block); block.Clear(); // Add another record. col1.Append(3); col2.Append("amos"); // Send it and finish. block.RefreshRowCount(); client->EndInsert(); ``` -------------------------------- ### Configure SSL with External Context Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Uses a pre-configured OpenSSL context for the client connection. ```cpp SSL_CTX* my_ctx = // ... your SSL_CTX setup ... ch::ClientOptions::SSLOptions ssl_opts; ssl_opts.SetExternalSSLContext(my_ctx); ch::ClientOptions opts; opts.SetHost("secure.clickhouse.example.com") .SetPort(9440) .SetSSLOptions(ssl_opts); ch::Client client(opts); ``` -------------------------------- ### Configure Single Endpoint Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/endpoint.md Sets a single host and port for the client connection using ClientOptions. ```cpp ch::ClientOptions opts; opts.SetHost("clickhouse.example.com") .SetPort(9000); ch::Client client(opts); ``` -------------------------------- ### ClientOptions Configuration Methods Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Methods available on the ch::ClientOptions object to configure client behavior. ```APIDOC ## ch::ClientOptions Configuration ### Description The `ch::ClientOptions` class provides a fluent interface to configure client behavior for error handling, query retries, and data compression. ### Methods #### Error Handling - **SetRethrowException(bool)**: If true, exceptions are thrown; if false, they are passed to the OnException handler. #### Query Retry Settings - **SetPingBeforeQuery(bool)**: If true, pings the server before executing each query. - **SetSendRetries(unsigned int)**: Sets the number of times to retry sending a request. - **SetRetryTimeout(std::chrono::seconds)**: Sets the wait time between retries. #### Compression - **SetCompressionMethod(CompressionMethod)**: Sets the compression algorithm (None, LZ4, or ZSTD). - **SetMaxCompressionChunkSize(unsigned int)**: Sets the maximum bytes to compress at once. ### Usage Example ```cpp ch::ClientOptions opts; opts.SetPingBeforeQuery(true) .SetSendRetries(3) .SetRetryTimeout(std::chrono::seconds(10)) .SetCompressionMethod(ch::CompressionMethod::LZ4) .SetMaxCompressionChunkSize(131072); ``` ``` -------------------------------- ### Client Class Interface Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/README.md Provides methods for executing queries, managing data insertion, and maintaining server connections. ```cpp class Client { Client(const ClientOptions& opts); // Queries void Execute(const Query& query); void Select(const std::string& query, SelectCallback cb); void BeginSelect(const std::string& query); std::optional NextBlock(); // Data insertion void Insert(const std::string& table, const Block& block); Block BeginInsert(const std::string& query); void SendInsertBlock(const Block& block); void EndInsert(); // Connection void Ping(); void ResetConnection(); const ServerInfo& GetServerInfo() const; }; ``` -------------------------------- ### Configure client failover Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/README.md Define primary and backup endpoints within ClientOptions to enable automatic failover. ```cpp ch::ClientOptions opts; opts.SetHost("primary.example.com") .SetPort(9000) .SetEndpoints({ {{"backup1.example.com", 9000}}, {{"backup2.example.com", 9000}}, {{"backup3.example.com", 9000}} }); ch::Client client(opts); ``` -------------------------------- ### Initialize ColumnTuple Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/columns.md Creates a ColumnTuple instance with specific column references and names. ```cpp auto col_id = std::make_shared(); auto col_name = std::make_shared(); ch::Block block; auto col_tuple = std::make_shared( std::vector{col_id, col_name}, std::vector{"id", "name"} ); ``` -------------------------------- ### Integrate with Bazel Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/README.md Configuration for adding the dependency and defining the build target using Bazel. ```bzl bazel_dep(name = "clickhouse-cpp", version = "2.6.2") ``` ```bzl cc_binary( name = "application-example", srcs = ["app.cpp"], deps = ["@clickhouse-cpp//:clickhouse"], ) ``` -------------------------------- ### Initialize an empty Block Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/block.md Create a new instance of a Block with no columns or rows. ```cpp ch::Block block; // Empty block ``` -------------------------------- ### Configure Compression Settings Source: https://github.com/clickhouse/clickhouse-cpp/blob/master/_autodocs/api-reference/client-options.md Sets the compression algorithm and chunk size for data transfer between the client and server. ```cpp ch::ClientOptions opts; opts.SetCompressionMethod(ch::CompressionMethod::LZ4) .SetMaxCompressionChunkSize(131072); // 128 KB chunks ```