encore-dev 2.0.0

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

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::Stream;
use futures_core::future::BoxFuture;
use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::runtime::core;
use crate::testing;

pub use self::param::{ArrayElement, Param};
pub use encore_sdk_core::clickhouse::{Column, Type, Value};

/// A ClickHouse database.
pub struct Database {
    name: &'static str,
    /// Read by Encore's parser from the declaration, not by the runtime.
    #[allow(dead_code)]
    migrations: Option<&'static str>,
    db: OnceLock<Arc<core_ch::Database>>,
}

impl Database {
    /// Declares a new ClickHouse database.
    ///
    /// This function is `const` so it can initialize a module-scope `static`.
    /// The connection is established on first use. Chain builder methods to
    /// configure options:
    ///
    /// ```no_run
    /// use encore::storage::clickhouse::Database;
    ///
    /// static EVENTS: Database = Database::new("events").migrations("./migrations");
    /// ```
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            migrations: None,
            db: OnceLock::new(),
        }
    }

    /// References an existing ClickHouse database by name. To declare a new
    /// database, use [`Database::new`] instead.
    ///
    /// `name` must be a string literal so Encore can resolve it statically.
    /// Referenced databases take no configuration options; options are set
    /// where the database is declared.
    ///
    /// ```no_run
    /// use encore::storage::clickhouse::Database;
    ///
    /// static EVENTS: Database = Database::named("events");
    /// ```
    pub const fn named(name: &'static str) -> Self {
        Self::new(name)
    }

    /// Sets the directory containing the database's migration files.
    ///
    /// `path` must be a slash-separated subdirectory path relative to the file
    /// declaring the database (for example, `"./migrations"`). Migration files
    /// are named `{n}_{description}.up.sql` with statements separated by `;`.
    ///
    /// Must be called as part of the `static` declaration.
    pub const fn migrations(mut self, path: &'static str) -> Self {
        self.migrations = Some(path);
        self
    }

    /// Attaches a classification tag (`key`, `value`) to the database, such as
    /// `.tag("data", "pii")`, for policy evaluation.
    ///
    /// Call once per tag with unique keys. Both `key` and `value` must be
    /// string literals of at most 63 characters (up to 32 tags per database).
    /// Keys may contain lowercase letters, digits, `_`, and `-`, must start
    /// with a letter, and cannot start with `encore` (reserved for Encore).
    /// Values use the same character set or may be empty.
    ///
    /// Must be called as part of the `static` declaration.
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

    /// Returns a handle with admin access, allowing any operation including
    /// schema changes.
    ///
    /// `const`, so it can initialize a module-scope `static`.
    pub const fn admin(&'static self) -> DatabaseRef {
        DatabaseRef {
            db: self,
            access: Access::Admin,
        }
    }

    /// Returns a handle with write access (reads and row mutations such as
    /// `INSERT`, `ALTER … UPDATE/DELETE`, and `DELETE`).
    pub const fn write(&'static self) -> DatabaseRef {
        DatabaseRef {
            db: self,
            access: Access::Write,
        }
    }

    /// Returns a handle with read-only access (`SELECT` and `SHOW`).
    ///
    /// ```no_run
    /// use encore::storage::clickhouse::{Database, DatabaseRef};
    ///
    /// static EVENTS: Database = Database::named("events");
    /// static REPORTS: DatabaseRef = EVENTS.read();
    /// ```
    pub const fn read(&'static self) -> DatabaseRef {
        DatabaseRef {
            db: self,
            access: Access::Read,
        }
    }

    /// Begins a query, with write access. See [`DatabaseRef::query`].
    pub fn query(&self, sql: impl Into<String>) -> Query<'_> {
        Query::new(self, Access::Write, sql.into())
    }

    /// Begins a statement that returns no rows, with write access. See
    /// [`DatabaseRef::exec`].
    pub fn exec(&self, sql: impl Into<String>) -> Exec<'_> {
        Exec::new(self, Access::Write, sql.into())
    }

    /// Begins an insert of `rows` into `table`, with write access. See
    /// [`DatabaseRef::insert`].
    pub fn insert<'a, T: Serialize>(&'a self, table: &str, rows: &'a [T]) -> Insert<'a, T> {
        Insert::new(self, Access::Write, table, rows)
    }

    /// Returns a connection URL (`http[s]://user:password@host:port/database`)
    /// with write access for use with external ClickHouse clients. See
    /// [`DatabaseRef::connection_string`].
    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)
    }

    /// The database calls are made on: the configured one, or under `encore
    /// test` the current test's instance of it (see [`crate::testing`]).
    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());
        // One that can't be reached says why on each call, and is asked for
        // again on the next: the runtime may yet have it.
        if db.cloud_name().is_ok() {
            // A concurrent caller may win the race; either way it's the same.
            let _ = self.db.set(db.clone());
        }
        Ok(db)
    }
}

/// A handle to a [`Database`] with a fixed access level, created by
/// [`Database::admin`], [`Database::write`], or [`Database::read`].
///
/// `DatabaseRef` is `Copy` and can be freely passed to other code. Calls run as
/// the database user for its access level. If the runtime has no user for that
/// level, it falls back to the next higher level and sets `readonly = 2` on
/// read handles so writes are still rejected.
#[derive(Clone, Copy)]
pub struct DatabaseRef {
    db: &'static Database,
    access: Access,
}

impl DatabaseRef {
    /// Starts a query. Set parameters, settings, and an optional query ID on
    /// the returned [`Query`], then run it with a `fetch` method.
    ///
    /// ```no_run
    /// # use encore::storage::clickhouse::{Database, Error};
    /// # static EVENTS: Database = Database::named("events");
    /// async fn kinds(id: u64) -> Result<Vec<String>, Error> {
    ///     EVENTS
    ///         .read()
    ///         .query("SELECT kind FROM events WHERE id = {id:UInt64}")
    ///         .param("id", id)
    ///         .fetch_all()
    ///         .await
    /// }
    /// ```
    pub fn query(&self, sql: impl Into<String>) -> Query<'static> {
        Query::new(self.db, self.access, sql.into())
    }

    /// Starts a statement that returns no rows, such as `ALTER TABLE … UPDATE`
    /// or `INSERT … SELECT`. Set parameters and settings on the returned
    /// [`Exec`], then await it for an [`ExecResult`]. Any rows returned by the
    /// server are discarded.
    ///
    /// ```no_run
    /// # use encore::storage::clickhouse::{Database, Error};
    /// # static EVENTS: Database = Database::named("events");
    /// async fn forget(id: u64) -> Result<(), Error> {
    ///     EVENTS
    ///         .write()
    ///         .exec("DELETE FROM events WHERE id = {id:UInt64}")
    ///         .param("id", id)
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn exec(&self, sql: impl Into<String>) -> Exec<'static> {
        Exec::new(self.db, self.access, sql.into())
    }

    /// Starts an insert of `rows` into `table` (`table` or `db.table`). Each
    /// row must serialize as a struct or map whose fields match column names
    /// (see the [module docs](self#inserting)). Configure optional settings
    /// such as `async_insert` on the returned [`Insert`], then await it for an
    /// [`ExecResult`].
    ///
    /// ```no_run
    /// # use encore::storage::clickhouse::{Database, Error};
    /// # static EVENTS: Database = Database::named("events");
    /// #[derive(serde::Serialize)]
    /// struct Event<'a> {
    ///     id: u64,
    ///     kind: &'a str,
    /// }
    ///
    /// async fn record(id: u64) -> Result<(), Error> {
    ///     EVENTS
    ///         .write()
    ///         .insert("events", &[Event { id, kind: "signup" }])
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn insert<'a, T: Serialize>(&self, table: &str, rows: &'a [T]) -> Insert<'a, T> {
        Insert::new(self.db, self.access, table, rows)
    }

    /// Returns a connection URL (`http[s]://user:password@host:port/database`)
    /// for use with external ClickHouse clients, with URL-encoded credentials
    /// for this handle's access level.
    ///
    /// If the runtime has no user for this access level, the URL uses the next
    /// higher level's credentials. In that case, `readonly` is not embedded in
    /// the URL—configure it on your client if you want read-only enforcement.
    pub fn connection_string(&self) -> Result<String, Error> {
        self.db.connection_string_as(self.access)
    }
}

/// A query builder created by [`Database::query`] or [`DatabaseRef::query`].
///
/// Configure parameters, settings, and an optional query ID, then run it with a
/// `fetch` method.
#[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),
        }
    }

    /// Binds `value` to the `{name:Type}` parameter placeholder. See [`Param`]
    /// for supported types.
    pub fn param(mut self, name: impl Into<String>, value: impl Into<Param>) -> Self {
        self.query.params.push((name.into(), value.into().0));
        self
    }

    /// Sets a ClickHouse query setting such as `max_execution_time`. Unknown
    /// settings are reported as server errors.
    pub fn setting(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.query.settings.push((name.into(), value.into()));
        self
    }

    /// Sets an explicit server-side query ID (visible in `system.query_log`)
    /// instead of letting ClickHouse generate one.
    pub fn query_id(mut self, id: impl Into<String>) -> Self {
        self.query.query_id = Some(id.into());
        self
    }

    /// Runs the query and streams rows as they arrive, decoding each as `T`
    /// (either [`Row`] or a [`serde::Deserialize`] type).
    ///
    /// ```no_run
    /// # use encore::storage::clickhouse::{Database, Error, Row};
    /// # static EVENTS: Database = Database::named("events");
    /// async fn scan() -> Result<u64, Error> {
    ///     let mut rows = EVENTS.read().query("SELECT id FROM events").fetch::<u64>().await?;
    ///     let mut sum = 0;
    ///     while let Some(id) = rows.next().await {
    ///         sum += id?;
    ///     }
    ///     Ok(sum)
    /// }
    /// ```
    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))
    }

    /// Runs the query and collects all rows decoded as `T`.
    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)
    }

    /// Runs the query and returns its single row decoded as `T`.
    ///
    /// Returns [`Error::NoRows`] if no rows are returned, or
    /// [`Error::TooManyRows`] if more than one row is returned.
    pub async fn fetch_one<T: FromRow>(self) -> Result<T, Error> {
        self.fetch_optional().await?.ok_or(Error::NoRows)
    }

    /// Runs the query and returns at most one row decoded as `T`.
    ///
    /// Returns [`Error::TooManyRows`] if more than one row is returned.
    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))
    }
}

/// A statement builder created by [`Database::exec`] or [`DatabaseRef::exec`].
///
/// Configure parameters, settings, and an optional query ID, then await it.
#[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),
        }
    }

    /// See [`Query::param`].
    pub fn param(self, name: impl Into<String>, value: impl Into<Param>) -> Self {
        Exec {
            inner: self.inner.param(name, value),
        }
    }

    /// See [`Query::setting`].
    pub fn setting(self, name: impl Into<String>, value: impl Into<String>) -> Self {
        Exec {
            inner: self.inner.setting(name, value),
        }
    }

    /// See [`Query::query_id`].
    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))
        })
    }
}

/// An insert builder created by [`Database::insert`] or [`DatabaseRef::insert`].
///
/// Configure any ClickHouse settings, then await it.
#[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,
        }
    }

    /// Runs the insert with `id` as its query id on the server.
    pub fn query_id(mut self, id: impl Into<String>) -> Self {
        self.query_id = Some(id.into());
        self
    }

    /// Runs the insert with the ClickHouse setting `name` set to `value`,
    /// such as `async_insert`. An unknown setting is the server's error.
    pub fn setting(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.settings.push((name.into(), value.into()));
        self
    }

    /// The rows' columns, those of every row in the order first seen, and
    /// each row's values for them: none where a row has no such field, which
    /// gives the column its default.
    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 {
        // Made into values here, so the future doesn't hold the rows.
        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))
        })
    }
}

/// Execution summary reported by ClickHouse for a statement or insert.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExecResult {
    /// The rows it wrote.
    pub rows_written: u64,
    /// The bytes it wrote, uncompressed.
    pub bytes_written: u64,
    /// The rows it read.
    pub rows_read: u64,
    /// Its id on the server.
    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,
        }
    }
}

/// A single row from a query result, pairing column metadata with [`Value`]s.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
    columns: Arc<[Column]>,
    values: Vec<Value>,
}

impl Row {
    /// The row's columns: their names and types.
    pub fn columns(&self) -> &[Column] {
        &self.columns
    }

    /// The row's values, in column order.
    pub fn values(&self) -> &[Value] {
        &self.values
    }

    /// The row's values, in column order.
    pub fn into_values(self) -> Vec<Value> {
        self.values
    }

    /// The number of columns.
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Whether the row has no columns.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Decodes a column value as `T`, looking it up by name or zero-based index.
    ///
    /// # Panics
    ///
    /// Panics if the column does not exist or cannot be decoded as `T`. Use
    /// [`Row::try_get`] to handle errors instead.
    #[track_caller]
    pub fn get<T: DeserializeOwned>(&self, column: impl ColumnIndex) -> T {
        match self.try_get(column) {
            Ok(v) => v,
            Err(err) => panic!("{err}"),
        }
    }

    /// Decodes a column value as `T`, looking it up by name or zero-based index.
    ///
    /// Returns [`Error::InvalidArgument`] if the column does not exist, or
    /// [`Error::Decode`] if its value cannot be decoded as `T`.
    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)))
    }

    /// Deserializes the entire row into `T`. See [Reading rows](self#reading-rows).
    pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T, Error> {
        de::from_row(&self.columns, self.values.clone()).map_err(|e| Error::Decode(e.0))
    }
}

/// A column of a [`Row`]: its name (`&str`) or its position (`usize`).
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}")
    }
}

/// Types that a ClickHouse row can be decoded into: [`Row`] or any type
/// implementing [`serde::Deserialize`] (see [Reading rows](self#reading-rows)).
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>,
);

/// Where a [`RowStream`] is: between rows, or waiting for the next.
enum State {
    Idle(Box<core_ch::Rows>),
    Reading(BoxFuture<'static, CoreNext>),
    Done,
}

/// A stream of rows returned by [`Query::fetch`], decoding each row as `T`.
///
/// Consume rows using [`RowStream::next`] or the [`Stream`] trait. Dropping the
/// stream before the last row cancels read queries on the server.
///
/// [`Stream`]: futures_core::Stream
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,
        }
    }

    /// The columns of the rows: their names and types.
    pub fn columns(&self) -> &[Column] {
        &self.columns
    }

    /// The query's id on the server.
    pub fn query_id(&self) -> &str {
        &self.query_id
    }

    /// The next row, or `None` after the last.
    pub async fn next(&mut self) -> Option<Result<T, Error>> {
        std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
    }

    /// The next row's values, unread.
    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))
                            }
                            // The rows end, or fail: dropped, so their span
                            // ends now.
                            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()
    }
}

/// Errors returned by ClickHouse operations. See the [module docs](self#errors).
///
/// Does not convert automatically into [`encore::Error`](crate::Error); map it
/// to the appropriate error code at API boundaries.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The server rejected or failed the query.
    #[error("{message}")]
    Server {
        /// ClickHouse exception code (for example, `60` for `UNKNOWN_TABLE`),
        /// or `0` if none was provided.
        code: i32,
        /// ClickHouse exception name (for example, `UNKNOWN_TABLE`), or empty
        /// if the server message did not include one.
        name: String,
        /// Error message from the server.
        message: String,
    },
    /// The database could not be reached or is not configured for this service
    /// at the required access level.
    #[error("ClickHouse is unavailable: {0}")]
    Unavailable(String),
    /// The call was canceled.
    #[error("ClickHouse call canceled")]
    Canceled,
    /// A response or row could not be decoded into the requested type.
    #[error("failed to decode ClickHouse response: {0}")]
    Decode(String),
    /// Invalid argument passed to the call (such as an empty table name or a
    /// row that is not a struct or map).
    #[error("{0}")]
    InvalidArgument(String),
    /// A query expecting a row returned none.
    #[error("the query returned no rows")]
    NoRows,
    /// A query expecting at most one row returned multiple rows.
    #[error("the query returned more than one row")]
    TooManyRows,
}

impl Error {
    /// ClickHouse's exception code, for a [`Error::Server`].
    pub fn code(&self) -> Option<i32> {
        match self {
            Error::Server { code, .. } => Some(*code),
            _ => None,
        }
    }
}

/// The core's error as this module's.
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,
    }
}

/// `err`, from setting up the current test's instance of a database under
/// `encore test`, as this module's error.
fn test_err(err: crate::Error) -> Error {
    Error::Unavailable(err.to_string())
}

/// The context a call's span is started in: the caller's, made the current
/// test's in a system test's process, as every SDK call's is.
fn context() -> OtelContext {
    testing::outgoing_if_known(&OtelContext::current())
}