Skip to main content

encore/storage/clickhouse/
mod.rs

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