Skip to main content

encore/storage/clickhouse/
mod.rs

1//! ClickHouse databases.
2//!
3//! Databases are declared at module scope and accessed over ClickHouse's HTTP
4//! interface. Each call runs as a single HTTP request using the database user
5//! for the handle's access level.
6//!
7//! ```no_run
8//! use encore::storage::clickhouse::{self, Database};
9//!
10//! static EVENTS: Database = Database::new("events").migrations("./migrations");
11//!
12//! #[derive(serde::Serialize, serde::Deserialize)]
13//! struct Event {
14//!     id: u64,
15//!     kind: String,
16//!     at: chrono::DateTime<chrono::Utc>,
17//! }
18//!
19//! async fn record(events: &[Event]) -> Result<(), clickhouse::Error> {
20//!     EVENTS.insert("events", events).await?;
21//!     Ok(())
22//! }
23//!
24//! async fn of_kind(kind: &str) -> Result<Vec<Event>, clickhouse::Error> {
25//!     EVENTS
26//!         .read()
27//!         .query("SELECT id, kind, at FROM events WHERE kind = {kind:String} ORDER BY at")
28//!         .param("kind", kind)
29//!         .fetch_all()
30//!         .await
31//! }
32//! ```
33//!
34//! # Queries
35//!
36//! [`Database::query`] starts a [`Query`]. Configure parameters, settings, and
37//! a query ID on it, then run it with a `fetch` method:
38//!
39//! - [`Query::fetch_all`] reads all rows.
40//! - [`Query::fetch_one`] reads exactly one row, returning [`Error::NoRows`] or
41//!   [`Error::TooManyRows`] otherwise.
42//! - [`Query::fetch_optional`] reads at most one row.
43//! - [`Query::fetch`] returns a [`RowStream`] (which implements [`Stream`]) that
44//!   streams rows as they arrive. Dropping the stream cancels read queries on
45//!   the server.
46//!
47//! Each method decodes rows into the requested type: either [`Row`] directly, or
48//! any [`serde::Deserialize`] type matched by column name (see
49//! [Reading rows](#reading-rows)).
50//!
51//! [`Database::exec`] runs a statement that returns no rows, such as an
52//! `ALTER TABLE … UPDATE`, and returns an [`ExecResult`].
53//! [`Database::insert`] inserts rows of any type that implements
54//! [`serde::Serialize`] (see [Inserting](#inserting)).
55//!
56//! ClickHouse has no transactions and each request is independent, so `SET`
57//! statements and temporary tables do not carry over between calls. Pass
58//! settings directly to the call that needs them instead:
59//!
60//! ```no_run
61//! # use encore::storage::clickhouse::{Database, Error};
62//! # static EVENTS: Database = Database::named("events");
63//! async fn count() -> Result<u64, Error> {
64//!     EVENTS
65//!         .read()
66//!         .query("SELECT count() FROM events")
67//!         .setting("max_execution_time", "30")
68//!         .fetch_one()
69//!         .await
70//! }
71//! ```
72//!
73//! # Parameters
74//!
75//! ClickHouse binds parameters on the server. Name each parameter and its type
76//! in the SQL (`{name:Type}`), then supply its value with [`Query::param`]. Any
77//! [`Param`] type is accepted: integers, floats, `bool`, strings, bytes,
78//! [`uuid::Uuid`], `chrono` timestamps and dates, IP addresses, `Option`s,
79//! `Vec`s, maps, or a [`Value`] for any other type. Values are never interpolated
80//! into the SQL string.
81//!
82//! ```no_run
83//! # use encore::storage::clickhouse::{Database, Error};
84//! # static EVENTS: Database = Database::named("events");
85//! async fn since(kinds: Vec<String>, at: chrono::DateTime<chrono::Utc>) -> Result<u64, Error> {
86//!     EVENTS
87//!         .read()
88//!         .query(
89//!             "SELECT count() FROM events \
90//!              WHERE kind IN {kinds:Array(String)} AND at >= {at:DateTime64(6)}",
91//!         )
92//!         .param("kinds", kinds)
93//!         .param("at", at)
94//!         .fetch_one()
95//!         .await
96//! }
97//! ```
98//!
99//! # Reading rows
100//!
101//! When deserializing a row into a type that implements [`serde::Deserialize`]:
102//!
103//! - Structs and maps are matched by column name (use `#[serde(rename = "…")]`
104//!   to map a field to a different column).
105//! - Tuples are matched by position and must have one element per column.
106//! - Scalar types decode from a single-column row (for example,
107//!   `fetch_one::<u64>()` for `SELECT count()`).
108//!
109//! Each column's [`Value`] maps to Rust types as follows:
110//!
111//! | ClickHouse | Rust |
112//! |---|---|
113//! | integers, floats, `Bool` | the numbers, with a range check; `bool` |
114//! | `Decimal`, `Int256` | `String` (the exact text), a float, a whole integer, or a decimal type that reads strings |
115//! | `String`, `FixedString` | `String` if UTF-8; `Vec<u8>` |
116//! | `UUID` | [`uuid::Uuid`] (with its `serde` feature), `String` |
117//! | `DateTime`, `DateTime64` | [`chrono::DateTime<Utc>`](chrono::DateTime) (RFC 3339 text), an integer (Unix seconds), a float |
118//! | `Date`, `Date32` | [`chrono::NaiveDate`], `String` |
119//! | `Enum8`/`Enum16` | a Rust enum's unit variant of that name, `String` |
120//! | `IPv4`, `IPv6` | [`std::net::IpAddr`] and its variants, `String` |
121//! | `Nullable(T)` | `Option<T>` |
122//! | `Array(T)` | `Vec<T>` |
123//! | `Tuple(…)` | a tuple, or a struct by position |
124//! | `Map(K, V)` | `HashMap`/`BTreeMap`, or a struct |
125//! | `JSON` | anything that reads JSON, such as `serde_json::Value` or a struct; `String` for its text |
126//!
127//! Timestamps decode as UTC text with a trailing `Z`, which `chrono::NaiveDateTime`
128//! does not parse—use `DateTime<Utc>` instead.
129//!
130//! [`Row`] keeps the raw [`Value`]s for each column; use [`Row::get`] to decode
131//! a single column.
132//!
133//! # Inserting
134//!
135//! [`Database::insert`] inserts rows from any [`serde::Serialize`] struct or
136//! map, mapping fields to columns. The inserted column list is the union of all
137//! fields across the batch. If a row omits a column (such as a missing map key
138//! or a field skipped with `#[serde(skip_serializing_if = …)]`), ClickHouse
139//! uses that column's default value. `None` is sent as `NULL`, which also falls
140//! back to the column default for non-`Nullable` columns.
141//!
142//! `chrono` timestamps and dates and `uuid::Uuid` values are serialized as text
143//! that ClickHouse parses into the corresponding column types. Byte slices
144//! (`serde_bytes`) are also serialized as text, which alters non-UTF-8 bytes;
145//! to insert arbitrary binary data, use a parameterized `INSERT … VALUES`
146//! statement with [`Database::exec`].
147//!
148//! # References
149//!
150//! Calling query methods directly on [`Database`] uses write access (reads and
151//! row mutations). Because calls appear directly on the `static`, Encore can
152//! analyze them statically and grant each service only the permissions it uses.
153//!
154//! For this reason, a [`Database`] cannot be passed around by value. To pass a
155//! database to helper functions or libraries, create a [`DatabaseRef`] with the
156//! access level it needs—[`Database::read`], [`Database::write`], or
157//! [`Database::admin`]—which grants that access level to the service. Requests
158//! run as that level's database user: read handles reject writes, and only
159//! admin handles can modify the schema.
160//!
161//! ```no_run
162//! use encore::storage::clickhouse::{Database, DatabaseRef, Error};
163//!
164//! static EVENTS: Database = Database::named("events");
165//! static REPORTS: DatabaseRef = EVENTS.read();
166//!
167//! async fn kinds() -> Result<Vec<(String, u64)>, Error> {
168//!     REPORTS
169//!         .query("SELECT kind, count() FROM events GROUP BY kind")
170//!         .fetch_all()
171//!         .await
172//! }
173//! ```
174//!
175//! # Errors
176//!
177//! Failed calls return this module's [`Error`]:
178//!
179//! - [`Error::Server`]: an error reported by ClickHouse, with its exception
180//!   code and name.
181//! - [`Error::Unavailable`]: the database could not be reached or is not
182//!   configured.
183//! - [`Error::Decode`]: the response or a row could not be decoded into the
184//!   requested type.
185//! - [`Error::InvalidArgument`]: an invalid argument in the call itself.
186//! - [`Error::NoRows`] and [`Error::TooManyRows`]: the query returned a
187//!   different number of rows than expected.
188//!
189//! [`Error`] does not automatically convert into
190//! [`encore::Error`](crate::Error). Match on it when you need to handle
191//! specific cases, and convert it with the appropriate error code where a
192//! function returns [`encore::Error`](crate::Error):
193//!
194//! ```no_run
195//! # use encore::storage::clickhouse::{Database, Error};
196//! # static EVENTS: Database = Database::named("events");
197//! async fn first_seen(id: u64) -> Result<Option<String>, encore::Error> {
198//!     match EVENTS
199//!         .read()
200//!         .query("SELECT min(at) FROM events WHERE id = {id:UInt64} HAVING count() > 0")
201//!         .param("id", id)
202//!         .fetch_optional()
203//!         .await
204//!     {
205//!         Ok(at) => Ok(at),
206//!         Err(Error::Server { name, .. }) if name == "UNKNOWN_TABLE" => Ok(None),
207//!         Err(err) => Err(encore::Error::internal(err.to_string())),
208//!     }
209//! }
210//! ```
211//!
212//! # Tracing
213//!
214//! Each call records a span in the current OpenTelemetry trace context with the
215//! query text and summary. A [`RowStream`] span ends after the last row is read
216//! or when the stream is dropped.
217//!
218//! [`Stream`]: futures_core::Stream
219
220mod de;
221mod param;
222mod ser;
223#[cfg(test)]
224mod tests;
225
226use std::future::IntoFuture;
227use std::marker::PhantomData;
228use std::pin::Pin;
229use std::sync::{Arc, OnceLock};
230use std::task::{Context, Poll};
231
232use encore_sdk_core::clickhouse::{self as core_ch, Access};
233use encore_sdk_core::telemetry::opentelemetry::Context as OtelContext;
234use futures_core::Stream;
235use futures_core::future::BoxFuture;
236use serde::Serialize;
237use serde::de::DeserializeOwned;
238
239use crate::runtime::core;
240use crate::testing;
241
242pub use self::param::{ArrayElement, Param};
243pub use encore_sdk_core::clickhouse::{Column, Type, Value};
244
245/// A ClickHouse database.
246pub struct Database {
247    name: &'static str,
248    /// Read by Encore's parser from the declaration, not by the runtime.
249    #[allow(dead_code)]
250    migrations: Option<&'static str>,
251    db: OnceLock<Arc<core_ch::Database>>,
252}
253
254impl Database {
255    /// Declares a new ClickHouse database.
256    ///
257    /// This function is `const` so it can initialize a module-scope `static`.
258    /// The connection is established on first use. Chain builder methods to
259    /// configure options:
260    ///
261    /// ```no_run
262    /// use encore::storage::clickhouse::Database;
263    ///
264    /// static EVENTS: Database = Database::new("events").migrations("./migrations");
265    /// ```
266    pub const fn new(name: &'static str) -> Self {
267        Self {
268            name,
269            migrations: None,
270            db: OnceLock::new(),
271        }
272    }
273
274    /// References an existing ClickHouse database by name. To declare a new
275    /// database, use [`Database::new`] instead.
276    ///
277    /// `name` must be a string literal so Encore can resolve it statically.
278    /// Referenced databases take no configuration options; options are set
279    /// where the database is declared.
280    ///
281    /// ```no_run
282    /// use encore::storage::clickhouse::Database;
283    ///
284    /// static EVENTS: Database = Database::named("events");
285    /// ```
286    pub const fn named(name: &'static str) -> Self {
287        Self::new(name)
288    }
289
290    /// Sets the directory containing the database's migration files.
291    ///
292    /// `path` must be a slash-separated subdirectory path relative to the file
293    /// declaring the database (for example, `"./migrations"`). Migration files
294    /// are named `{n}_{description}.up.sql` with statements separated by `;`.
295    ///
296    /// Must be called as part of the `static` declaration.
297    pub const fn migrations(mut self, path: &'static str) -> Self {
298        self.migrations = Some(path);
299        self
300    }
301
302    /// Attaches a classification tag (`key`, `value`) to the database, such as
303    /// `.tag("data", "pii")`, for policy evaluation.
304    ///
305    /// Call once per tag with unique keys. Both `key` and `value` must be
306    /// string literals of at most 63 characters (up to 32 tags per database).
307    /// Keys may contain lowercase letters, digits, `_`, and `-`, must start
308    /// with a letter, and cannot start with `encore` (reserved for Encore).
309    /// Values use the same character set or may be empty.
310    ///
311    /// Must be called as part of the `static` declaration.
312    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
313        self
314    }
315
316    /// Returns a handle with admin access, allowing any operation including
317    /// schema changes.
318    ///
319    /// `const`, so it can initialize a module-scope `static`.
320    pub const fn admin(&'static self) -> DatabaseRef {
321        DatabaseRef {
322            db: self,
323            access: Access::Admin,
324        }
325    }
326
327    /// Returns a handle with write access (reads and row mutations such as
328    /// `INSERT`, `ALTER … UPDATE/DELETE`, and `DELETE`).
329    pub const fn write(&'static self) -> DatabaseRef {
330        DatabaseRef {
331            db: self,
332            access: Access::Write,
333        }
334    }
335
336    /// Returns a handle with read-only access (`SELECT` and `SHOW`).
337    ///
338    /// ```no_run
339    /// use encore::storage::clickhouse::{Database, DatabaseRef};
340    ///
341    /// static EVENTS: Database = Database::named("events");
342    /// static REPORTS: DatabaseRef = EVENTS.read();
343    /// ```
344    pub const fn read(&'static self) -> DatabaseRef {
345        DatabaseRef {
346            db: self,
347            access: Access::Read,
348        }
349    }
350
351    /// Begins a query, with write access. See [`DatabaseRef::query`].
352    pub fn query(&self, sql: impl Into<String>) -> Query<'_> {
353        Query::new(self, Access::Write, sql.into())
354    }
355
356    /// Begins a statement that returns no rows, with write access. See
357    /// [`DatabaseRef::exec`].
358    pub fn exec(&self, sql: impl Into<String>) -> Exec<'_> {
359        Exec::new(self, Access::Write, sql.into())
360    }
361
362    /// Begins an insert of `rows` into `table`, with write access. See
363    /// [`DatabaseRef::insert`].
364    pub fn insert<'a, T: Serialize>(&'a self, table: &str, rows: &'a [T]) -> Insert<'a, T> {
365        Insert::new(self, Access::Write, table, rows)
366    }
367
368    /// Returns a connection URL (`http[s]://user:password@host:port/database`)
369    /// with write access for use with external ClickHouse clients. See
370    /// [`DatabaseRef::connection_string`].
371    pub fn connection_string(&self) -> Result<String, Error> {
372        self.connection_string_as(Access::Write)
373    }
374
375    fn connection_string_as(&self, access: Access) -> Result<String, Error> {
376        self.database()?.connection_string(access).map_err(ch_err)
377    }
378
379    /// The database calls are made on: the configured one, or under `encore
380    /// test` the current test's instance of it (see [`crate::testing`]).
381    fn database(&self) -> Result<Arc<core_ch::Database>, Error> {
382        if let Some(test) = testing::active().map_err(test_err)? {
383            return test.clickhouse_database(self.name).map_err(test_err);
384        }
385        if let Some(db) = self.db.get() {
386            return Ok(db.clone());
387        }
388        let db = core().clickhouse().database(&self.name.into());
389        // One that can't be reached says why on each call, and is asked for
390        // again on the next: the runtime may yet have it.
391        if db.cloud_name().is_ok() {
392            // A concurrent caller may win the race; either way it's the same.
393            let _ = self.db.set(db.clone());
394        }
395        Ok(db)
396    }
397}
398
399/// A handle to a [`Database`] with a fixed access level, created by
400/// [`Database::admin`], [`Database::write`], or [`Database::read`].
401///
402/// `DatabaseRef` is `Copy` and can be freely passed to other code. Calls run as
403/// the database user for its access level. If the runtime has no user for that
404/// level, it falls back to the next higher level and sets `readonly = 2` on
405/// read handles so writes are still rejected.
406#[derive(Clone, Copy)]
407pub struct DatabaseRef {
408    db: &'static Database,
409    access: Access,
410}
411
412impl DatabaseRef {
413    /// Starts a query. Set parameters, settings, and an optional query ID on
414    /// the returned [`Query`], then run it with a `fetch` method.
415    ///
416    /// ```no_run
417    /// # use encore::storage::clickhouse::{Database, Error};
418    /// # static EVENTS: Database = Database::named("events");
419    /// async fn kinds(id: u64) -> Result<Vec<String>, Error> {
420    ///     EVENTS
421    ///         .read()
422    ///         .query("SELECT kind FROM events WHERE id = {id:UInt64}")
423    ///         .param("id", id)
424    ///         .fetch_all()
425    ///         .await
426    /// }
427    /// ```
428    pub fn query(&self, sql: impl Into<String>) -> Query<'static> {
429        Query::new(self.db, self.access, sql.into())
430    }
431
432    /// Starts a statement that returns no rows, such as `ALTER TABLE … UPDATE`
433    /// or `INSERT … SELECT`. Set parameters and settings on the returned
434    /// [`Exec`], then await it for an [`ExecResult`]. Any rows returned by the
435    /// server are discarded.
436    ///
437    /// ```no_run
438    /// # use encore::storage::clickhouse::{Database, Error};
439    /// # static EVENTS: Database = Database::named("events");
440    /// async fn forget(id: u64) -> Result<(), Error> {
441    ///     EVENTS
442    ///         .write()
443    ///         .exec("DELETE FROM events WHERE id = {id:UInt64}")
444    ///         .param("id", id)
445    ///         .await?;
446    ///     Ok(())
447    /// }
448    /// ```
449    pub fn exec(&self, sql: impl Into<String>) -> Exec<'static> {
450        Exec::new(self.db, self.access, sql.into())
451    }
452
453    /// Starts an insert of `rows` into `table` (`table` or `db.table`). Each
454    /// row must serialize as a struct or map whose fields match column names
455    /// (see the [module docs](self#inserting)). Configure optional settings
456    /// such as `async_insert` on the returned [`Insert`], then await it for an
457    /// [`ExecResult`].
458    ///
459    /// ```no_run
460    /// # use encore::storage::clickhouse::{Database, Error};
461    /// # static EVENTS: Database = Database::named("events");
462    /// #[derive(serde::Serialize)]
463    /// struct Event<'a> {
464    ///     id: u64,
465    ///     kind: &'a str,
466    /// }
467    ///
468    /// async fn record(id: u64) -> Result<(), Error> {
469    ///     EVENTS
470    ///         .write()
471    ///         .insert("events", &[Event { id, kind: "signup" }])
472    ///         .await?;
473    ///     Ok(())
474    /// }
475    /// ```
476    pub fn insert<'a, T: Serialize>(&self, table: &str, rows: &'a [T]) -> Insert<'a, T> {
477        Insert::new(self.db, self.access, table, rows)
478    }
479
480    /// Returns a connection URL (`http[s]://user:password@host:port/database`)
481    /// for use with external ClickHouse clients, with URL-encoded credentials
482    /// for this handle's access level.
483    ///
484    /// If the runtime has no user for this access level, the URL uses the next
485    /// higher level's credentials. In that case, `readonly` is not embedded in
486    /// the URL—configure it on your client if you want read-only enforcement.
487    pub fn connection_string(&self) -> Result<String, Error> {
488        self.db.connection_string_as(self.access)
489    }
490}
491
492/// A query builder created by [`Database::query`] or [`DatabaseRef::query`].
493///
494/// Configure parameters, settings, and an optional query ID, then run it with a
495/// `fetch` method.
496#[must_use = "a query does nothing until a `fetch` method runs it"]
497pub struct Query<'a> {
498    db: &'a Database,
499    access: Access,
500    query: core_ch::Query,
501}
502
503impl<'a> Query<'a> {
504    fn new(db: &'a Database, access: Access, sql: String) -> Self {
505        Query {
506            db,
507            access,
508            query: core_ch::Query::new(sql),
509        }
510    }
511
512    /// Binds `value` to the `{name:Type}` parameter placeholder. See [`Param`]
513    /// for supported types.
514    pub fn param(mut self, name: impl Into<String>, value: impl Into<Param>) -> Self {
515        self.query.params.push((name.into(), value.into().0));
516        self
517    }
518
519    /// Sets a ClickHouse query setting such as `max_execution_time`. Unknown
520    /// settings are reported as server errors.
521    pub fn setting(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
522        self.query.settings.push((name.into(), value.into()));
523        self
524    }
525
526    /// Sets an explicit server-side query ID (visible in `system.query_log`)
527    /// instead of letting ClickHouse generate one.
528    pub fn query_id(mut self, id: impl Into<String>) -> Self {
529        self.query.query_id = Some(id.into());
530        self
531    }
532
533    /// Runs the query and streams rows as they arrive, decoding each as `T`
534    /// (either [`Row`] or a [`serde::Deserialize`] type).
535    ///
536    /// ```no_run
537    /// # use encore::storage::clickhouse::{Database, Error, Row};
538    /// # static EVENTS: Database = Database::named("events");
539    /// async fn scan() -> Result<u64, Error> {
540    ///     let mut rows = EVENTS.read().query("SELECT id FROM events").fetch::<u64>().await?;
541    ///     let mut sum = 0;
542    ///     while let Some(id) = rows.next().await {
543    ///         sum += id?;
544    ///     }
545    ///     Ok(sum)
546    /// }
547    /// ```
548    pub async fn fetch<T: FromRow>(self) -> Result<RowStream<T>, Error> {
549        let db = self.db.database()?;
550        let cx = context();
551        let rows = db
552            .query_in(self.access, self.query, &cx)
553            .await
554            .map_err(ch_err)?;
555        Ok(RowStream::new(rows))
556    }
557
558    /// Runs the query and collects all rows decoded as `T`.
559    pub async fn fetch_all<T: FromRow>(self) -> Result<Vec<T>, Error> {
560        let mut rows = self.fetch::<T>().await?;
561        let mut out = Vec::new();
562        while let Some(row) = rows.next().await {
563            out.push(row?);
564        }
565        Ok(out)
566    }
567
568    /// Runs the query and returns its single row decoded as `T`.
569    ///
570    /// Returns [`Error::NoRows`] if no rows are returned, or
571    /// [`Error::TooManyRows`] if more than one row is returned.
572    pub async fn fetch_one<T: FromRow>(self) -> Result<T, Error> {
573        self.fetch_optional().await?.ok_or(Error::NoRows)
574    }
575
576    /// Runs the query and returns at most one row decoded as `T`.
577    ///
578    /// Returns [`Error::TooManyRows`] if more than one row is returned.
579    pub async fn fetch_optional<T: FromRow>(self) -> Result<Option<T>, Error> {
580        let mut rows = self.fetch::<T>().await?;
581        let Some(first) = rows.next().await.transpose()? else {
582            return Ok(None);
583        };
584        if rows.next_values().await?.is_some() {
585            return Err(Error::TooManyRows);
586        }
587        Ok(Some(first))
588    }
589}
590
591/// A statement builder created by [`Database::exec`] or [`DatabaseRef::exec`].
592///
593/// Configure parameters, settings, and an optional query ID, then await it.
594#[must_use = "a statement does nothing until it is awaited"]
595pub struct Exec<'a> {
596    inner: Query<'a>,
597}
598
599impl<'a> Exec<'a> {
600    fn new(db: &'a Database, access: Access, sql: String) -> Self {
601        Exec {
602            inner: Query::new(db, access, sql),
603        }
604    }
605
606    /// See [`Query::param`].
607    pub fn param(self, name: impl Into<String>, value: impl Into<Param>) -> Self {
608        Exec {
609            inner: self.inner.param(name, value),
610        }
611    }
612
613    /// See [`Query::setting`].
614    pub fn setting(self, name: impl Into<String>, value: impl Into<String>) -> Self {
615        Exec {
616            inner: self.inner.setting(name, value),
617        }
618    }
619
620    /// See [`Query::query_id`].
621    pub fn query_id(self, id: impl Into<String>) -> Self {
622        Exec {
623            inner: self.inner.query_id(id),
624        }
625    }
626}
627
628impl<'a> IntoFuture for Exec<'a> {
629    type Output = Result<ExecResult, Error>;
630    type IntoFuture = BoxFuture<'a, Self::Output>;
631
632    fn into_future(self) -> Self::IntoFuture {
633        let Query { db, access, query } = self.inner;
634        Box::pin(async move {
635            let db = db.database()?;
636            let cx = context();
637            let summary = db.exec_in(access, query, &cx).await.map_err(ch_err)?;
638            Ok(ExecResult::from(summary))
639        })
640    }
641}
642
643/// An insert builder created by [`Database::insert`] or [`DatabaseRef::insert`].
644///
645/// Configure any ClickHouse settings, then await it.
646#[must_use = "an insert does nothing until it is awaited"]
647pub struct Insert<'a, T> {
648    db: &'a Database,
649    access: Access,
650    table: String,
651    rows: &'a [T],
652    settings: Vec<(String, String)>,
653    query_id: Option<String>,
654}
655
656impl<'a, T: Serialize> Insert<'a, T> {
657    fn new(db: &'a Database, access: Access, table: &str, rows: &'a [T]) -> Self {
658        Insert {
659            db,
660            access,
661            table: table.to_string(),
662            rows,
663            settings: Vec::new(),
664            query_id: None,
665        }
666    }
667
668    /// Runs the insert with `id` as its query id on the server.
669    pub fn query_id(mut self, id: impl Into<String>) -> Self {
670        self.query_id = Some(id.into());
671        self
672    }
673
674    /// Runs the insert with the ClickHouse setting `name` set to `value`,
675    /// such as `async_insert`. An unknown setting is the server's error.
676    pub fn setting(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
677        self.settings.push((name.into(), value.into()));
678        self
679    }
680
681    /// The rows' columns, those of every row in the order first seen, and
682    /// each row's values for them: none where a row has no such field, which
683    /// gives the column its default.
684    fn columns(&self) -> Result<(Vec<String>, core_ch::InsertRows), Error> {
685        let mut columns: Vec<String> = Vec::new();
686        let mut index = std::collections::HashMap::new();
687        let mut rows = Vec::with_capacity(self.rows.len());
688        for (i, row) in self.rows.iter().enumerate() {
689            let fields =
690                ser::to_row(row).map_err(|e| Error::InvalidArgument(format!("row {i}: {e}")))?;
691            let mut values = vec![None; columns.len()];
692            for (name, value) in fields {
693                let at = *index.entry(name.clone()).or_insert_with(|| {
694                    columns.push(name);
695                    columns.len() - 1
696                });
697                if at >= values.len() {
698                    values.resize(at + 1, None);
699                }
700                values[at] = Some(value);
701            }
702            rows.push(values);
703        }
704        for row in &mut rows {
705            row.resize(columns.len(), None);
706        }
707        Ok((columns, rows))
708    }
709}
710
711impl<'a, T: Serialize> IntoFuture for Insert<'a, T> {
712    type Output = Result<ExecResult, Error>;
713    type IntoFuture = BoxFuture<'a, Self::Output>;
714
715    fn into_future(self) -> Self::IntoFuture {
716        // Made into values here, so the future doesn't hold the rows.
717        let columns = self.columns();
718        let Insert {
719            db,
720            access,
721            table,
722            settings,
723            query_id,
724            ..
725        } = self;
726        Box::pin(async move {
727            let (columns, rows) = columns?;
728            if rows.is_empty() {
729                return Ok(ExecResult::default());
730            }
731            let db = db.database()?;
732            let cx = context();
733            let insert = core_ch::Insert {
734                table,
735                columns,
736                rows,
737                settings,
738                query_id,
739            };
740            let summary = db.insert_in(access, insert, &cx).await.map_err(ch_err)?;
741            Ok(ExecResult::from(summary))
742        })
743    }
744}
745
746/// Execution summary reported by ClickHouse for a statement or insert.
747#[derive(Clone, Debug, Default, PartialEq, Eq)]
748#[non_exhaustive]
749pub struct ExecResult {
750    /// The rows it wrote.
751    pub rows_written: u64,
752    /// The bytes it wrote, uncompressed.
753    pub bytes_written: u64,
754    /// The rows it read.
755    pub rows_read: u64,
756    /// Its id on the server.
757    pub query_id: String,
758}
759
760impl From<core_ch::Summary> for ExecResult {
761    fn from(s: core_ch::Summary) -> Self {
762        ExecResult {
763            rows_written: s.written_rows,
764            bytes_written: s.written_bytes,
765            rows_read: s.read_rows,
766            query_id: s.query_id,
767        }
768    }
769}
770
771/// A single row from a query result, pairing column metadata with [`Value`]s.
772#[derive(Clone, Debug, PartialEq)]
773pub struct Row {
774    columns: Arc<[Column]>,
775    values: Vec<Value>,
776}
777
778impl Row {
779    /// The row's columns: their names and types.
780    pub fn columns(&self) -> &[Column] {
781        &self.columns
782    }
783
784    /// The row's values, in column order.
785    pub fn values(&self) -> &[Value] {
786        &self.values
787    }
788
789    /// The row's values, in column order.
790    pub fn into_values(self) -> Vec<Value> {
791        self.values
792    }
793
794    /// The number of columns.
795    pub fn len(&self) -> usize {
796        self.values.len()
797    }
798
799    /// Whether the row has no columns.
800    pub fn is_empty(&self) -> bool {
801        self.values.is_empty()
802    }
803
804    /// Decodes a column value as `T`, looking it up by name or zero-based index.
805    ///
806    /// # Panics
807    ///
808    /// Panics if the column does not exist or cannot be decoded as `T`. Use
809    /// [`Row::try_get`] to handle errors instead.
810    #[track_caller]
811    pub fn get<T: DeserializeOwned>(&self, column: impl ColumnIndex) -> T {
812        match self.try_get(column) {
813            Ok(v) => v,
814            Err(err) => panic!("{err}"),
815        }
816    }
817
818    /// Decodes a column value as `T`, looking it up by name or zero-based index.
819    ///
820    /// Returns [`Error::InvalidArgument`] if the column does not exist, or
821    /// [`Error::Decode`] if its value cannot be decoded as `T`.
822    pub fn try_get<T: DeserializeOwned>(&self, column: impl ColumnIndex) -> Result<T, Error> {
823        let Some(i) = column.index(&self.columns) else {
824            return Err(Error::InvalidArgument(format!(
825                "the row has no column {}",
826                column.describe()
827            )));
828        };
829        de::from_value(self.values[i].clone())
830            .map_err(|e| Error::Decode(format!("column {:?}: {e}", self.columns[i].name)))
831    }
832
833    /// Deserializes the entire row into `T`. See [Reading rows](self#reading-rows).
834    pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T, Error> {
835        de::from_row(&self.columns, self.values.clone()).map_err(|e| Error::Decode(e.0))
836    }
837}
838
839/// A column of a [`Row`]: its name (`&str`) or its position (`usize`).
840pub trait ColumnIndex: private::SealedIndex {
841    #[doc(hidden)]
842    fn index(&self, columns: &[Column]) -> Option<usize>;
843    #[doc(hidden)]
844    fn describe(&self) -> String;
845}
846
847impl ColumnIndex for &str {
848    fn index(&self, columns: &[Column]) -> Option<usize> {
849        columns.iter().position(|c| c.name == *self)
850    }
851    fn describe(&self) -> String {
852        format!("{self:?}")
853    }
854}
855
856impl ColumnIndex for usize {
857    fn index(&self, columns: &[Column]) -> Option<usize> {
858        (*self < columns.len()).then_some(*self)
859    }
860    fn describe(&self) -> String {
861        format!("at {self}")
862    }
863}
864
865/// Types that a ClickHouse row can be decoded into: [`Row`] or any type
866/// implementing [`serde::Deserialize`] (see [Reading rows](self#reading-rows)).
867pub trait FromRow: Sized + Send + 'static + private::SealedRow {
868    #[doc(hidden)]
869    fn from_row(columns: &Arc<[Column]>, values: Vec<Value>) -> Result<Self, Error>;
870}
871
872impl FromRow for Row {
873    fn from_row(columns: &Arc<[Column]>, values: Vec<Value>) -> Result<Self, Error> {
874        Ok(Row {
875            columns: columns.clone(),
876            values,
877        })
878    }
879}
880
881impl<T: DeserializeOwned + Send + 'static> FromRow for T {
882    fn from_row(columns: &Arc<[Column]>, values: Vec<Value>) -> Result<Self, Error> {
883        de::from_row(columns, values).map_err(|e| Error::Decode(e.0))
884    }
885}
886
887mod private {
888    pub trait SealedRow {}
889    impl SealedRow for super::Row {}
890    impl<T: serde::de::DeserializeOwned> SealedRow for T {}
891
892    pub trait SealedIndex {}
893    impl SealedIndex for &str {}
894    impl SealedIndex for usize {}
895}
896
897type CoreNext = (
898    Box<core_ch::Rows>,
899    Result<Option<Vec<Value>>, core_ch::Error>,
900);
901
902/// Where a [`RowStream`] is: between rows, or waiting for the next.
903enum State {
904    Idle(Box<core_ch::Rows>),
905    Reading(BoxFuture<'static, CoreNext>),
906    Done,
907}
908
909/// A stream of rows returned by [`Query::fetch`], decoding each row as `T`.
910///
911/// Consume rows using [`RowStream::next`] or the [`Stream`] trait. Dropping the
912/// stream before the last row cancels read queries on the server.
913///
914/// [`Stream`]: futures_core::Stream
915pub struct RowStream<T = Row> {
916    columns: Arc<[Column]>,
917    query_id: String,
918    state: State,
919    row: PhantomData<fn() -> T>,
920}
921
922impl<T: FromRow> RowStream<T> {
923    fn new(rows: core_ch::Rows) -> Self {
924        RowStream {
925            columns: rows.columns().clone(),
926            query_id: rows.query_id().to_string(),
927            state: State::Idle(Box::new(rows)),
928            row: PhantomData,
929        }
930    }
931
932    /// The columns of the rows: their names and types.
933    pub fn columns(&self) -> &[Column] {
934        &self.columns
935    }
936
937    /// The query's id on the server.
938    pub fn query_id(&self) -> &str {
939        &self.query_id
940    }
941
942    /// The next row, or `None` after the last.
943    pub async fn next(&mut self) -> Option<Result<T, Error>> {
944        std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
945    }
946
947    /// The next row's values, unread.
948    async fn next_values(&mut self) -> Result<Option<Vec<Value>>, Error> {
949        std::future::poll_fn(|cx| self.poll_values(cx)).await
950    }
951
952    fn poll_values(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<Vec<Value>>, Error>> {
953        loop {
954            match std::mem::replace(&mut self.state, State::Done) {
955                State::Done => return Poll::Ready(Ok(None)),
956                State::Idle(mut rows) => {
957                    self.state = State::Reading(Box::pin(async move {
958                        let next = rows.next().await;
959                        (rows, next)
960                    }));
961                }
962                State::Reading(mut fut) => match fut.as_mut().poll(cx) {
963                    Poll::Pending => {
964                        self.state = State::Reading(fut);
965                        return Poll::Pending;
966                    }
967                    Poll::Ready((rows, result)) => {
968                        return Poll::Ready(match result {
969                            Ok(Some(values)) => {
970                                self.state = State::Idle(rows);
971                                Ok(Some(values))
972                            }
973                            // The rows end, or fail: dropped, so their span
974                            // ends now.
975                            Ok(None) => Ok(None),
976                            Err(e) => Err(ch_err(e)),
977                        });
978                    }
979                },
980            }
981        }
982    }
983}
984
985impl<T: FromRow> Stream for RowStream<T> {
986    type Item = Result<T, Error>;
987
988    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
989        let this = self.get_mut();
990        this.poll_values(cx).map(|r| match r {
991            Ok(Some(values)) => Some(T::from_row(&this.columns, values)),
992            Ok(None) => None,
993            Err(e) => Some(Err(e)),
994        })
995    }
996}
997
998impl<T> std::fmt::Debug for RowStream<T> {
999    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1000        f.debug_struct("RowStream")
1001            .field("columns", &self.columns)
1002            .field("query_id", &self.query_id)
1003            .finish_non_exhaustive()
1004    }
1005}
1006
1007/// Errors returned by ClickHouse operations. See the [module docs](self#errors).
1008///
1009/// Does not convert automatically into [`encore::Error`](crate::Error); map it
1010/// to the appropriate error code at API boundaries.
1011#[derive(Clone, Debug, PartialEq, thiserror::Error)]
1012#[non_exhaustive]
1013pub enum Error {
1014    /// The server rejected or failed the query.
1015    #[error("{message}")]
1016    Server {
1017        /// ClickHouse exception code (for example, `60` for `UNKNOWN_TABLE`),
1018        /// or `0` if none was provided.
1019        code: i32,
1020        /// ClickHouse exception name (for example, `UNKNOWN_TABLE`), or empty
1021        /// if the server message did not include one.
1022        name: String,
1023        /// Error message from the server.
1024        message: String,
1025    },
1026    /// The database could not be reached or is not configured for this service
1027    /// at the required access level.
1028    #[error("ClickHouse is unavailable: {0}")]
1029    Unavailable(String),
1030    /// The call was canceled.
1031    #[error("ClickHouse call canceled")]
1032    Canceled,
1033    /// A response or row could not be decoded into the requested type.
1034    #[error("failed to decode ClickHouse response: {0}")]
1035    Decode(String),
1036    /// Invalid argument passed to the call (such as an empty table name or a
1037    /// row that is not a struct or map).
1038    #[error("{0}")]
1039    InvalidArgument(String),
1040    /// A query expecting a row returned none.
1041    #[error("the query returned no rows")]
1042    NoRows,
1043    /// A query expecting at most one row returned multiple rows.
1044    #[error("the query returned more than one row")]
1045    TooManyRows,
1046}
1047
1048impl Error {
1049    /// ClickHouse's exception code, for a [`Error::Server`].
1050    pub fn code(&self) -> Option<i32> {
1051        match self {
1052            Error::Server { code, .. } => Some(*code),
1053            _ => None,
1054        }
1055    }
1056}
1057
1058/// The core's error as this module's.
1059fn ch_err(err: core_ch::Error) -> Error {
1060    match err {
1061        core_ch::Error::Server {
1062            code,
1063            name,
1064            message,
1065        } => Error::Server {
1066            code,
1067            name,
1068            message,
1069        },
1070        core_ch::Error::Unavailable(m) => Error::Unavailable(m),
1071        core_ch::Error::Canceled => Error::Canceled,
1072        core_ch::Error::Decode(m) => Error::Decode(m),
1073        core_ch::Error::InvalidArgument(m) => Error::InvalidArgument(m),
1074        core_ch::Error::NoRows => Error::NoRows,
1075        core_ch::Error::TooManyRows => Error::TooManyRows,
1076    }
1077}
1078
1079/// `err`, from setting up the current test's instance of a database under
1080/// `encore test`, as this module's error.
1081fn test_err(err: crate::Error) -> Error {
1082    Error::Unavailable(err.to_string())
1083}
1084
1085/// The context a call's span is started in: the caller's, made the current
1086/// test's in a system test's process, as every SDK call's is.
1087fn context() -> OtelContext {
1088    testing::outgoing_if_known(&OtelContext::current())
1089}