encore-dev 2.0.0-beta.4

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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
//! Postgres databases. Declared at module scope; the connection pool is built
//! lazily from the runtime on first query and reused thereafter.
//!
//! ```no_run
//! use encore::storage::postgres::Database;
//!
//! static DB: Database = Database::new("hello").migrations("./migrations");
//!
//! async fn rename(id: i64, name: &str) -> Result<Option<String>, encore::Error> {
//!     DB.execute("UPDATE users SET name = $2 WHERE id = $1", &[&id, &name])
//!         .await?;
//!     let row = DB
//!         .query_opt("SELECT email FROM users WHERE id = $1", &[&id])
//!         .await?;
//!     Ok(row.map(|row| row.get("email")))
//! }
//! ```
//!
//! # Queries
//!
//! The query methods are those of [`tokio_postgres::Client`], with the same
//! names, parameters and meaning — `query`, `query_one`, `query_opt`,
//! `query_raw`, `execute`, `batch_execute`, … — returning this crate's
//! [`Error`]. Their types ([`Row`], [`Statement`], [`types::ToSql`], …) are
//! this module's own, with the methods of their `tokio_postgres` counterparts.
//!
//! Every query method is a method of the [`Database`], and calling one there
//! uses it with read-write privileges. That is what lets Encore grant each
//! service exactly the access it uses: the operation is visible at the call,
//! so the parser can read it.
//!
//! A [`Database`] is a pool of connections, where a `tokio_postgres` client is
//! one. What needs a connection of its own — a prepared statement, `COPY` — is
//! on a [`Connection`] ([`Database::acquire`]) or a [`Transaction`].
//!
//! # References
//!
//! For the same reason, a database cannot be passed around as a value. To hand
//! it to other code, make a [`DatabaseRef`] with the privileges that code
//! needs — [`Database::read`], [`Database::write`] or [`Database::admin`] —
//! which the service is then granted:
//!
//! ```no_run
//! use encore::storage::postgres::{Database, Queryable};
//!
//! static DB: Database = Database::named("hello");
//!
//! // Library code asks for something to query, as a trait.
//! async fn count(db: &impl Queryable) -> Result<i64, encore::Error> {
//!     let row = db.query_one("SELECT count(*) FROM users", &[]).await?;
//!     Ok(row.get(0))
//! }
//!
//! async fn users() -> Result<i64, encore::Error> {
//!     count(&DB.read()).await
//! }
//! ```
//!
//! [`Queryable`] is also implemented by a [`Transaction`] and a
//! [`Connection`], so the same library code runs inside either. It is not
//! implemented by the [`Database`] itself:
//!
//! ```compile_fail,E0277
//! # use encore::storage::postgres::{Database, Queryable};
//! # static DB: Database = Database::named("hello");
//! # async fn count(db: &impl Queryable) -> Result<i64, encore::Error> {
//! #     let row = db.query_one("SELECT count(*) FROM users", &[]).await?;
//! #     Ok(row.get(0))
//! # }
//! async fn users() -> Result<i64, encore::Error> {
//!     count(&DB).await
//! }
//! ```
//!
//! [`tokio_postgres::Client`]: https://docs.rs/tokio-postgres/latest/tokio_postgres/struct.Client.html

mod row;
#[cfg(test)]
mod tests;
pub mod types;

use std::fmt::Display;
use std::future::Future;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::{Arc, OnceLock};

use bytes::Buf;
use encore_sdk_core::postgres::Access as CoreAccess;
use encore_sdk_core::postgres::{self, Pool, QuerySpan};

use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::testing;

use self::row::{ConnId, StatementRef};
use self::types::{BorrowToSql, Param, ToSql, Type};

pub use self::row::{Column, Row, RowIndex, RowStream, Statement, ToStatement};
pub use tokio_postgres::{
    CopyInSink, CopyOutStream, IsolationLevel, SimpleColumn, SimpleQueryMessage, SimpleQueryRow,
};

/// A Postgres database, backed by a lazily-built connection pool.
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>,
    pool: OnceLock<Arc<Pool>>,
}

impl Database {
    /// Declare a database. `const` so it can initialize a module-scope `static`;
    /// the pool is built on first use.
    ///
    /// Options follow the name, each a method of its own:
    ///
    /// ```no_run
    /// use encore::storage::postgres::Database;
    ///
    /// static DB: Database = Database::new("hello").migrations("./migrations");
    /// ```
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            migrations: None,
            pool: 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.
    /// `const` so it can initialize a module-scope `static`; the pool is built
    /// on first use. A named database takes no options: it is configured where
    /// it is declared.
    ///
    /// ```no_run
    /// use encore::storage::postgres::Database;
    ///
    /// static DB: Database = Database::named("hello");
    /// ```
    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"`.
    ///
    /// 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
    }

    /// A handle to the database with admin-level privileges.
    ///
    /// `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 read-write privileges.
    pub const fn write(&'static self) -> DatabaseRef {
        DatabaseRef {
            db: self,
            access: Access::Write,
        }
    }

    /// A handle to the database with read-only privileges, which may connect
    /// to a read replica. To always read from the primary server, use
    /// [`Database::read_primary`].
    ///
    /// ```no_run
    /// use encore::storage::postgres::{Database, DatabaseRef};
    ///
    /// static DB: Database = Database::named("hello");
    /// static REPORTS: DatabaseRef = DB.read();
    /// ```
    pub const fn read(&'static self) -> DatabaseRef {
        DatabaseRef {
            db: self,
            access: Access::Read { primary: false },
        }
    }

    /// A handle to the database with read-only privileges that connects to the
    /// primary server, even if there are read replicas available.
    pub const fn read_primary(&'static self) -> DatabaseRef {
        DatabaseRef {
            db: self,
            access: Access::Read { primary: true },
        }
    }

    /// The pool queries run on: the database's own, or under `encore test` the
    /// one of the current test's instance of it (see [`crate::testing`]).
    fn pool(&self) -> Result<Arc<Pool>, Error> {
        if let Some(test) = testing::active()? {
            return test.database_pool(self.name);
        }
        if let Some(pool) = self.pool.get() {
            return Ok(pool.clone());
        }
        let pool = core()
            .postgres()
            .database(&self.name.into())
            .new_pool()
            .map_err(db_err)?;
        // A concurrent caller may win the race; either way `get` returns a pool.
        let _ = self.pool.set(Arc::new(pool));
        Ok(self.pool.get().expect("pool just set").clone())
    }

    /// Begin a transaction, on a connection of its own from the pool.
    ///
    /// The returned [`Transaction`] rolls back when dropped, so an early return
    /// cannot leave one open. Commit explicitly:
    ///
    /// ```ignore
    /// let tx = DB.transaction().await?;
    /// tx.execute("INSERT INTO items (name) VALUES ($1)", &[&name]).await?;
    /// tx.commit().await?;
    /// ```
    pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
        self.begin(CoreAccess::ReadWrite, "START TRANSACTION").await
    }

    /// A builder for a transaction with its characteristics set: isolation
    /// level, read-only, deferrable.
    ///
    /// ```ignore
    /// let tx = DB.build_transaction()
    ///     .isolation_level(IsolationLevel::Serializable)
    ///     .read_only(true)
    ///     .start()
    ///     .await?;
    /// ```
    pub fn build_transaction(&self) -> TransactionBuilder<'_> {
        TransactionBuilder::new(Target::Database(self, CoreAccess::ReadWrite))
    }

    /// The pool a handle with `access` runs on. See [`Pool::with_access`].
    fn pool_for(&self, access: CoreAccess) -> Result<Pool, Error> {
        self.pool()?.with_access(access).map_err(db_err)
    }

    async fn begin(
        &self,
        access: CoreAccess,
        statement: &str,
    ) -> Result<Transaction<'static>, Error> {
        let inner = self
            .pool_for(access)?
            .begin_with(statement)
            .await
            .map_err(db_err)?;
        Ok(Transaction {
            inner,
            id: ConnId::new(),
            conn: PhantomData,
        })
    }

    /// Acquire a connection from the database's connection pool. It is returned
    /// to the pool when closed or dropped.
    pub async fn acquire(&self) -> Result<Connection, Error> {
        self.acquire_as(CoreAccess::ReadWrite).await
    }

    async fn acquire_as(&self, access: CoreAccess) -> Result<Connection, Error> {
        let inner = self.pool_for(access)?.acquire().await.map_err(db_err)?;
        Ok(Connection {
            inner,
            id: ConnId::new(),
        })
    }

    /// The connection string to connect to this database with, for a client
    /// other than this SDK's, read-write. It connects through the runtime's
    /// local proxy, which connects on to the database. A read handle's
    /// ([`DatabaseRef::connection_string`]) connects read-only.
    pub fn connection_string(&self) -> Result<String, Error> {
        self.connection_string_as(CoreAccess::ReadWrite)
    }

    fn connection_string_as(&self, access: CoreAccess) -> Result<String, Error> {
        if let Some(test) = testing::active()? {
            return test.database_connection_string(self.name, access);
        }
        Ok(core()
            .postgres()
            .database(&self.name.into())
            .proxy_conn_string(access))
    }
}

/// The privileges a [`DatabaseRef`] was made with.
///
/// What the service is granted comes from the calls that make the handles,
/// which Encore's parser reads. Which connections a handle's statements run on
/// the runtime decides from it: a read handle's are read-only, so a write
/// fails with `read_only_sql_transaction` (SQLSTATE 25006) and a transaction
/// is read-only. See [`Pool::with_access`].
#[derive(Clone, Copy)]
enum Access {
    Admin,
    Write,
    Read { primary: bool },
}

impl Access {
    /// The access the runtime runs the handle's statements with.
    fn core(self) -> CoreAccess {
        match self {
            Access::Admin | Access::Write => CoreAccess::ReadWrite,
            Access::Read { primary: false } => CoreAccess::Read,
            Access::Read { primary: true } => CoreAccess::ReadPrimary,
        }
    }
}

/// A handle to a [`Database`] with one level of privileges, made by
/// [`Database::admin`], [`Database::write`], [`Database::read`] or
/// [`Database::read_primary`]. `Copy`, and free to pass to other code.
///
/// Its methods are the database's. On a read handle they run on read-only
/// connections: a statement that writes fails with `read_only_sql_transaction`
/// (SQLSTATE 25006), and a transaction it begins is read-only. On the
/// database's own pool, which a read handle shares when there is no read-only
/// pool for it, that refuses mistaken writes, not deliberate ones: SQL that
/// changes the session's `default_transaction_read_only` on the same
/// connection (`SET default_transaction_read_only = off`) lifts it. Against
/// untrusted code, the read-only pool's database role is what refuses writes.
///
/// The query methods are also those of [`Queryable`], which library code
/// takes instead of a `DatabaseRef` to run in a transaction as readily.
#[derive(Clone, Copy)]
pub struct DatabaseRef {
    db: &'static Database,
    access: Access,
}

impl DatabaseRef {
    /// See [`Database::transaction`]. On a read handle the transaction is
    /// read-only.
    pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
        self.db.begin(self.access.core(), "START TRANSACTION").await
    }

    /// See [`Database::build_transaction`]. On a read handle the transaction
    /// is read-only, whatever the builder says.
    pub fn build_transaction(&self) -> TransactionBuilder<'static> {
        TransactionBuilder::new(Target::Database(self.db, self.access.core()))
    }

    /// See [`Database::acquire`]. On a read handle the connection is
    /// read-only, as are the transactions begun on it.
    pub async fn acquire(&self) -> Result<Connection, Error> {
        self.db.acquire_as(self.access.core()).await
    }

    /// See [`Database::connection_string`]. A read handle's connects as its
    /// statements run: through the database's read-only pool, as that pool's
    /// role, if they would run on it, and otherwise to the primary as the
    /// database's role. Either way its session is read-only
    /// (`default_transaction_read_only` is on), so a write fails with
    /// `read_only_sql_transaction` (SQLSTATE 25006), until SQL on it turns
    /// that off; through the read-only pool, its role refuses writes still.
    pub fn connection_string(&self) -> Result<String, Error> {
        self.db.connection_string_as(self.access.core())
    }
}

/// A connection acquired from a database's pool by [`Database::acquire`].
/// Returned to the pool when closed or dropped.
///
/// Beside the query methods, it has what needs a connection of its own:
/// prepared statements and `COPY`.
pub struct Connection {
    inner: postgres::Connection,
    id: ConnId,
}

impl Connection {
    /// Begin a transaction on the connection. The connection is borrowed until
    /// the transaction ends, and stays acquired afterwards.
    pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
        self.begin("START TRANSACTION").await
    }

    /// A builder for a transaction with its characteristics set. See
    /// [`Database::build_transaction`].
    pub fn build_transaction(&mut self) -> TransactionBuilder<'_> {
        TransactionBuilder::new(Target::Connection(self))
    }

    async fn begin(&mut self, statement: &str) -> Result<Transaction<'_>, Error> {
        let inner = self.inner.begin_with(statement).await.map_err(db_err)?;
        Ok(Transaction {
            inner,
            id: self.id,
            conn: PhantomData,
        })
    }

    /// Whether the connection is closed: by [`Connection::close`], or because
    /// the server ended it.
    pub fn is_closed(&self) -> bool {
        self.inner.is_closed()
    }

    /// Close the connection, returning it to the pool. Dropping does the same
    /// thing.
    pub async fn close(self) {
        self.inner.close().await;
    }
}

/// An open transaction. Rolls back on drop unless [`Transaction::commit`] is
/// called.
///
/// One begun on a [`Connection`] borrows it until the transaction ends.
pub struct Transaction<'c> {
    inner: postgres::Transaction,
    id: ConnId,
    conn: PhantomData<&'c mut Connection>,
}

impl Transaction<'_> {
    /// Commit the transaction.
    pub async fn commit(self) -> Result<(), Error> {
        self.inner.commit().await.map_err(db_err)
    }

    /// Roll the transaction back explicitly. Dropping does the same thing.
    pub async fn rollback(self) -> Result<(), Error> {
        self.inner.rollback().await.map_err(db_err)
    }
}

/// What a [`TransactionBuilder`] begins its transaction on.
enum Target<'a> {
    /// A connection of its own, for a handle with the access.
    Database(&'a Database, CoreAccess),
    Connection(&'a mut Connection),
}

/// A builder for a transaction with its characteristics set, made by
/// `build_transaction`.
pub struct TransactionBuilder<'a> {
    target: Target<'a>,
    isolation_level: Option<IsolationLevel>,
    read_only: Option<bool>,
    deferrable: Option<bool>,
}

impl<'a> TransactionBuilder<'a> {
    fn new(target: Target<'a>) -> Self {
        Self {
            target,
            isolation_level: None,
            read_only: None,
            deferrable: None,
        }
    }

    /// Sets the isolation level of the transaction.
    pub fn isolation_level(mut self, isolation_level: IsolationLevel) -> Self {
        self.isolation_level = Some(isolation_level);
        self
    }

    /// Sets the access mode of the transaction.
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.read_only = Some(read_only);
        self
    }

    /// Sets the deferrability of the transaction.
    ///
    /// It has an effect only on a transaction that is also `SERIALIZABLE` and
    /// `READ ONLY`.
    pub fn deferrable(mut self, deferrable: bool) -> Self {
        self.deferrable = Some(deferrable);
        self
    }

    /// Begins the transaction.
    pub async fn start(self) -> Result<Transaction<'a>, Error> {
        let mut options = Vec::new();
        if let Some(level) = self.isolation_level {
            options.push(match level {
                IsolationLevel::ReadUncommitted => "ISOLATION LEVEL READ UNCOMMITTED",
                IsolationLevel::ReadCommitted => "ISOLATION LEVEL READ COMMITTED",
                IsolationLevel::RepeatableRead => "ISOLATION LEVEL REPEATABLE READ",
                IsolationLevel::Serializable => "ISOLATION LEVEL SERIALIZABLE",
                _ => return Err(Error::invalid_argument("unsupported isolation level")),
            });
        }
        if let Some(read_only) = self.read_only {
            options.push(if read_only { "READ ONLY" } else { "READ WRITE" });
        }
        if let Some(deferrable) = self.deferrable {
            options.push(if deferrable {
                "DEFERRABLE"
            } else {
                "NOT DEFERRABLE"
            });
        }
        let statement = format!("START TRANSACTION {}", options.join(", "));
        match self.target {
            Target::Database(db, access) => db.begin(access, &statement).await,
            Target::Connection(conn) => conn.begin(&statement).await,
        }
    }
}

/// What a statement runs on.
#[derive(Clone, Copy)]
enum On<'a> {
    /// A connection of the pool, for a handle with the access.
    Database(&'a Database, CoreAccess),
    Connection(&'a Connection),
    Transaction(&'a postgres::Transaction, ConnId),
}

/// The client a statement runs on, for as long as it takes to send it.
enum Client<'a> {
    /// Taken from the pool, and returned to it when dropped.
    Pooled(postgres::PooledClient),
    Connection(postgres::ConnClient<'a>),
    Transaction(&'a postgres::Transaction),
}

impl Deref for Client<'_> {
    type Target = tokio_postgres::Client;

    fn deref(&self) -> &Self::Target {
        match self {
            Client::Pooled(client) => client,
            Client::Connection(client) => client,
            Client::Transaction(tx) => tx.client(),
        }
    }
}

impl<'a> On<'a> {
    /// The client to run `statement` on, told it will, so that one that may
    /// change the session's access mode has the next checkout set it again.
    async fn client(self, statement: &str) -> Result<Client<'a>, Error> {
        let client = match self {
            On::Database(db, access) => db.pool_for(access)?.client().await.map(Client::Pooled),
            On::Connection(conn) => conn.inner.client().await.map(Client::Connection),
            On::Transaction(tx, _) => Ok(Client::Transaction(tx)),
        }
        .map_err(db_err)?;
        match &client {
            Client::Pooled(client) => client.will_run(statement),
            Client::Connection(client) => client.will_run(statement),
            Client::Transaction(tx) => tx.will_run(statement),
        }
        Ok(client)
    }

    /// Starts the trace span of a query.
    fn span(self, query: &str) -> Result<QuerySpan, Error> {
        Ok(match self {
            On::Database(db, _) => db.pool()?.query_span(query),
            On::Connection(conn) => conn.inner.query_span(query),
            On::Transaction(tx, _) => tx.query_span(query),
        })
    }

    /// The connection prepared statements belong to, if this is one.
    fn conn(self) -> Option<ConnId> {
        match self {
            On::Database(..) => None,
            On::Connection(conn) => Some(conn.id),
            On::Transaction(_, id) => Some(id),
        }
    }
}

impl Database {
    fn on(&self) -> On<'_> {
        On::Database(self, CoreAccess::ReadWrite)
    }
}

impl DatabaseRef {
    fn on(&self) -> On<'_> {
        On::Database(self.db, self.access.core())
    }
}

impl Connection {
    fn on(&self) -> On<'_> {
        On::Connection(self)
    }
}

impl Transaction<'_> {
    fn on(&self) -> On<'_> {
        On::Transaction(&self.inner, self.id)
    }
}

/// The statement implementations, written once. Each runs under a query span.
mod ops {
    use super::*;

    /// The parameters of a statement, as `tokio_postgres` takes them.
    pub type Params<'a> = Vec<Param<&'a (dyn ToSql + Sync)>>;

    pub fn params<'a>(params: &[&'a (dyn ToSql + Sync)]) -> Params<'a> {
        params.iter().map(|p| Param(*p)).collect()
    }

    /// Ends `span` with the outcome of a query.
    fn finish<T>(span: QuerySpan, result: Result<T, Error>) -> Result<T, Error> {
        span.end(result.as_ref().err());
        result
    }

    /// The statement to run on `client`: a query string prepared there, or a
    /// statement the connection prepared earlier.
    async fn resolve(
        on: On<'_>,
        client: &tokio_postgres::Client,
        statement: StatementRef<'_>,
    ) -> Result<tokio_postgres::Statement, Error> {
        match statement {
            StatementRef::Query(query) => client.prepare(query).await.map_err(db_err),
            StatementRef::Statement(statement) if on.conn() == Some(statement.conn) => {
                Ok(statement.inner.clone())
            }
            StatementRef::Statement(_) => Err(Error::invalid_argument(
                "a prepared statement can only be used on the connection that prepared it, \
                 or in a transaction on that connection",
            )),
        }
    }

    pub async fn query_raw<T, P, I>(
        on: On<'_>,
        statement: &T,
        params: I,
    ) -> Result<RowStream, Error>
    where
        T: ?Sized + ToStatement,
        P: BorrowToSql,
        I: IntoIterator<Item = P>,
        I::IntoIter: ExactSizeIterator,
    {
        let statement = statement.__convert();
        let span = on.span(statement.text())?;
        let result = async {
            let client = on.client(statement.text()).await?;
            let statement = resolve(on, &client, statement).await?;
            client
                .query_raw(&statement, params.into_iter().map(Param))
                .await
                .map(RowStream::new)
                .map_err(db_err)
        }
        .await;
        finish(span, result)
    }

    /// `query_raw`, for parameters already converted.
    async fn query_stream(
        on: On<'_>,
        statement: StatementRef<'_>,
        params: Params<'_>,
    ) -> Result<RowStream, Error> {
        let span = on.span(statement.text())?;
        let result = async {
            let client = on.client(statement.text()).await?;
            let statement = resolve(on, &client, statement).await?;
            client
                .query_raw(&statement, params)
                .await
                .map(RowStream::new)
                .map_err(db_err)
        }
        .await;
        finish(span, result)
    }

    async fn collect(mut stream: RowStream) -> Result<Vec<Row>, Error> {
        let mut rows = Vec::new();
        while let Some(row) = stream.next().await {
            rows.push(row?);
        }
        Ok(rows)
    }

    pub async fn query(
        on: On<'_>,
        statement: StatementRef<'_>,
        params: Params<'_>,
    ) -> Result<Vec<Row>, Error> {
        collect(query_stream(on, statement, params).await?).await
    }

    pub async fn query_opt(
        on: On<'_>,
        statement: StatementRef<'_>,
        params: Params<'_>,
    ) -> Result<Option<Row>, Error> {
        let mut stream = query_stream(on, statement, params).await?;
        let Some(first) = stream.next().await.transpose()? else {
            return Ok(None);
        };
        if stream.next().await.transpose()?.is_some() {
            return Err(Error::new(
                ErrCode::FailedPrecondition,
                "query returned an unexpected number of rows",
            ));
        }
        Ok(Some(first))
    }

    pub async fn query_one(
        on: On<'_>,
        statement: StatementRef<'_>,
        params: Params<'_>,
    ) -> Result<Row, Error> {
        query_opt(on, statement, params)
            .await?
            .ok_or_else(|| Error::not_found("query returned an unexpected number of rows"))
    }

    pub async fn query_typed_raw<P, I>(
        on: On<'_>,
        query: &str,
        params: I,
    ) -> Result<RowStream, Error>
    where
        P: BorrowToSql,
        I: IntoIterator<Item = (P, Type)>,
    {
        let span = on.span(query)?;
        let result = async {
            let client = on.client(query).await?;
            client
                .query_typed_raw(query, params.into_iter().map(|(p, ty)| (Param(p), ty)))
                .await
                .map(RowStream::new)
                .map_err(db_err)
        }
        .await;
        finish(span, result)
    }

    pub async fn query_typed(
        on: On<'_>,
        query: &str,
        params: Vec<(Param<&(dyn ToSql + Sync)>, Type)>,
    ) -> Result<Vec<Row>, Error> {
        let span = on.span(query)?;
        let result = async {
            let client = on.client(query).await?;
            client
                .query_typed_raw(query, params)
                .await
                .map(RowStream::new)
                .map_err(db_err)
        }
        .await;
        collect(finish(span, result)?).await
    }

    pub async fn execute_raw<T, P, I>(on: On<'_>, statement: &T, params: I) -> Result<u64, Error>
    where
        T: ?Sized + ToStatement,
        P: BorrowToSql,
        I: IntoIterator<Item = P>,
        I::IntoIter: ExactSizeIterator,
    {
        let statement = statement.__convert();
        let span = on.span(statement.text())?;
        let result = async {
            let client = on.client(statement.text()).await?;
            let statement = resolve(on, &client, statement).await?;
            client
                .execute_raw(&statement, params.into_iter().map(Param))
                .await
                .map_err(db_err)
        }
        .await;
        finish(span, result)
    }

    pub async fn execute(
        on: On<'_>,
        statement: StatementRef<'_>,
        params: Params<'_>,
    ) -> Result<u64, Error> {
        let span = on.span(statement.text())?;
        let result = async {
            let client = on.client(statement.text()).await?;
            let statement = resolve(on, &client, statement).await?;
            client.execute_raw(&statement, params).await.map_err(db_err)
        }
        .await;
        finish(span, result)
    }

    pub async fn simple_query(on: On<'_>, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
        let span = on.span(query)?;
        let result = async {
            let client = on.client(query).await?;
            client.simple_query(query).await.map_err(db_err)
        }
        .await;
        finish(span, result)
    }

    pub async fn batch_execute(on: On<'_>, query: &str) -> Result<(), Error> {
        let span = on.span(query)?;
        let result = async {
            let client = on.client(query).await?;
            client.batch_execute(query).await.map_err(db_err)
        }
        .await;
        finish(span, result)
    }

    pub async fn prepare(on: On<'_>, query: &str, types: &[Type]) -> Result<Statement, Error> {
        let conn = on.conn().expect("only a connection prepares statements");
        let client = on.client(query).await?;
        let inner = client.prepare_typed(query, types).await.map_err(db_err)?;
        Ok(Statement {
            inner,
            conn,
            query: query.into(),
        })
    }

    pub async fn copy_in<U>(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyInSink<U>, Error>
    where
        U: Buf + 'static + Send,
    {
        let span = on.span(statement.text())?;
        let result = async {
            let client = on.client(statement.text()).await?;
            let statement = resolve(on, &client, statement).await?;
            client.copy_in(&statement).await.map_err(db_err)
        }
        .await;
        finish(span, result)
    }

    pub async fn copy_out(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyOutStream, Error> {
        let span = on.span(statement.text())?;
        let result = async {
            let client = on.client(statement.text()).await?;
            let statement = resolve(on, &client, statement).await?;
            client.copy_out(&statement).await.map_err(db_err)
        }
        .await;
        finish(span, result)
    }
}

/// Something queries run on: a [`DatabaseRef`], a [`Transaction`] or a
/// [`Connection`]. Library code takes it — `&impl Queryable` — so it works
/// with any of them.
///
/// Its methods are the query methods those types have, which are the ones of
/// `tokio_postgres`'s `GenericClient`.
///
/// A [`Database`] does not implement it: to pass one to library code, make a
/// [`DatabaseRef`] with the privileges the code needs.
pub trait Queryable: Send + Sync {
    /// See [`Database::execute`].
    fn execute<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> impl Future<Output = Result<u64, Error>> + Send
    where
        T: ?Sized + ToStatement;

    /// See [`Database::execute_raw`].
    fn execute_raw<T, P, I>(
        &self,
        statement: &T,
        params: I,
    ) -> impl Future<Output = Result<u64, Error>> + Send
    where
        T: ?Sized + ToStatement,
        P: BorrowToSql + Send,
        I: IntoIterator<Item = P> + Send,
        I::IntoIter: ExactSizeIterator + Send;

    /// See [`Database::query`].
    fn query<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
    where
        T: ?Sized + ToStatement;

    /// See [`Database::query_one`].
    fn query_one<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> impl Future<Output = Result<Row, Error>> + Send
    where
        T: ?Sized + ToStatement;

    /// See [`Database::query_opt`].
    fn query_opt<T>(
        &self,
        statement: &T,
        params: &[&(dyn ToSql + Sync)],
    ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
    where
        T: ?Sized + ToStatement;

    /// See [`Database::query_raw`].
    fn query_raw<T, P, I>(
        &self,
        statement: &T,
        params: I,
    ) -> impl Future<Output = Result<RowStream, Error>> + Send
    where
        T: ?Sized + ToStatement,
        P: BorrowToSql + Send,
        I: IntoIterator<Item = P> + Send,
        I::IntoIter: ExactSizeIterator + Send;

    /// See [`Database::query_typed`].
    fn query_typed(
        &self,
        query: &str,
        params: &[(&(dyn ToSql + Sync), Type)],
    ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send;

    /// See [`Database::query_typed_raw`].
    fn query_typed_raw<P, I>(
        &self,
        query: &str,
        params: I,
    ) -> impl Future<Output = Result<RowStream, Error>> + Send
    where
        P: BorrowToSql + Send,
        I: IntoIterator<Item = (P, Type)> + Send,
        I::IntoIter: Send;

    /// See [`Database::simple_query`].
    fn simple_query(
        &self,
        query: &str,
    ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send;

    /// See [`Database::batch_execute`].
    fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
}

/// The query methods, on each type queries run on. Documented once, on
/// [`Database`]; the others refer there.
macro_rules! query_methods {
    ($ty:ty) => {
        impl $ty {
            /// Executes a statement, returning the resulting rows.
            ///
            /// A statement may contain parameters, written `$1`, `$2`, … and
            /// given in `params`. That is the way to pass values: it keeps
            /// them out of the SQL text.
            ///
            /// ```ignore
            /// for row in DB.query("SELECT name FROM users WHERE age > $1", &[&18]).await? {
            ///     let name: String = row.get("name");
            /// }
            /// ```
            pub async fn query<T>(
                &self,
                statement: &T,
                params: &[&(dyn ToSql + Sync)],
            ) -> Result<Vec<Row>, Error>
            where
                T: ?Sized + ToStatement,
            {
                ops::query(self.on(), statement.__convert(), ops::params(params)).await
            }

            /// Executes a statement which returns a single row, returning it.
            ///
            /// Returns an error if the query does not return exactly one row.
            pub async fn query_one<T>(
                &self,
                statement: &T,
                params: &[&(dyn ToSql + Sync)],
            ) -> Result<Row, Error>
            where
                T: ?Sized + ToStatement,
            {
                ops::query_one(self.on(), statement.__convert(), ops::params(params)).await
            }

            /// Executes a statement which returns zero or one rows, returning
            /// it.
            ///
            /// Returns an error if the query returns more than one row.
            pub async fn query_opt<T>(
                &self,
                statement: &T,
                params: &[&(dyn ToSql + Sync)],
            ) -> Result<Option<Row>, Error>
            where
                T: ?Sized + ToStatement,
            {
                ops::query_opt(self.on(), statement.__convert(), ops::params(params)).await
            }

            /// The maximally flexible version of `query`: the parameters are
            /// an iterator, and the rows come as a stream rather than
            /// collected.
            pub async fn query_raw<T, P, I>(
                &self,
                statement: &T,
                params: I,
            ) -> Result<RowStream, Error>
            where
                T: ?Sized + ToStatement,
                P: BorrowToSql,
                I: IntoIterator<Item = P>,
                I::IntoIter: ExactSizeIterator,
            {
                ops::query_raw(self.on(), statement, params).await
            }

            /// Like `query`, but with the types of the parameters given, so
            /// the query needs no round trip to prepare it.
            pub async fn query_typed(
                &self,
                query: &str,
                params: &[(&(dyn ToSql + Sync), Type)],
            ) -> Result<Vec<Row>, Error> {
                let params = params
                    .iter()
                    .map(|(p, ty)| (Param(*p), ty.clone()))
                    .collect();
                ops::query_typed(self.on(), query, params).await
            }

            /// The maximally flexible version of `query_typed`.
            pub async fn query_typed_raw<P, I>(
                &self,
                query: &str,
                params: I,
            ) -> Result<RowStream, Error>
            where
                P: BorrowToSql,
                I: IntoIterator<Item = (P, Type)>,
            {
                ops::query_typed_raw(self.on(), query, params).await
            }

            /// Executes a statement, returning the number of rows modified.
            ///
            /// If the statement does not modify any rows (e.g. `SELECT`), 0
            /// is returned.
            pub async fn execute<T>(
                &self,
                statement: &T,
                params: &[&(dyn ToSql + Sync)],
            ) -> Result<u64, Error>
            where
                T: ?Sized + ToStatement,
            {
                ops::execute(self.on(), statement.__convert(), ops::params(params)).await
            }

            /// The maximally flexible version of `execute`.
            pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
            where
                T: ?Sized + ToStatement,
                P: BorrowToSql,
                I: IntoIterator<Item = P>,
                I::IntoIter: ExactSizeIterator,
            {
                ops::execute_raw(self.on(), statement, params).await
            }

            /// Executes a sequence of SQL statements using the simple query
            /// protocol, returning the resulting rows, with every value as
            /// text.
            ///
            /// The statements, separated by semicolons, take no parameters:
            /// never build the query from untrusted input.
            pub async fn simple_query(
                &self,
                query: &str,
            ) -> Result<Vec<SimpleQueryMessage>, Error> {
                ops::simple_query(self.on(), query).await
            }

            /// Executes a sequence of SQL statements using the simple query
            /// protocol, stopping at the first error.
            ///
            /// The statements, separated by semicolons, take no parameters:
            /// never build the query from untrusted input.
            pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
                ops::batch_execute(self.on(), query).await
            }
        }
    };
}

/// [`Queryable`], for a type with the [`query_methods!`].
macro_rules! queryable {
    ($ty:ty) => {
        impl Queryable for $ty {
            fn execute<T>(
                &self,
                statement: &T,
                params: &[&(dyn ToSql + Sync)],
            ) -> impl Future<Output = Result<u64, Error>> + Send
            where
                T: ?Sized + ToStatement,
            {
                <$ty>::execute(self, statement, params)
            }

            fn execute_raw<T, P, I>(
                &self,
                statement: &T,
                params: I,
            ) -> impl Future<Output = Result<u64, Error>> + Send
            where
                T: ?Sized + ToStatement,
                P: BorrowToSql + Send,
                I: IntoIterator<Item = P> + Send,
                I::IntoIter: ExactSizeIterator + Send,
            {
                <$ty>::execute_raw(self, statement, params)
            }

            fn query<T>(
                &self,
                statement: &T,
                params: &[&(dyn ToSql + Sync)],
            ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
            where
                T: ?Sized + ToStatement,
            {
                <$ty>::query(self, statement, params)
            }

            fn query_one<T>(
                &self,
                statement: &T,
                params: &[&(dyn ToSql + Sync)],
            ) -> impl Future<Output = Result<Row, Error>> + Send
            where
                T: ?Sized + ToStatement,
            {
                <$ty>::query_one(self, statement, params)
            }

            fn query_opt<T>(
                &self,
                statement: &T,
                params: &[&(dyn ToSql + Sync)],
            ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
            where
                T: ?Sized + ToStatement,
            {
                <$ty>::query_opt(self, statement, params)
            }

            fn query_raw<T, P, I>(
                &self,
                statement: &T,
                params: I,
            ) -> impl Future<Output = Result<RowStream, Error>> + Send
            where
                T: ?Sized + ToStatement,
                P: BorrowToSql + Send,
                I: IntoIterator<Item = P> + Send,
                I::IntoIter: ExactSizeIterator + Send,
            {
                <$ty>::query_raw(self, statement, params)
            }

            fn query_typed(
                &self,
                query: &str,
                params: &[(&(dyn ToSql + Sync), Type)],
            ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send {
                <$ty>::query_typed(self, query, params)
            }

            fn query_typed_raw<P, I>(
                &self,
                query: &str,
                params: I,
            ) -> impl Future<Output = Result<RowStream, Error>> + Send
            where
                P: BorrowToSql + Send,
                I: IntoIterator<Item = (P, Type)> + Send,
                I::IntoIter: Send,
            {
                <$ty>::query_typed_raw(self, query, params)
            }

            fn simple_query(
                &self,
                query: &str,
            ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send {
                <$ty>::simple_query(self, query)
            }

            fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
                <$ty>::batch_execute(self, query)
            }
        }
    };
}

/// What needs a connection of its own, on the types that are one.
macro_rules! connection_methods {
    ($ty:ty) => {
        impl $ty {
            /// Creates a new prepared statement.
            ///
            /// A prepared statement is parsed and planned once, and can then
            /// be run repeatedly, with different parameters each time. It
            /// belongs to this connection, and can only be used on it.
            pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
                ops::prepare(self.on(), query, &[]).await
            }

            /// Like `prepare`, but with the types of the statement's
            /// parameters given, rather than left to Postgres to infer.
            pub async fn prepare_typed(
                &self,
                query: &str,
                parameter_types: &[Type],
            ) -> Result<Statement, Error> {
                ops::prepare(self.on(), query, parameter_types).await
            }

            /// Executes a `COPY FROM STDIN` statement, returning a sink to
            /// write the copy data to.
            ///
            /// The copy is aborted if the sink is dropped without being
            /// finished.
            pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
            where
                T: ?Sized + ToStatement,
                U: Buf + 'static + Send,
            {
                ops::copy_in(self.on(), statement.__convert()).await
            }

            /// Executes a `COPY TO STDOUT` statement, returning a stream of
            /// the resulting data.
            pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
            where
                T: ?Sized + ToStatement,
            {
                ops::copy_out(self.on(), statement.__convert()).await
            }
        }
    };
}

query_methods!(Database);
query_methods!(DatabaseRef);
query_methods!(Connection);
query_methods!(Transaction<'_>);

queryable!(DatabaseRef);
queryable!(Connection);
queryable!(Transaction<'_>);

connection_methods!(Connection);
connection_methods!(Transaction<'_>);

fn db_err(err: impl Display) -> Error {
    Error::wrap(ErrCode::Unavailable, err)
}