Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/target
.idea
.cargo/
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* Implemented `Connection::get_option_string()` for `OptionConnection::AutoCommit`
(always `"true"`, as ClickHouse has no transactions) and `OptionConnection::CurrentCatalog`
(always empty, as ClickHouse has no catalog level above the database). ([#65])
* Implemented `Connection::get_info()` for driver/vendor metadata ([#69]).

[#65]: https://github.com/ClickHouse/adbc_clickhouse/pull/65
[#69]: https://github.com/ClickHouse/adbc_clickhouse/pull/69

## [0.1.2] - 2026-11-06

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ However, the core query flow is supported:
* Creating a `Driver` and `Database`
* Setting URL, username and password on the `Database`
* Creating a `Connection` and `Statement`
* Querying driver/vendor metadata with `Connection::get_info()`
* Setting a query with `Statement::set_sql_query()` and binding parameters with `Statement::bind()`
* Binding a statement in streaming insert mode with `Statement::bind_stream()`
* Executing a statement with `Statement::execute()` or `Statement::execute_update()`
Expand Down
147 changes: 147 additions & 0 deletions src/info.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
//! Helpers for building [`Connection::get_info`][adbc_core::Connection::get_info] results.
//!
//! The result schema is defined by [`adbc_core::schemas::GET_INFO_SCHEMA`].

use adbc_core::error::{Error, Status};
use adbc_core::options::InfoCode;
use adbc_core::schemas::GET_INFO_SCHEMA;
use arrow_array::builder::{
ArrayBuilder, BooleanBuilder, Int32Builder, Int64Builder, ListBuilder, MapBuilder,
MapFieldNames, StringBuilder, UInt32Builder,
};
use arrow_array::{ArrayRef, RecordBatch, RecordBatchIterator, RecordBatchReader, UnionArray};
use arrow_buffer::ScalarBuffer;
use arrow_schema::{DataType, UnionMode};
use std::collections::HashSet;
use std::sync::Arc;

type Result<T, E = Error> = std::result::Result<T, E>;

/// Builds a dense-union `get_info` result matching [`GET_INFO_SCHEMA`].
///
/// Pattern adapted from the ADBC Driver Foundry [`InfoBuilder`][info-builder].
///
/// [info-builder]: https://github.com/adbc-drivers/driverbase-rs/blob/main/driverbase/src/lib.rs
pub(crate) struct InfoBuilder {
info_name: UInt32Builder,
type_id: Vec<i8>,
offset: Vec<i32>,
string_value: StringBuilder,
bool_value: BooleanBuilder,
int64_value: Int64Builder,
int32_bitmask: Int32Builder,
string_list: ListBuilder<StringBuilder>,
int32_to_int32_list_map: MapBuilder<Int32Builder, ListBuilder<Int32Builder>>,
}

impl InfoBuilder {
const CODE_STRING: i8 = 0;
const CODE_BOOL: i8 = 1;
const CODE_INT64: i8 = 2;

pub(crate) fn new() -> Self {
Self {
info_name: UInt32Builder::new(),
type_id: Vec::new(),
offset: Vec::new(),
string_value: StringBuilder::new(),
bool_value: BooleanBuilder::new(),
int64_value: Int64Builder::new(),
int32_bitmask: Int32Builder::new(),
string_list: ListBuilder::new(StringBuilder::new()),
// Match `GET_INFO_SCHEMA` field names (`key`/`value`, not MapBuilder defaults).
int32_to_int32_list_map: MapBuilder::new(
Some(MapFieldNames {
entry: "entries".to_string(),
key: "key".to_string(),
value: "value".to_string(),
}),
Int32Builder::new(),
ListBuilder::new(Int32Builder::new()),
),
}
}

pub(crate) fn add_string(&mut self, code: InfoCode, value: impl AsRef<str>) {
self.info_name.append_value(u32::from(&code));
self.type_id.push(Self::CODE_STRING);
self.offset.push(self.string_value.len() as i32);
self.string_value.append_value(value);
}

pub(crate) fn add_bool(&mut self, code: InfoCode, value: bool) {
self.info_name.append_value(u32::from(&code));
self.type_id.push(Self::CODE_BOOL);
self.offset.push(self.bool_value.len() as i32);
self.bool_value.append_value(value);
}

pub(crate) fn add_i64(&mut self, code: InfoCode, value: i64) {
self.info_name.append_value(u32::from(&code));
self.type_id.push(Self::CODE_INT64);
self.offset.push(self.int64_value.len() as i32);
self.int64_value.append_value(value);
}

pub(crate) fn finish(mut self) -> Result<Box<dyn RecordBatchReader + Send + 'static>> {
let num_rows = self.type_id.len();
let info_name = self.info_name.finish();

let type_ids = ScalarBuffer::from(self.type_id);
let offsets = ScalarBuffer::from(self.offset);

let children: Vec<ArrayRef> = vec![
Arc::new(self.string_value.finish()),
Arc::new(self.bool_value.finish()),
Arc::new(self.int64_value.finish()),
Arc::new(self.int32_bitmask.finish()),
Arc::new(self.string_list.finish()),
Arc::new(self.int32_to_int32_list_map.finish()),
];

let schema = GET_INFO_SCHEMA.clone();
let DataType::Union(union_fields, UnionMode::Dense) = schema.field(1).data_type() else {
return Err(Error::with_message_and_status(
"GET_INFO_SCHEMA.info_value is not a dense union",
Status::Internal,
));
};

let info_value = UnionArray::try_new(
union_fields.clone(),
type_ids,
Some(offsets),
children,
)
.map_err(|e| {
Error::with_message_and_status(
format!("error building get_info union array: {e}"),
Status::Internal,
)
})?;

let batch = RecordBatch::try_new(
schema.clone(),
vec![Arc::new(info_name), Arc::new(info_value)],
)
.map_err(|e| {
Error::with_message_and_status(
format!("error building get_info record batch: {e}"),
Status::Internal,
)
})?;

debug_assert_eq!(batch.num_rows(), num_rows);

Ok(Box::new(RecordBatchIterator::new(
std::iter::once(Ok(batch)),
schema,
)))
}
}

/// Whether `codes` requests `code` (or requests everything when `None`).
#[inline]
pub(crate) fn wants(codes: Option<&HashSet<InfoCode>>, code: InfoCode) -> bool {
codes.is_none_or(|set| set.contains(&code))
}
79 changes: 77 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,14 @@
//! all strings as binary strings instead. This may be set at the connection or statement level.
use crate::options::{OptionValueExt, ProductInfo};
use adbc_core::error::{Error, Status};
use adbc_core::constants::ADBC_VERSION_1_1_0;
use adbc_core::options::{InfoCode, ObjectDepth, OptionConnection, OptionDatabase, OptionValue};
use adbc_core::{Connection, Database, Driver, Optionable, schemas};
use arrow_array::{RecordBatchIterator, RecordBatchReader, record_batch};
use arrow_schema::Schema;
use clickhouse::Client;
use rand::distr::{Alphanumeric, SampleString};
use std::future::Future;
use std::collections::{HashMap, HashSet};
use std::ops::Deref;
use std::sync::Arc;
Expand All @@ -124,6 +126,7 @@ macro_rules! err_unimplemented {
};
}

mod info;
pub mod options;
mod reader;
mod schema;
Expand Down Expand Up @@ -664,11 +667,17 @@ impl Connection for ClickhouseConnection {
err_unimplemented!("ClickhouseConnection::cancel()")
}

/// Return driver and vendor metadata as described by [`InfoCode`].
///
/// When `codes` is `None`, all supported info codes are returned. Unsupported codes
/// (currently `VendorArrowVersion` and Substrait version bounds) are omitted.
///
/// `VendorVersion` is fetched from the server via `SELECT version()`.
fn get_info(
&self,
_codes: Option<HashSet<InfoCode>>,
codes: Option<HashSet<InfoCode>>,
) -> adbc_core::error::Result<Box<dyn RecordBatchReader + Send + 'static>> {
err_unimplemented!("ClickhouseConnection::get_info()" -> Box<dyn RecordBatchReader + Send + 'static>)
self.tokio.block_on(self.build_info(codes.as_ref()))
}

fn get_objects(
Expand Down Expand Up @@ -890,6 +899,72 @@ impl ClickhouseConnection {
)),
}
}

async fn build_info(
&self,
codes: Option<&HashSet<InfoCode>>,
) -> Result<Box<dyn RecordBatchReader + Send + 'static>> {
let mut builder = info::InfoBuilder::new();

if info::wants(codes, InfoCode::VendorName) {
builder.add_string(InfoCode::VendorName, "ClickHouse");
}

if info::wants(codes, InfoCode::VendorVersion) {
let version = fetch_vendor_version(&self.client).await?;
builder.add_string(InfoCode::VendorVersion, version);
}

// ClickHouse does not expose a vendor Arrow library version over HTTP.
// Omit `VendorArrowVersion` rather than guessing.

if info::wants(codes, InfoCode::VendorSql) {
builder.add_bool(InfoCode::VendorSql, true);
}

if info::wants(codes, InfoCode::VendorSubstrait) {
builder.add_bool(InfoCode::VendorSubstrait, false);
}

// Substrait is unsupported. Arrow dense unions cannot carry top-level nulls, so we omit
// `VendorSubstrait{Min,Max}Version` rather than returning null `info_value` rows.

if info::wants(codes, InfoCode::DriverName) {
builder.add_string(InfoCode::DriverName, "ADBC ClickHouse Driver");
}

if info::wants(codes, InfoCode::DriverVersion) {
builder.add_string(InfoCode::DriverVersion, env!("CARGO_PKG_VERSION"));
}

// FIXME: populate `DriverArrowVersion` once we bump `arrow-*` far enough to use
// `arrow_array::ARROW_VERSION` (apache/arrow-rs#10957).

if info::wants(codes, InfoCode::DriverAdbcVersion) {
builder.add_i64(InfoCode::DriverAdbcVersion, ADBC_VERSION_1_1_0 as i64);
}

builder.finish()
}
}

#[derive(clickhouse::Row, serde::Deserialize)]
struct VendorVersionRow {
version: String,
}

async fn fetch_vendor_version(client: &Client) -> Result<String> {
client
.query("SELECT version() AS version")
.fetch_one::<VendorVersionRow>()
.await
.map(|row| row.version)
.map_err(|e| {
Error::with_message_and_status(
format!("error fetching ClickHouse version: {e}"),
Status::IO,
)
})
}

/// Wrapper for [`Client`] that implements expected semantics for certain settings.
Expand Down
Loading
Loading