mod de;
mod param;
mod ser;
#[cfg(test)]
mod tests;
use std::future::IntoFuture;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll};
use encore_sdk_core::clickhouse::{self as core_ch, Access};
use encore_sdk_core::telemetry::opentelemetry::Context as OtelContext;
use futures_core::future::BoxFuture;
use futures_core::Stream;
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::runtime::core;
use crate::testing;
pub use self::param::{ArrayElement, Param};
pub use encore_sdk_core::clickhouse::{Column, Type, Value};
pub struct Database {
name: &'static str,
#[allow(dead_code)]
migrations: Option<&'static str>,
db: OnceLock<Arc<core_ch::Database>>,
}
impl Database {
pub const fn new(name: &'static str) -> Self {
Self {
name,
migrations: None,
db: OnceLock::new(),
}
}
pub const fn named(name: &'static str) -> Self {
Self::new(name)
}
pub const fn migrations(mut self, path: &'static str) -> Self {
self.migrations = Some(path);
self
}
pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
self
}
pub const fn admin(&'static self) -> DatabaseRef {
DatabaseRef {
db: self,
access: Access::Admin,
}
}
pub const fn write(&'static self) -> DatabaseRef {
DatabaseRef {
db: self,
access: Access::Write,
}
}
pub const fn read(&'static self) -> DatabaseRef {
DatabaseRef {
db: self,
access: Access::Read,
}
}
pub fn query(&self, sql: impl Into<String>) -> Query<'_> {
Query::new(self, Access::Write, sql.into())
}
pub fn exec(&self, sql: impl Into<String>) -> Exec<'_> {
Exec::new(self, Access::Write, sql.into())
}
pub fn insert<'a, T: Serialize>(&'a self, table: &str, rows: &'a [T]) -> Insert<'a, T> {
Insert::new(self, Access::Write, table, rows)
}
pub fn connection_string(&self) -> Result<String, Error> {
self.connection_string_as(Access::Write)
}
fn connection_string_as(&self, access: Access) -> Result<String, Error> {
self.database()?.connection_string(access).map_err(ch_err)
}
fn database(&self) -> Result<Arc<core_ch::Database>, Error> {
if let Some(test) = testing::active().map_err(test_err)? {
return test.clickhouse_database(self.name).map_err(test_err);
}
if let Some(db) = self.db.get() {
return Ok(db.clone());
}
let db = core().clickhouse().database(&self.name.into());
if db.cloud_name().is_ok() {
let _ = self.db.set(db.clone());
}
Ok(db)
}
}
#[derive(Clone, Copy)]
pub struct DatabaseRef {
db: &'static Database,
access: Access,
}
impl DatabaseRef {
pub fn query(&self, sql: impl Into<String>) -> Query<'static> {
Query::new(self.db, self.access, sql.into())
}
pub fn exec(&self, sql: impl Into<String>) -> Exec<'static> {
Exec::new(self.db, self.access, sql.into())
}
pub fn insert<'a, T: Serialize>(&self, table: &str, rows: &'a [T]) -> Insert<'a, T> {
Insert::new(self.db, self.access, table, rows)
}
pub fn connection_string(&self) -> Result<String, Error> {
self.db.connection_string_as(self.access)
}
}
#[must_use = "a query does nothing until a `fetch` method runs it"]
pub struct Query<'a> {
db: &'a Database,
access: Access,
query: core_ch::Query,
}
impl<'a> Query<'a> {
fn new(db: &'a Database, access: Access, sql: String) -> Self {
Query {
db,
access,
query: core_ch::Query::new(sql),
}
}
pub fn param(mut self, name: impl Into<String>, value: impl Into<Param>) -> Self {
self.query.params.push((name.into(), value.into().0));
self
}
pub fn setting(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.query.settings.push((name.into(), value.into()));
self
}
pub fn query_id(mut self, id: impl Into<String>) -> Self {
self.query.query_id = Some(id.into());
self
}
pub async fn fetch<T: FromRow>(self) -> Result<RowStream<T>, Error> {
let db = self.db.database()?;
let cx = context();
let rows = db
.query_in(self.access, self.query, &cx)
.await
.map_err(ch_err)?;
Ok(RowStream::new(rows))
}
pub async fn fetch_all<T: FromRow>(self) -> Result<Vec<T>, Error> {
let mut rows = self.fetch::<T>().await?;
let mut out = Vec::new();
while let Some(row) = rows.next().await {
out.push(row?);
}
Ok(out)
}
pub async fn fetch_one<T: FromRow>(self) -> Result<T, Error> {
self.fetch_optional().await?.ok_or(Error::NoRows)
}
pub async fn fetch_optional<T: FromRow>(self) -> Result<Option<T>, Error> {
let mut rows = self.fetch::<T>().await?;
let Some(first) = rows.next().await.transpose()? else {
return Ok(None);
};
if rows.next_values().await?.is_some() {
return Err(Error::TooManyRows);
}
Ok(Some(first))
}
}
#[must_use = "a statement does nothing until it is awaited"]
pub struct Exec<'a> {
inner: Query<'a>,
}
impl<'a> Exec<'a> {
fn new(db: &'a Database, access: Access, sql: String) -> Self {
Exec {
inner: Query::new(db, access, sql),
}
}
pub fn param(self, name: impl Into<String>, value: impl Into<Param>) -> Self {
Exec {
inner: self.inner.param(name, value),
}
}
pub fn setting(self, name: impl Into<String>, value: impl Into<String>) -> Self {
Exec {
inner: self.inner.setting(name, value),
}
}
pub fn query_id(self, id: impl Into<String>) -> Self {
Exec {
inner: self.inner.query_id(id),
}
}
}
impl<'a> IntoFuture for Exec<'a> {
type Output = Result<ExecResult, Error>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
let Query { db, access, query } = self.inner;
Box::pin(async move {
let db = db.database()?;
let cx = context();
let summary = db.exec_in(access, query, &cx).await.map_err(ch_err)?;
Ok(ExecResult::from(summary))
})
}
}
#[must_use = "an insert does nothing until it is awaited"]
pub struct Insert<'a, T> {
db: &'a Database,
access: Access,
table: String,
rows: &'a [T],
settings: Vec<(String, String)>,
query_id: Option<String>,
}
impl<'a, T: Serialize> Insert<'a, T> {
fn new(db: &'a Database, access: Access, table: &str, rows: &'a [T]) -> Self {
Insert {
db,
access,
table: table.to_string(),
rows,
settings: Vec::new(),
query_id: None,
}
}
pub fn query_id(mut self, id: impl Into<String>) -> Self {
self.query_id = Some(id.into());
self
}
pub fn setting(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.settings.push((name.into(), value.into()));
self
}
fn columns(&self) -> Result<(Vec<String>, core_ch::InsertRows), Error> {
let mut columns: Vec<String> = Vec::new();
let mut index = std::collections::HashMap::new();
let mut rows = Vec::with_capacity(self.rows.len());
for (i, row) in self.rows.iter().enumerate() {
let fields =
ser::to_row(row).map_err(|e| Error::InvalidArgument(format!("row {i}: {e}")))?;
let mut values = vec![None; columns.len()];
for (name, value) in fields {
let at = *index.entry(name.clone()).or_insert_with(|| {
columns.push(name);
columns.len() - 1
});
if at >= values.len() {
values.resize(at + 1, None);
}
values[at] = Some(value);
}
rows.push(values);
}
for row in &mut rows {
row.resize(columns.len(), None);
}
Ok((columns, rows))
}
}
impl<'a, T: Serialize> IntoFuture for Insert<'a, T> {
type Output = Result<ExecResult, Error>;
type IntoFuture = BoxFuture<'a, Self::Output>;
fn into_future(self) -> Self::IntoFuture {
let columns = self.columns();
let Insert {
db,
access,
table,
settings,
query_id,
..
} = self;
Box::pin(async move {
let (columns, rows) = columns?;
if rows.is_empty() {
return Ok(ExecResult::default());
}
let db = db.database()?;
let cx = context();
let insert = core_ch::Insert {
table,
columns,
rows,
settings,
query_id,
};
let summary = db.insert_in(access, insert, &cx).await.map_err(ch_err)?;
Ok(ExecResult::from(summary))
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExecResult {
pub rows_written: u64,
pub bytes_written: u64,
pub rows_read: u64,
pub query_id: String,
}
impl From<core_ch::Summary> for ExecResult {
fn from(s: core_ch::Summary) -> Self {
ExecResult {
rows_written: s.written_rows,
bytes_written: s.written_bytes,
rows_read: s.read_rows,
query_id: s.query_id,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
columns: Arc<[Column]>,
values: Vec<Value>,
}
impl Row {
pub fn columns(&self) -> &[Column] {
&self.columns
}
pub fn values(&self) -> &[Value] {
&self.values
}
pub fn into_values(self) -> Vec<Value> {
self.values
}
pub fn len(&self) -> usize {
self.values.len()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
#[track_caller]
pub fn get<T: DeserializeOwned>(&self, column: impl ColumnIndex) -> T {
match self.try_get(column) {
Ok(v) => v,
Err(err) => panic!("{err}"),
}
}
pub fn try_get<T: DeserializeOwned>(&self, column: impl ColumnIndex) -> Result<T, Error> {
let Some(i) = column.index(&self.columns) else {
return Err(Error::InvalidArgument(format!(
"the row has no column {}",
column.describe()
)));
};
de::from_value(self.values[i].clone())
.map_err(|e| Error::Decode(format!("column {:?}: {e}", self.columns[i].name)))
}
pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T, Error> {
de::from_row(&self.columns, self.values.clone()).map_err(|e| Error::Decode(e.0))
}
}
pub trait ColumnIndex: private::SealedIndex {
#[doc(hidden)]
fn index(&self, columns: &[Column]) -> Option<usize>;
#[doc(hidden)]
fn describe(&self) -> String;
}
impl ColumnIndex for &str {
fn index(&self, columns: &[Column]) -> Option<usize> {
columns.iter().position(|c| c.name == *self)
}
fn describe(&self) -> String {
format!("{self:?}")
}
}
impl ColumnIndex for usize {
fn index(&self, columns: &[Column]) -> Option<usize> {
(*self < columns.len()).then_some(*self)
}
fn describe(&self) -> String {
format!("at {self}")
}
}
pub trait FromRow: Sized + Send + 'static + private::SealedRow {
#[doc(hidden)]
fn from_row(columns: &Arc<[Column]>, values: Vec<Value>) -> Result<Self, Error>;
}
impl FromRow for Row {
fn from_row(columns: &Arc<[Column]>, values: Vec<Value>) -> Result<Self, Error> {
Ok(Row {
columns: columns.clone(),
values,
})
}
}
impl<T: DeserializeOwned + Send + 'static> FromRow for T {
fn from_row(columns: &Arc<[Column]>, values: Vec<Value>) -> Result<Self, Error> {
de::from_row(columns, values).map_err(|e| Error::Decode(e.0))
}
}
mod private {
pub trait SealedRow {}
impl SealedRow for super::Row {}
impl<T: serde::de::DeserializeOwned> SealedRow for T {}
pub trait SealedIndex {}
impl SealedIndex for &str {}
impl SealedIndex for usize {}
}
type CoreNext = (
Box<core_ch::Rows>,
Result<Option<Vec<Value>>, core_ch::Error>,
);
enum State {
Idle(Box<core_ch::Rows>),
Reading(BoxFuture<'static, CoreNext>),
Done,
}
pub struct RowStream<T = Row> {
columns: Arc<[Column]>,
query_id: String,
state: State,
row: PhantomData<fn() -> T>,
}
impl<T: FromRow> RowStream<T> {
fn new(rows: core_ch::Rows) -> Self {
RowStream {
columns: rows.columns().clone(),
query_id: rows.query_id().to_string(),
state: State::Idle(Box::new(rows)),
row: PhantomData,
}
}
pub fn columns(&self) -> &[Column] {
&self.columns
}
pub fn query_id(&self) -> &str {
&self.query_id
}
pub async fn next(&mut self) -> Option<Result<T, Error>> {
std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
}
async fn next_values(&mut self) -> Result<Option<Vec<Value>>, Error> {
std::future::poll_fn(|cx| self.poll_values(cx)).await
}
fn poll_values(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<Vec<Value>>, Error>> {
loop {
match std::mem::replace(&mut self.state, State::Done) {
State::Done => return Poll::Ready(Ok(None)),
State::Idle(mut rows) => {
self.state = State::Reading(Box::pin(async move {
let next = rows.next().await;
(rows, next)
}));
}
State::Reading(mut fut) => match fut.as_mut().poll(cx) {
Poll::Pending => {
self.state = State::Reading(fut);
return Poll::Pending;
}
Poll::Ready((rows, result)) => {
return Poll::Ready(match result {
Ok(Some(values)) => {
self.state = State::Idle(rows);
Ok(Some(values))
}
Ok(None) => Ok(None),
Err(e) => Err(ch_err(e)),
});
}
},
}
}
}
}
impl<T: FromRow> Stream for RowStream<T> {
type Item = Result<T, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
this.poll_values(cx).map(|r| match r {
Ok(Some(values)) => Some(T::from_row(&this.columns, values)),
Ok(None) => None,
Err(e) => Some(Err(e)),
})
}
}
impl<T> std::fmt::Debug for RowStream<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RowStream")
.field("columns", &self.columns)
.field("query_id", &self.query_id)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("{message}")]
Server {
code: i32,
name: String,
message: String,
},
#[error("ClickHouse is unavailable: {0}")]
Unavailable(String),
#[error("the ClickHouse call was canceled")]
Canceled,
#[error("decode the ClickHouse response: {0}")]
Decode(String),
#[error("{0}")]
InvalidArgument(String),
#[error("the query returned no rows")]
NoRows,
#[error("the query returned more than one row")]
TooManyRows,
}
impl Error {
pub fn code(&self) -> Option<i32> {
match self {
Error::Server { code, .. } => Some(*code),
_ => None,
}
}
}
fn ch_err(err: core_ch::Error) -> Error {
match err {
core_ch::Error::Server {
code,
name,
message,
} => Error::Server {
code,
name,
message,
},
core_ch::Error::Unavailable(m) => Error::Unavailable(m),
core_ch::Error::Canceled => Error::Canceled,
core_ch::Error::Decode(m) => Error::Decode(m),
core_ch::Error::InvalidArgument(m) => Error::InvalidArgument(m),
core_ch::Error::NoRows => Error::NoRows,
core_ch::Error::TooManyRows => Error::TooManyRows,
}
}
fn test_err(err: crate::Error) -> Error {
Error::Unavailable(err.to_string())
}
fn context() -> OtelContext {
testing::outgoing(&OtelContext::current())
}