encore-dev 2.0.0-beta.13

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
//! ClickHouse databases. Declared at module scope; reached over ClickHouse's
//! HTTP interface, each call one request, as the user of the call'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`] begins a [`Query`]: its parameters, settings and query
//! id are set on it, and a `fetch` method runs it.
//!
//! - [`Query::fetch_all`] reads every row, [`Query::fetch_one`] exactly one
//!   ([`Error::NoRows`] or [`Error::TooManyRows`] otherwise), and
//!   [`Query::fetch_optional`] at most one.
//! - [`Query::fetch`] streams the rows as they arrive: a [`RowStream`], also
//!   a [`Stream`]. Dropping it stops a read's query on the server.
//!
//! Each reads its rows as the type asked for: a [`Row`] as it is, or any type
//! that implements [`serde::Deserialize`], read from the row by its columns'
//! names (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)).
//!
//! There are no transactions, and each request stands alone: `SET` and
//! temporary tables don't carry from one call to the next. Pass settings 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. The SQL names each and says its
//! type, `{name:Type}`, and [`Query::param`] gives its value, any [`Param`]:
//! integers, floats, `bool`, strings, bytes, [`uuid::Uuid`], `chrono`'s
//! timestamps and dates, IP addresses, `Option`s, `Vec`s and maps of them, or
//! a [`Value`] for any other form. Values are never spliced into the SQL.
//!
//! ```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
//!
//! A row read as a type that implements [`serde::Deserialize`] is:
//!
//! - a struct or a map, by column name: a struct's fields are its columns
//!   (`#[serde(rename = "…")]` names another);
//! - a tuple, by position, with as many elements as the row has columns;
//! - anything else, from the row's one column: `fetch_one::<u64>()` of
//!   `SELECT count()`.
//!
//! Each column is read from its [`Value`] as the field's type asks:
//!
//! | 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 |
//!
//! A timestamp is read as text in UTC with a `Z`, which a `chrono`
//! `NaiveDateTime` doesn't read: use `DateTime<Utc>`.
//!
//! A [`Row`] keeps the columns' [`Value`]s as they are: [`Row::get`] reads
//! one of them as a type.
//!
//! # Inserting
//!
//! [`Database::insert`] inserts rows of a type that implements
//! [`serde::Serialize`] as a struct or a map: its fields are the columns. The
//! columns are those of every row together; a column a row doesn't have (a
//! map without the key, or a field `#[serde(skip_serializing_if = …)]`
//! skips) is left out of that row, so it gets the column's default. `None`
//! is `NULL`, which a column that isn't `Nullable` also takes as its
//! default. `chrono` timestamps and
//! dates, and `uuid`s, are written as their text, which ClickHouse reads as
//! its types. Bytes (`serde_bytes`) are written as text too, which changes
//! bytes that are not UTF-8: insert those with a parameterized
//! `INSERT … VALUES` through [`Database::exec`].
//!
//! # References
//!
//! Every query method is a method of the [`Database`], and calling one there
//! uses it with write access: reads and changes to rows. That is what lets
//! Encore grant each service exactly the access it uses: the call shows it,
//! so the parser can read it.
//!
//! So a database cannot be passed around as a value. To hand it to other
//! code, make a [`DatabaseRef`] with the access that code needs —
//! [`Database::read`], [`Database::write`] or [`Database::admin`] — which the
//! service is then granted. Its requests are made as that level's user: a
//! read handle's writes are refused, and only an admin handle may change 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
//!
//! A call that fails returns this module's [`Error`]: what the server
//! reported ([`Error::Server`], with ClickHouse's exception code and its
//! name), a database that can't be reached ([`Error::Unavailable`]), a
//! response or a row that can't be read as asked ([`Error::Decode`]), a
//! mistake in the call ([`Error::InvalidArgument`]), or a row count other
//! than the call wants ([`Error::NoRows`], [`Error::TooManyRows`]).
//!
//! The error is this module's own, and doesn't convert into
//! [`encore::Error`](crate::Error). Match on it where the kind matters, and
//! where a function returns an [`encore::Error`](crate::Error), convert it
//! there with the code that fits:
//!
//! ```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 is a span of the trace it is made in, as the current
//! OpenTelemetry context has it, with the query's text and summary. A
//! [`RowStream`]'s span ends with its last row, or when it 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::future::BoxFuture;
use futures_core::Stream;
use serde::de::DeserializeOwned;
use serde::Serialize;

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

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

/// 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 {
    /// Declare a database. `const` so it can initialize a module-scope
    /// `static`; it is reached on first use.
    ///
    /// Options follow the name, each a method of its own:
    ///
    /// ```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(),
        }
    }

    /// Reference an existing database by name. To declare a new database, use
    /// [`Database::new`] instead.
    ///
    /// The name must be a string literal, so Encore can resolve it statically.
    /// A named database takes no options: it is configured where it 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)
    }

    /// Where the database's migrations are stored: a slash-separated path to
    /// a subdirectory, relative to the file declaring the database, such as
    /// `"./migrations"`. Each is `{n}_{description}.up.sql`, its statements
    /// separated by `;`.
    ///
    /// Part of the declaration: it takes the database by value, so it cannot
    /// be called on the `static`.
    pub const fn migrations(mut self, path: &'static str) -> Self {
        self.migrations = Some(path);
        self
    }

    /// Tags the database with `key` and `value`: key/value classification,
    /// such as `.tag("data", "pii")`, for policies to read. One call per tag,
    /// each with its own key. Encore reads them from the source, so both are
    /// string literals. A key is lowercase letters, digits, `_` and `-`,
    /// starting with a letter and not with `encore`, which is kept for
    /// Encore's own tags; a value is the same characters, or empty. Each is
    /// at most 63 characters, and a database has at most 32 tags.
    ///
    /// Part of the declaration: it takes the database by value, so it cannot
    /// be called on the `static`.
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

    /// A handle to the database with admin access: anything on the
    /// database, its schema included.
    ///
    /// `const`, so a handle can initialize a module-scope `static`.
    pub const fn admin(&'static self) -> DatabaseRef {
        DatabaseRef {
            db: self,
            access: Access::Admin,
        }
    }

    /// A handle to the database with write access: reads, and changes to
    /// rows (`INSERT`, `ALTER … UPDATE/DELETE`, `DELETE`).
    pub const fn write(&'static self) -> DatabaseRef {
        DatabaseRef {
            db: self,
            access: Access::Write,
        }
    }

    /// A handle to the database with read 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)
    }

    /// The URL to connect to the database with, for a ClickHouse client
    /// other than this SDK's, with write access:
    /// `http[s]://user:password@host:port/database`. 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 one level of access, made by
/// [`Database::admin`], [`Database::write`] or [`Database::read`]. `Copy`,
/// and free to pass to other code.
///
/// Its calls are made as the user of its level. Where the runtime has no
/// user of that level, the next one up's is used, and a read handle's calls
/// are then made with the setting `readonly = 2`: a read handle's writes are
/// refused either way.
#[derive(Clone, Copy)]
pub struct DatabaseRef {
    db: &'static Database,
    access: Access,
}

impl DatabaseRef {
    /// Begins a query: set its parameters, settings and 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())
    }

    /// Begins a statement that returns no rows, such as an `ALTER TABLE …
    /// UPDATE` or an `INSERT … SELECT`: set its parameters and settings on
    /// the returned [`Exec`], then await it for an [`ExecResult`]. Any rows
    /// it returns 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())
    }

    /// Begins an insert of `rows` into `table` (`table` or `db.table`): each
    /// row is a struct or map whose fields are its columns (see the [module
    /// docs](self#inserting)). Await it for an [`ExecResult`]; settings for
    /// the insert, such as `async_insert`, are set on the returned [`Insert`].
    ///
    /// ```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)
    }

    /// The URL to connect to the database with, for a ClickHouse client
    /// other than this SDK's: `http[s]://user:password@host:port/database`,
    /// with the user of the handle's level, the user and password
    /// URL-encoded. ClickHouse's clients read the database from the path.
    ///
    /// Where the runtime has no user of the handle's level, the URL has the
    /// next level up's. The `readonly` setting that keeps a read handle's
    /// own calls from writing then isn't in it: set it on the client.
    pub fn connection_string(&self) -> Result<String, Error> {
        self.db.connection_string_as(self.access)
    }
}

/// A query, begun by [`Database::query`] or [`DatabaseRef::query`]: set its
/// parameters, settings and 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),
        }
    }

    /// Gives the parameter `{name:Type}` its value. See [`Param`] for the
    /// values a parameter can have.
    pub fn param(mut self, name: impl Into<String>, value: impl Into<Param>) -> Self {
        self.query.params.push((name.into(), value.into().0));
        self
    }

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

    /// Runs the query with this id on the server, as `system.query_log` has
    /// it, rather than one the server makes up.
    pub fn query_id(mut self, id: impl Into<String>) -> Self {
        self.query.query_id = Some(id.into());
        self
    }

    /// Runs the query, streaming its rows as they arrive, each read as `T`:
    /// a [`Row`], or a type that implements [`serde::Deserialize`].
    ///
    /// ```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 reads every row 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 reads its one row as `T`: [`Error::NoRows`] if it
    /// returns none, [`Error::TooManyRows`] if more than one.
    pub async fn fetch_one<T: FromRow>(self) -> Result<T, Error> {
        self.fetch_optional().await?.ok_or(Error::NoRows)
    }

    /// Runs the query, and reads its row as `T`, if it returns one:
    /// [`Error::TooManyRows`] if it returns more than one.
    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, begun by [`Database::exec`] or [`DatabaseRef::exec`]: set its
/// parameters, settings and 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, begun by [`Database::insert`] or [`DatabaseRef::insert`]: set
/// its 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))
        })
    }
}

/// What a statement or an insert did, as the server summarizes it.
#[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,
        }
    }
}

/// One row of a query's result: its columns, and a [`Value`] for each.
#[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()
    }

    /// The value of a column, by name or by position, read as `T`.
    ///
    /// # Panics
    ///
    /// If there is no such column, or its value can't be read as `T`. See
    /// [`Row::try_get`] for a version that returns an error 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}"),
        }
    }

    /// The value of a column, by name or by position, read as `T`:
    /// [`Error::InvalidArgument`] if there is no such column, and
    /// [`Error::Decode`] if its value can't be read 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)))
    }

    /// The row read as `T`, by column name: 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}")
    }
}

/// What a query's rows can be read as: a [`Row`], as it is, and every type
/// that implements [`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 query's rows as they arrive, each read as `T`: returned by
/// [`Query::fetch`]. Take them with [`RowStream::next`], or as a [`Stream`].
///
/// Dropping it before the last row stops a read's query 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()
    }
}

/// What a ClickHouse call failed with. See the [module docs](self#errors).
///
/// It is this module's own error and doesn't convert into
/// [`encore::Error`](crate::Error): where a function returns one, map it
/// with the code that fits the caller.
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The server refused or failed the query.
    #[error("{message}")]
    Server {
        /// ClickHouse's exception code, such as 60 for `UNKNOWN_TABLE`; 0
        /// when the server gave none.
        code: i32,
        /// The code's name, such as `UNKNOWN_TABLE`; empty when the message
        /// doesn't carry it.
        name: String,
        /// The server's message.
        message: String,
    },
    /// The database can't be reached, or isn't configured for this service
    /// at the access level the call needs; the message says why.
    #[error("ClickHouse is unavailable: {0}")]
    Unavailable(String),
    /// The call was canceled.
    #[error("the ClickHouse call was canceled")]
    Canceled,
    /// A response, or a row, that couldn't be read as asked; the message
    /// says why.
    #[error("decode the ClickHouse response: {0}")]
    Decode(String),
    /// A mistake in the call itself, such as an empty table name or a row
    /// that is no struct or map; the message says which.
    #[error("{0}")]
    InvalidArgument(String),
    /// A query that should return a row returned none.
    #[error("the query returned no rows")]
    NoRows,
    /// A query that should return at most one row returned more.
    #[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())
}