### Run a ClickHouse Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/examples/README.md Executes a specific example using cargo. ```sh cargo run --package clickhouse --example async_insert ``` -------------------------------- ### Inserter Module Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to initialize an inserter. ```rust #[cfg(feature = "inserter")] use clickhouse::inserter::Inserter; let inserter = client.inserter::("table"); ``` -------------------------------- ### Query Module Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to build and execute a query. ```rust use clickhouse::query::Query; let query = client.query("SELECT * FROM table"); let cursor = query.fetch::()?; ``` -------------------------------- ### SQL Module Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to use SQL utilities and parameter binding. ```rust use clickhouse::sql::{Bind, Identifier}; client .query("SELECT * FROM ?") .bind(Identifier("table_name")) .fetch_all() .await? ``` -------------------------------- ### Run Arrow Examples Source: https://github.com/clickhouse/clickhouse-rs/blob/main/ext-arrow/README.md Execute the provided arrow example to demonstrate SELECT and INSERT operations using the Arrow integration. ```sh cargo run --package clickhouse --example arrow ``` -------------------------------- ### Insert Module Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to perform a single insert. ```rust use clickhouse::insert::Insert; let mut insert = client.insert::("table").await?; insert.write(&row).await?; insert.end().await?; ``` -------------------------------- ### Run a ClickHouse Example with Features Source: https://github.com/clickhouse/clickhouse-rs/blob/main/examples/README.md Executes a specific example that requires additional cargo features. ```sh cargo run --package clickhouse --example usage --features inserter ``` -------------------------------- ### Test Module Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to use the mock server for testing. ```rust #[cfg(test)] mod tests { use clickhouse::test::Mock; #[tokio::test] async fn test_query() { let mock = Mock::new(); let client = Client::default().with_mock(&mock); } } ``` -------------------------------- ### Insert Formatted Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to insert pre-formatted data. ```rust let insert = client.insert_formatted_with("INSERT INTO table FORMAT CSV"); insert.send(csv_data).await?; ``` -------------------------------- ### Serde Module Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to use serialization helpers for external types. ```rust use clickhouse::serde::ipv4; use std::net::Ipv4Addr; #[derive(Row, Serialize, Deserialize)] struct NetworkRow { #[serde(with = "clickhouse::serde::ipv4")] ip: Ipv4Addr, } ``` -------------------------------- ### Start ClickHouse with Docker Compose Source: https://github.com/clickhouse/clickhouse-rs/blob/main/CONTRIBUTING.md Use this command to start a ClickHouse server instance using Docker Compose for local development and testing. ```sh docker compose up -d ``` -------------------------------- ### Client Compression Configuration Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Demonstrates how to apply ZSTD compression to a ClickHouse client instance. ```rust let client = Client::default().with_compression(Compression::zstd()); ``` -------------------------------- ### Types Module Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to use custom data types. ```rust use clickhouse::types::{Int256, UInt256}; let int256 = Int256::from_ne_bytes([0u8; 32]); ``` -------------------------------- ### Int256 Creation Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/types-and-errors.md Example of creating an Int256 instance from native-endian bytes. ```rust let int256 = Int256::from_ne_bytes([0u8; 32]); ``` -------------------------------- ### Start ClickHouse Server for Benchmarks Source: https://github.com/clickhouse/clickhouse-rs/blob/main/benches/README.md Launch a ClickHouse server using Docker Compose for integration benchmarks. This command starts the necessary services in detached mode. ```bash docker compose up -d cargo bench --bench ``` -------------------------------- ### InsertFormatted usage example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/insert-api.md Example showing how to create an insert operation for CSV data and send it to the server. ```rust let csv_data = "id,name\n1,Alice\n2,Bob"; let insert = client.insert_formatted_with( "INSERT INTO users FORMAT CSV" ); insert.send(csv_data).await?; ``` -------------------------------- ### Configure returning rows Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Example of configuring the rows returned by a mock query. ```rust mock.expect_query("SELECT * FROM users") .returning(vec![ User { id: 1, name: "Alice".into() }, User { id: 2, name: "Bob".into() }, ]); ``` -------------------------------- ### Error Module Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Example showing how to use the error and result types. ```rust use clickhouse::error::{Error, Result}; fn may_fail() -> Result<()> { // ... Ok(()) } ``` -------------------------------- ### with_compression() Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Sets the compression mode for requests and responses. Supports LZ4 and ZSTD algorithms. ```rust let client = Client::default() .with_compression(Compression::Lz4); // or with ZSTD let client = Client::default() .with_compression(Compression::zstd()); ``` -------------------------------- ### Insert data using Client::insert() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/insert-api.md Example showing how to create an insert builder, write a row, and finalize the operation. ```rust #[derive(Row, Serialize)] struct MyRow { id: u32, name: String, } let mut insert = client.insert::("my_table").await?; insert.write(&MyRow { id: 1, name: "Alice".into() }).await?; insert.end().await?; ``` -------------------------------- ### Test query with Mock server Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Example of using the mock server within a tokio test environment. ```rust #[tokio::test] async fn test_query() { let mock = Mock::new(); let client = Client::default().with_mock(&mock); // Use client for queries/inserts } ``` -------------------------------- ### with_setting() Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Sets a ClickHouse setting to be applied to all subsequent queries. ```rust let client = Client::default() .with_setting("async_insert", "1") .with_setting("wait_end_of_query", "1"); ``` -------------------------------- ### Field Ordering Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/row-derive.md Demonstrates matching struct field order to database table column order. ```rust // Table: CREATE TABLE test (id UInt32, name String) #[derive(Row)] struct MyRow { id: u32, name: String, // Order matches table } ``` -------------------------------- ### insert_formatted_with Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Starts an INSERT with pre-formatted data. ```APIDOC ## insert_formatted_with(sql: impl Into) ### Description Starts an INSERT with pre-formatted data (CSV, JSON, TabSeparated, etc.). Data is not validated by the client. ### Parameters - **sql** (impl Into) - Required - Full INSERT INTO ... FORMAT ... statement ``` -------------------------------- ### Initializing OpenTelemetry tracing Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Setup for the OpenTelemetry tracer provider and subscriber to enable automatic span emission for client queries. ```rust use opentelemetry_sdk::trace::TracerProvider; use opentelemetry_sdk::runtime; use tracing_opentelemetry::OpenTelemetryLayer; use tracing_subscriber::layer::SubscriberExt; let tracer_provider = TracerProvider::builder() .with_batch_exporter(/* exporter */, runtime::Tokio) .build(); let tracing_layer = OpenTelemetryLayer::new( tracer_provider.tracer("clickhouse-rs") ); tracing_subscriber::registry() .with(tracing_layer) .init(); // All queries now emit OpenTelemetry spans client.query("SELECT * FROM table").fetch_all().await?; ``` -------------------------------- ### Run Real Server Benchmarks Source: https://github.com/clickhouse/clickhouse-rs/blob/main/benches/README.md Execute benchmarks against a running ClickHouse server. This requires the server to be started first, typically via Docker Compose. ```bash cargo bench --bench & perf record -p `ps -AT | grep | awk '{print $2}'` --call-graph dwarf,65528 --freq 5000 -g -- sleep 5 perf script > perf.script ``` -------------------------------- ### Register expected query Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Example of registering a query expectation and fetching results using the mock client. ```rust let mock = Mock::new(); mock.expect_query("SELECT ?") .returning(vec![ MyRow { id: 1, name: "Alice".into() }, MyRow { id: 2, name: "Bob".into() }, ]); let client = Client::default().with_mock(&mock); let rows: Vec = client .query("SELECT * FROM users") .fetch_all() .await?; ``` -------------------------------- ### Run ClickHouse Server via Docker Source: https://github.com/clickhouse/clickhouse-rs/blob/main/examples/README.md Starts a ClickHouse server instance in a Docker container for testing purposes. ```sh docker run -d -p 8123:8123 -p 9000:9000 --name chrs-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server ``` -------------------------------- ### query() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Starts a new SELECT or DDL query with client-side parameter binding. ```APIDOC ## `query(query)` ### Description Starts a new SELECT or DDL query with client-side parameter binding. Supports `?` for bind args, `?fields` for column names, and `??` for literal `?`. ### Parameters - **query** (&str) - Required - SQL query template with `?` placeholders ### Example ```rust let rows: Vec = client .query("SELECT ?fields FROM table WHERE id = ?") .bind(42) .fetch_all() .await?; ``` ``` -------------------------------- ### with_roles() Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Sets one or more roles for the client, overriding any previously set roles. These roles are applied to all queries. ```rust let client = Client::default() .with_roles(["analyst", "viewer"]); ``` -------------------------------- ### Insert pre-formatted data with insert_formatted_with() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Example of using a raw SQL string with a specified format to send pre-formatted data. ```rust let insert = client.insert_formatted_with( "INSERT INTO table FORMAT CSV" ); insert.send(csv_data).await?; ``` -------------------------------- ### Bind Trait Usage Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/types-and-errors.md Demonstrates binding a vector of integers to a query placeholder. ```rust client .query("SELECT * FROM users WHERE id IN ?") .bind(vec![1, 2, 3]) .fetch_all::() .await? ``` -------------------------------- ### Struct Fields with Option Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/row-derive.md Example of a struct with various field types including an optional field. ```rust #[derive(Row, Serialize, Deserialize)] struct Person { id: u32, name: String, age: u16, email: Option, } ``` -------------------------------- ### Register expected insert Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Example of registering an expected INSERT statement and executing it via the mock client. ```rust let mock = Mock::new(); mock.expect_insert("INSERT INTO table") .returning(vec![]); // Accept any rows let client = Client::default().with_mock(&mock); let mut insert = client.insert::("table").await?; insert.write(&row).await?; insert.end().await?; ``` -------------------------------- ### Identifier usage example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Demonstrates escaping table names for safe SQL inclusion using the Identifier struct. ```rust use clickhouse::sql::Identifier; let table = "my_table"; let rows = client .query("SELECT * FROM ?") .bind(Identifier(table)) .fetch_all::() .await?; ``` -------------------------------- ### Execute query with client-side binding Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Starts a SELECT or DDL query using client-side parameter binding. Supports '?' for bind arguments and '?fields' for column names. ```rust let rows: Vec = client .query("SELECT ?fields FROM table WHERE id = ?") .bind(42) .fetch_all() .await?; ``` -------------------------------- ### Configure Client with Environment Variables Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/configuration.md A recommended pattern for initializing the client using environment variables for URL, user, password, and database credentials. ```rust let url = std::env::var("CLICKHOUSE_URL") .unwrap_or_else(|_| "http://localhost:8123".to_string()); let user = std::env::var("CLICKHOUSE_USER").ok(); let password = std::env::var("CLICKHOUSE_PASSWORD").ok(); let database = std::env::var("CLICKHOUSE_DATABASE").ok(); let mut client = Client::default().with_url(url); if let Some(u) = user { client = client.with_user(u); } if let Some(p) = password { client = client.with_password(p); } if let Some(d) = database { client = client.with_database(d); } ``` -------------------------------- ### Initialize Mock server Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Create a new mock server instance and associate it with a ClickHouse client. ```rust use clickhouse::test::Mock; let mock = Mock::new(); let client = Client::default().with_mock(&mock); ``` -------------------------------- ### Creating a Client Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/README.md Initializes a new ClickHouse client with connection details including URL, database, user, and password. ```rust use clickhouse::Client; let client = Client::default() .with_url("http://localhost:8123") .with_database("my_db") .with_user("alice") .with_password("secret"); ``` -------------------------------- ### Client Initialization Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/README.md Configures and initializes a new ClickHouse client instance with connection details and settings. ```APIDOC ## Client Initialization ### Description Initializes a new `clickhouse::Client` instance with connection parameters such as URL, database, credentials, and custom settings. ### Usage ```rust use clickhouse::Client; let client = Client::default() .with_url("http://localhost:8123") .with_database("my_db") .with_user("alice") .with_password("secret"); ``` ``` -------------------------------- ### Create a ClickHouse client instance Source: https://github.com/clickhouse/clickhouse-rs/blob/main/docs/index.mdx Initialize a client instance. It is recommended to reuse or clone clients to leverage the underlying hyper connection pool. ```rust use clickhouse::Client; let client = Client::default() // should include both protocol and port .with_url("http://localhost:8123") .with_user("name") .with_password("123") .with_database("test"); ``` -------------------------------- ### Run Mocked Server Benchmarks Source: https://github.com/clickhouse/clickhouse-rs/blob/main/benches/README.md Execute benchmarks against a mocked HTTP server to measure client overhead. Ensure the bench target is specified. ```bash cargo bench --bench & perf record -p `ps -AT | grep testee | awk '{print $2}'` --call-graph dwarf,65528 --freq 5000 -g -- sleep 5 perf script > perf.script ``` -------------------------------- ### insert Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Starts a new INSERT statement with automatic table name escaping. ```APIDOC ## insert(table: &str) ### Description Starts a new INSERT statement with automatic table name escaping. Validates schema by fetching it once per table. ### Parameters - **table** (&str) - Required - Table name (escaped as identifier) ### Return Type - **Result>** - Insert builder, or error if schema validation fails ``` -------------------------------- ### Client::with_http_client() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Initializes a client using a custom HTTP client implementation. ```APIDOC ## Client::with_http_client() ### Description Creates a client with a custom underlying HTTP client implementation. ### Signature `pub fn with_http_client(client: impl HttpClient) -> Self` ### Parameters - **client** (impl HttpClient) - Required - Custom HTTP client implementation. ``` -------------------------------- ### Configure Product Information Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/configuration.md Adds product metadata to the User-Agent header. Products are added in reverse order of calls. ```rust let client = Client::default() .with_product_info("MyApp", "1.0.0") .with_product_info("MyDataSource", "2.0.0"); // User-Agent: MyDataSource/2.0.0 MyApp/1.0.0 clickhouse-rs/0.15.2 (...) ``` -------------------------------- ### Pattern Matching Errors Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/types-and-errors.md Example of how to handle specific error variants when executing a query. ```rust use clickhouse::error::Error; match client.query("SELECT * FROM t").fetch_one::().await { Ok(row) => println!("Success: {:?}", row), Err(Error::RowNotFound) => println!("No rows"), Err(Error::Network(e)) => println!("Network: {}", e), Err(Error::SchemaMismatch(msg)) => println!("Schema: {}", msg), Err(Error::TimedOut) => println!("Timeout"), Err(e) => println!("Other: {}", e), } ``` -------------------------------- ### Configuration Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/README.md Configures client options such as compression, custom settings, headers, and validation. ```rust let client = Client::default() .with_url("http://localhost:8123") .with_compression(Compression::Lz4) .with_setting("async_insert", "1") .with_header("X-Custom-Header", "value") .with_validation(true); ``` -------------------------------- ### Bind trait usage example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Shows binding multiple values to query placeholders. ```rust client .query("SELECT * FROM table WHERE id IN ? AND name = ?") .bind(vec![1, 2, 3]) .bind("Alice") .fetch_all() .await? ``` -------------------------------- ### Named Fields Support Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/row-derive.md Example of a struct with named fields supported by the Row macro. ```rust #[derive(Row)] struct NamedRow { col1: u32, col2: String, } ``` -------------------------------- ### Basic Row Derive Usage Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/row-derive.md Example of deriving Row, Serialize, and Deserialize for a struct. ```rust use clickhouse::Row; use serde::{Serialize, Deserialize}; #[derive(Row, Serialize, Deserialize)] struct MyRow { id: u32, name: String, score: f64, } ``` -------------------------------- ### Client::default() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Creates a new default Client instance with no pre-configured settings. ```APIDOC ## Client::default() ### Description Creates a default client with no URL, database, authentication, or settings configured. ### Signature `pub fn default() -> Self` ### Returns A new `Client` instance. ``` -------------------------------- ### Nullable Data Type Mapping Source: https://github.com/clickhouse/clickhouse-rs/blob/main/README.md Example of mapping a Nullable ClickHouse type to an Option in Rust. ```rust use clickhouse::Row; use serde::{Serialize, Deserialize}; use std::net::Ipv4Addr; #[derive(Row, Serialize, Deserialize)] struct MyRow { #[serde(with = "clickhouse::serde::ipv4::option")] ipv4_opt: Option, } ``` -------------------------------- ### RowOwned trait usage example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Shows a generic function signature requiring owned data. ```rust pub async fn fetch_one(self) -> Result where T: RowOwned + RowRead ``` -------------------------------- ### RowRead trait usage example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Demonstrates fetching rows generically using the RowRead trait. ```rust async fn fetch_generic( client: &Client, table: &str, ) -> Result> { client .query("SELECT ?fields FROM ?") .bind(Identifier(table)) .fetch_all() .await } ``` -------------------------------- ### with_product_info() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Adds product information to the User-Agent header. Products appear in the User-Agent string in the reverse order of calls. ```APIDOC ## `with_product_info(product_name, product_version)` ### Description Adds product information to the User-Agent header. Products appear in reverse order of calls. ### Parameters - **product_name** (impl Into) - Required - Product name - **product_version** (impl Into) - Required - Product version ### Example ```rust let client = Client::default() .with_product_info("MyDataSource", "v1.0.0") .with_product_info("MyApp", "0.0.1"); ``` ``` -------------------------------- ### Connection with Credentials from Environment Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/README.md Configuring a ClickHouse client using environment variables for URL, user, and password, with fallback defaults. ```rust let client = Client::default() .with_url( std::env::var("CLICKHOUSE_URL") .unwrap_or_else(|_| "http://localhost:8123".into()) ) .with_user(std::env::var("CLICKHOUSE_USER").ok().unwrap_or_default()) .with_password(std::env::var("CLICKHOUSE_PASSWORD").ok().unwrap_or_default()); ``` -------------------------------- ### Geo Data Type Mapping Source: https://github.com/clickhouse/clickhouse-rs/blob/main/README.md Example of mapping various Geo data types to Rust structures. ```rust use clickhouse::Row; use serde::{Serialize, Deserialize}; type Point = (f64, f64); type Ring = Vec; type Polygon = Vec; type MultiPolygon = Vec; type LineString = Vec; type MultiLineString = Vec; #[derive(Row, Serialize, Deserialize)] struct MyRow { point: Point, ring: Ring, polygon: Polygon, multi_polygon: MultiPolygon, line_string: LineString, multi_line_string: MultiLineString, } ``` -------------------------------- ### Time Data Type Mapping Source: https://github.com/clickhouse/clickhouse-rs/blob/main/README.md Example of using the Time data type with a custom serde attribute. ```rust #[derive(Row, Serialize, Deserialize)] struct MyRow { #[serde(with = "clickhouse::serde::time::time")] t0: Time, } ``` -------------------------------- ### Client::default() Constructor Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Creates a default client instance. Use this for initial client creation before applying configuration. ```rust pub fn default() -> Self ``` ```rust let client = Client::default() .with_url("http://localhost:8123") .with_database("my_db"); ``` -------------------------------- ### Generate Documentation Source: https://github.com/clickhouse/clickhouse-rs/blob/main/CONTRIBUTING.md Generates the project's documentation, including all features, to be checked for completeness and correctness. ```sh cargo doc --all-features ``` -------------------------------- ### RowWrite trait usage example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Demonstrates inserting a batch of rows generically using the RowWrite trait. ```rust async fn insert_batch( client: &Client, table: &str, rows: &[R], ) -> Result<()> { let mut insert = client.insert::(table).await?; for row in rows { insert.write(row).await?; } insert.end().await?; Ok(()) } ``` -------------------------------- ### Configure Insert-Level Settings Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/configuration.md Shows how to apply timeouts, settings, and roles to an individual INSERT statement. All configuration must be set before the first write call. ```rust let mut insert = client.insert::("table").await? .with_timeouts( Some(Duration::from_secs(5)), Some(Duration::from_secs(30)) ) .with_setting("async_insert", "1") .with_roles(["writer"]); insert.write(&row).await?; insert.end().await?; ``` -------------------------------- ### Configure Inserter Settings Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/configuration.md Demonstrates configuring batch inserter parameters such as timeouts, max bytes, max rows, and timing periods. ```rust let mut inserter = client.inserter::("table") .with_timeouts( Some(Duration::from_secs(5)), Some(Duration::from_secs(30)) ) .with_max_bytes(50_000_000) .with_max_rows(100_000) .with_period(Some(Duration::from_secs(10))) .with_period_bias(Some(Duration::from_millis(500))); for row in &my_data { inserter.write(&row).await?; } inserter.end().await?; ``` -------------------------------- ### Configure Compression Algorithms Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/configuration.md Sets the compression algorithm for the client. Options include LZ4, ZSTD with custom levels, or no compression. ```rust // LZ4 compression let client = Client::default().with_compression(Compression::Lz4); // ZSTD with default level let client = Client::default().with_compression(Compression::zstd()); // ZSTD with custom level (1-22) let client = Client::default().with_compression(Compression::Zstd(9)); // No compression let client = Client::default().with_compression(Compression::None); ``` -------------------------------- ### Borrowed Data with Lifetimes Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/row-derive.md Example of using lifetime parameters to borrow data from the cursor, avoiding allocations. ```rust #[derive(Row, Deserialize)] struct BorrowedRow<'a> { id: u32, name: &'a str, // Borrows from cursor data: &'a [u8], // Borrows from cursor } ``` -------------------------------- ### Exporting data with fetch_bytes and fetch_native Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Demonstrates how to use fetch_bytes for formats like CSV and JSON, and fetch_native for the native ClickHouse format. ```rust // Export to CSV let mut cursor = client .query("SELECT * FROM events") .fetch_bytes("CSV")?; // Export to JSON let mut cursor = client .query("SELECT * FROM events") .fetch_bytes("JSON")?; // Native format let mut cursor = client .query("SELECT * FROM events") .fetch_native()?; ``` -------------------------------- ### Nested Data Type Mapping Source: https://github.com/clickhouse/clickhouse-rs/blob/main/README.md Example of mapping a ClickHouse Nested type by providing multiple arrays with renaming. ```rust // CREATE TABLE test(items Nested(name String, count UInt32)) use clickhouse::Row; use serde::{Serialize, Deserialize}; #[derive(Row, Serialize, Deserialize)] struct MyRow { #[serde(rename = "items.name")] items_name: Vec, #[serde(rename = "items.count")] items_count: Vec, } ``` -------------------------------- ### Testing with Mock Server Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/README.md Using the clickhouse::test::Mock utility to simulate query responses during unit testing. ```rust #[cfg(test)] mod tests { use clickhouse::test::Mock; #[tokio::test] async fn test_query() { let mock = Mock::new(); mock.expect_query("SELECT ?") .returning(vec![ MyRow { id: 1, name: "Alice".into() }, MyRow { id: 2, name: "Bob".into() }, ]); let client = Client::default().with_mock(&mock); let rows: Vec = client .query("SELECT * FROM users") .fetch_all() .await .unwrap(); assert_eq!(rows.len(), 2); } } ``` -------------------------------- ### with_header() Example Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Adds a custom HTTP header to all requests. Header values are redacted in debug output for security. ```rust let client = Client::default() .with_header("X-Custom-Header", "value") .with_header("User-Agent", "MyApp/1.0"); ``` -------------------------------- ### Write rows using Inserter Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/insert-api.md Demonstrates initializing an inserter with row and time thresholds, writing data in a loop, and finalizing the process. ```rust let mut inserter = client.inserter::("table") .with_max_rows(10_000) .with_period(Some(Duration::from_secs(5))); for row in my_data { inserter.write(&row).await?; } inserter.end().await?; ``` -------------------------------- ### Incorrect Rust Struct Definition Source: https://github.com/clickhouse/clickhouse-rs/blob/main/docs/index.mdx An example of an EventLog struct definition that causes a CANNOT_READ_ALL_DATA error due to a type mismatch. ```rust #[derive(Debug, Serialize, Deserialize, Row)] struct EventLog { id: String, // <- should be u32 instead! } ``` -------------------------------- ### Mock::new() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Creates a new instance of the mock server for testing. ```APIDOC ## Mock::new() ### Description Creates a new mock server instance that simulates ClickHouse responses. ### Signature `pub fn new() -> Self` ### Returns - **Mock** - A new mock server instance. ``` -------------------------------- ### SQL Table Definition for event_log Source: https://github.com/clickhouse/clickhouse-rs/blob/main/docs/index.mdx Example table schema used to demonstrate potential data type mismatch errors. ```sql CREATE OR REPLACE TABLE event_log (id UInt32) ENGINE = MergeTree ORDER BY timestamp ``` -------------------------------- ### Recommended Import Pattern Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md It is recommended to import types directly from their respective dependencies for clarity. ```rust use serde::{Serialize, Deserialize}; use clickhouse::Row; ``` -------------------------------- ### Array Data Type Mapping Source: https://github.com/clickhouse/clickhouse-rs/blob/main/README.md Example of mapping a ClickHouse Array to a Rust Vec using the uuid_vec serde helper. ```rust use serde::{Serialize, Deserialize}; use clickhouse::Row; #[derive(Row, Serialize, Deserialize)] struct MyRow { #[serde(with = "clickhouse::serde::uuid_vec")] uuids: Vec, } ``` -------------------------------- ### Run All Tests Source: https://github.com/clickhouse/clickhouse-rs/blob/main/CONTRIBUTING.md Execute all tests in the project. Includes commands for running with default, no, and all features enabled. ```sh cargo test ``` ```sh cargo test --no-default-features ``` ```sh cargo test --all-features ``` -------------------------------- ### Mock::url() signature Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Gets the mock server's internal URL. Rarely needed; use with_mock() instead. ```rust pub fn url(&self) -> &str ``` -------------------------------- ### Configure chrono crate dependencies Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Add the chrono crate and enable the chrono feature in clickhouse-rs. ```toml [dependencies] chrono = "0.4" clickhouse = { version = "0.15.2", features = ["chrono"] } ``` -------------------------------- ### Perform batch operations with inserter() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Shows how to configure an infinite inserter with row, byte, and time thresholds for batch operations. ```rust let mut inserter = client.inserter::("table") .with_max_rows(100_000) .with_max_bytes(50_000_000) .with_period(Some(Duration::from_secs(10))); inserter.write(&row).await?; let stats = inserter.commit().await?; ``` -------------------------------- ### Using Serde Modules in a Row Struct Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/types-and-errors.md Example of applying custom Serde modules to struct fields using the serde(with) attribute. ```rust #[derive(Row, Serialize, Deserialize)] struct MyRow { #[serde(with = "clickhouse::serde::ipv4")] ip: std::net::Ipv4Addr, #[serde(with = "clickhouse::serde::uuid")] id: uuid::Uuid, } ``` -------------------------------- ### Variant Data Type Mapping Source: https://github.com/clickhouse/clickhouse-rs/blob/main/README.md Example of mapping a ClickHouse Variant type to a Rust enum, ensuring the order of variants matches the database definition. ```rust use clickhouse::Row; use serde::{Serialize, Deserialize}; use time::Date; #[derive(Serialize, Deserialize)] enum MyRowVariant { Array(Vec), Boolean(bool), #[serde(with = "clickhouse::serde::time::date")] Date(time::Date), String(String), UInt32(u32), } #[derive(Row, Serialize, Deserialize)] struct MyRow { id: u64, var: MyRowVariant, } ``` -------------------------------- ### Enable test-util feature module Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/modules-and-exports.md Enables the mock server for testing by conditionally compiling the test module. ```rust #[cfg(feature = "test-util")] pub mod test; // Exports Mock ``` -------------------------------- ### Client Configuration Methods Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/configuration.md Methods available on the Client builder to configure connection, authentication, and request behavior. ```APIDOC ## Client Configuration Methods ### Connection - `with_url(url: String)`: Sets the ClickHouse HTTP endpoint. - `with_database(db: String)`: Sets the default database for queries. ### Authentication - `with_user(user: String)`: Sets the username. - `with_password(password: String)`: Sets the password. - `with_access_token(token: String)`: Sets the JWT token for ClickHouse Cloud. ### Compression - `with_compression(compression: Compression)`: Sets the compression algorithm (LZ4, Zstd, or None). ### Settings - `with_setting(name: String, value: String)`: Adds a server setting. - `set_setting(name: String, value: String)`: Updates a setting and returns the previous value. - `get_setting(name: String)`: Retrieves the current value of a setting. ### Headers - `with_header(key: String, value: String)`: Adds a custom HTTP header. ### Roles - `with_roles(roles: HashSet)`: Sets the roles for access control. - `with_default_roles()`: Clears configured roles. ### Product Information - `with_product_info(name: String, version: String)`: Adds product metadata to the User-Agent header. ``` -------------------------------- ### RowOwned Trait and Usage Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/types-and-errors.md The RowOwned trait identifies rows where the value type does not depend on a lifetime, meaning it contains no borrowed data. It is used in generic code requiring owned data, such as the provided fetch_one example. ```rust pub trait RowOwned: for<'a> Row = Self> {} ``` ```rust pub async fn fetch_one(self) -> Result where T: RowOwned + RowRead ``` -------------------------------- ### Client::with_password() Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Sets the password for authentication. ```APIDOC ## Client::with_password() ### Description Sets the password for credential-based authentication. ### Signature `pub fn with_password(mut self, password: impl Into) -> Self` ### Parameters - **password** (impl Into) - Required - Password. ``` -------------------------------- ### Inserting Data Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/README.md Shows how to perform single inserts and batch inserts, the latter of which requires the inserter feature. ```rust // Single insert let mut insert = client.insert::("table").await?; insert.write(&MyRow { id: 1, name: "Alice".into() }).await?; insert.end().await?; // Batch insert (requires inserter feature) #[cfg(feature = "inserter")] { let mut inserter = client.inserter::("table") .with_max_rows(100_000) .with_period(Some(Duration::from_secs(5))); for row in &my_data { inserter.write(row).await?; } inserter.end().await?; } ``` -------------------------------- ### Client::database() Configuration Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md Returns the currently configured default database name. ```rust pub fn database(&self) -> Option<&str> ``` -------------------------------- ### Configure Connection URL and Database Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/configuration.md Sets the ClickHouse HTTP endpoint and the default database for queries. ```rust let client = Client::default() .with_url("http://localhost:8123") .with_database("analytics"); ``` -------------------------------- ### Mock::new() signature Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/testing-and-utilities.md Creates a new mock server instance. ```rust pub fn new() -> Self ``` -------------------------------- ### Configure Query Settings Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/configuration.md Sets server-side query settings and retrieves current values. ```rust let client = Client::default() .with_setting("async_insert", "1") .with_setting("wait_end_of_query", "1"); // Get current value if let Some(value) = client.get_setting("async_insert") { println!("async_insert = {}", value); } ``` -------------------------------- ### Client::query() Method Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/query-api.md Creates a query with client-side parameter parsing using '?' placeholders. ```rust pub fn query(&self, query: &str) -> query::Query ``` -------------------------------- ### Infinite inserting with Inserter Source: https://github.com/clickhouse/clickhouse-rs/blob/main/README.md Demonstrates how to use the Inserter feature to batch and insert rows into a ClickHouse table. Requires the 'inserter' feature enabled. ```rust use serde::Serialize; use clickhouse::Row; use clickhouse::inserter::Inserter; use std::time::Duration; #[derive(Row, Serialize)] struct MyRow { no: u32, name: String, } async fn example(client: clickhouse::Client) -> clickhouse::error::Result<()> { let mut inserter = client.inserter::("some") .with_timeouts(Some(Duration::from_secs(5)), Some(Duration::from_secs(20))) .with_max_bytes(50_000_000) .with_max_rows(750_000) .with_period(Some(Duration::from_secs(15))); inserter.write(&MyRow { no: 0, name: "foo".into() }).await?; inserter.write(&MyRow { no: 1, name: "bar".into() }).await?; let stats = inserter.commit().await?; if stats.rows > 0 { println!( "{} bytes, {} rows, {} transactions have been inserted", stats.bytes, stats.rows, stats.transactions, ); } Ok(()) } ``` -------------------------------- ### Client Struct Signature Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/client-api.md The main entry point for interacting with ClickHouse. ```rust pub struct Client { // Internal fields omitted } ``` -------------------------------- ### Client::query_raw() Method Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/query-api.md Creates a query sending SQL verbatim without placeholder parsing. ```rust pub fn query_raw(&self, query: &str) -> query::Query ``` -------------------------------- ### Configuration Methods Source: https://github.com/clickhouse/clickhouse-rs/blob/main/_autodocs/insert-api.md Methods to configure the behavior of the Inserter, including timeouts and batch thresholds. ```APIDOC ## Inserter Configuration Methods ### with_timeouts(send_timeout: Option, end_timeout: Option) Sets timeouts for all INSERT operations. ### with_max_bytes(threshold: u64) Sets the maximum uncompressed bytes threshold for one INSERT. ### with_max_rows(threshold: u64) Sets the maximum row count threshold for one INSERT. ### with_period(period: Option) Sets the time interval between INSERTs. ### with_period_bias(bias: Option) Adds a random bias to period timing to avoid thundering herd in parallel inserters. ```