1mod row;
136#[cfg(test)]
137mod tests;
138pub mod types;
139
140use std::future::Future;
141use std::marker::PhantomData;
142use std::ops::Deref;
143use std::sync::{Arc, OnceLock};
144
145use bytes::Buf;
146use encore_sdk_core::postgres::Access as CoreAccess;
147use encore_sdk_core::postgres::IsolationLevel as CoreIsolationLevel;
148use encore_sdk_core::postgres::{self, Pool, QuerySpan, TransactionOptions};
149
150use crate::runtime::core;
151use crate::testing;
152
153use self::row::{ConnId, StatementRef};
154use self::types::{BorrowToSql, Param, ToSql, Type};
155
156pub use self::row::{Column, Row, RowIndex, RowStream, Statement, ToStatement};
157pub use encore_sdk_core::postgres::{DatabaseError, ErrorCode, ErrorDetails};
158pub use tokio_postgres::{
159 CopyInSink, CopyOutStream, IsolationLevel, SimpleColumn, SimpleQueryMessage, SimpleQueryRow,
160};
161
162pub struct Database {
164 name: &'static str,
165 #[allow(dead_code)]
167 migrations: Option<&'static str>,
168 pool: OnceLock<Arc<Pool>>,
169}
170
171impl Database {
172 pub const fn new(name: &'static str) -> Self {
184 Self {
185 name,
186 migrations: None,
187 pool: OnceLock::new(),
188 }
189 }
190
191 pub const fn named(name: &'static str) -> Self {
204 Self::new(name)
205 }
206
207 pub const fn migrations(mut self, path: &'static str) -> Self {
214 self.migrations = Some(path);
215 self
216 }
217
218 pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
237 self
238 }
239
240 pub const fn admin(&'static self) -> DatabaseRef {
244 DatabaseRef {
245 db: self,
246 access: Access::Admin,
247 }
248 }
249
250 pub const fn write(&'static self) -> DatabaseRef {
252 DatabaseRef {
253 db: self,
254 access: Access::Write,
255 }
256 }
257
258 pub const fn read(&'static self) -> DatabaseRef {
269 DatabaseRef {
270 db: self,
271 access: Access::Read { primary: false },
272 }
273 }
274
275 pub const fn read_primary(&'static self) -> DatabaseRef {
278 DatabaseRef {
279 db: self,
280 access: Access::Read { primary: true },
281 }
282 }
283
284 fn pool(&self) -> Result<Arc<Pool>, Error> {
287 if let Some(test) = testing::active().map_err(test_err)? {
288 return test.database_pool(self.name).map_err(test_err);
289 }
290 if let Some(pool) = self.pool.get() {
291 return Ok(pool.clone());
292 }
293 let pool = core()
294 .postgres()
295 .database(&self.name.into())
296 .new_pool()
297 .map_err(db_err)?;
298 let _ = self.pool.set(Arc::new(pool));
300 Ok(self.pool.get().expect("pool just set").clone())
301 }
302
303 pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
314 self.begin(CoreAccess::ReadWrite, &TransactionOptions::default())
315 .await
316 }
317
318 pub fn build_transaction(&self) -> TransactionBuilder<'_> {
329 TransactionBuilder::new(Target::Database(self, CoreAccess::ReadWrite))
330 }
331
332 fn pool_for(&self, access: CoreAccess) -> Result<Pool, Error> {
334 self.pool()?.with_access(access).map_err(db_err)
335 }
336
337 async fn begin(
338 &self,
339 access: CoreAccess,
340 options: &TransactionOptions,
341 ) -> Result<Transaction<'static>, Error> {
342 let pool = self.pool_for(access)?;
343 check_options(options, pool.is_read_only())?;
344 let inner = pool.begin_with_options(options).await.map_err(db_err)?;
345 Ok(Transaction::new(inner, ConnId::new()))
346 }
347
348 pub async fn acquire(&self) -> Result<Connection, Error> {
351 self.acquire_as(CoreAccess::ReadWrite).await
352 }
353
354 async fn acquire_as(&self, access: CoreAccess) -> Result<Connection, Error> {
355 let inner = self.pool_for(access)?.acquire().await.map_err(db_err)?;
356 Ok(Connection {
357 inner,
358 id: ConnId::new(),
359 })
360 }
361
362 pub fn connection_string(&self) -> Result<String, Error> {
369 self.connection_string_as(CoreAccess::ReadWrite)
370 }
371
372 fn connection_string_as(&self, access: CoreAccess) -> Result<String, Error> {
373 if let Some(test) = testing::active().map_err(test_err)? {
374 return test
375 .database_connection_string(self.name, access)
376 .map_err(test_err);
377 }
378 Ok(core()
379 .postgres()
380 .database(&self.name.into())
381 .proxy_conn_string(access))
382 }
383}
384
385#[derive(Clone, Copy)]
393enum Access {
394 Admin,
395 Write,
396 Read { primary: bool },
397}
398
399impl Access {
400 fn core(self) -> CoreAccess {
402 match self {
403 Access::Admin | Access::Write => CoreAccess::ReadWrite,
404 Access::Read { primary: false } => CoreAccess::Read,
405 Access::Read { primary: true } => CoreAccess::ReadPrimary,
406 }
407 }
408}
409
410#[derive(Clone, Copy)]
426pub struct DatabaseRef {
427 db: &'static Database,
428 access: Access,
429}
430
431impl DatabaseRef {
432 pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
435 self.db
436 .begin(self.access.core(), &TransactionOptions::default())
437 .await
438 }
439
440 pub fn build_transaction(&self) -> TransactionBuilder<'static> {
444 TransactionBuilder::new(Target::Database(self.db, self.access.core()))
445 }
446
447 pub async fn acquire(&self) -> Result<Connection, Error> {
450 self.db.acquire_as(self.access.core()).await
451 }
452
453 pub fn connection_string(&self) -> Result<String, Error> {
462 self.db.connection_string_as(self.access.core())
463 }
464}
465
466pub struct Connection {
472 inner: postgres::Connection,
473 id: ConnId,
474}
475
476impl Connection {
477 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
480 self.begin(&TransactionOptions::default()).await
481 }
482
483 pub fn build_transaction(&mut self) -> TransactionBuilder<'_> {
486 TransactionBuilder::new(Target::Connection(self))
487 }
488
489 async fn begin(&mut self, options: &TransactionOptions) -> Result<Transaction<'_>, Error> {
490 check_options(options, self.inner.is_read_only())?;
491 let inner = self
492 .inner
493 .begin_with_options(options)
494 .await
495 .map_err(db_err)?;
496 Ok(Transaction::new(inner, self.id))
497 }
498
499 pub fn is_closed(&self) -> bool {
502 self.inner.is_closed()
503 }
504
505 pub async fn close(self) {
508 self.inner.close().await;
509 }
510}
511
512pub struct Transaction<'c> {
517 inner: postgres::Transaction,
518 id: ConnId,
519 conn: PhantomData<&'c mut Connection>,
520}
521
522impl Transaction<'_> {
523 fn new(inner: postgres::Transaction, id: ConnId) -> Self {
524 Self {
525 inner,
526 id,
527 conn: PhantomData,
528 }
529 }
530
531 pub async fn commit(self) -> Result<(), Error> {
533 self.inner.commit().await.map_err(db_err)
534 }
535
536 pub async fn rollback(self) -> Result<(), Error> {
538 self.inner.rollback().await.map_err(db_err)
539 }
540}
541
542fn check_options(options: &TransactionOptions, read_only: bool) -> Result<(), Error> {
545 if read_only && options.read_only == Some(false) {
546 return Err(Error::other(
547 "a read handle's transactions are read-only: read_only(false) is not allowed",
548 ));
549 }
550 Ok(())
551}
552
553enum Target<'a> {
555 Database(&'a Database, CoreAccess),
557 Connection(&'a mut Connection),
558}
559
560pub struct TransactionBuilder<'a> {
563 target: Target<'a>,
564 isolation_level: Option<IsolationLevel>,
565 read_only: Option<bool>,
566 deferrable: Option<bool>,
567}
568
569impl<'a> TransactionBuilder<'a> {
570 fn new(target: Target<'a>) -> Self {
571 Self {
572 target,
573 isolation_level: None,
574 read_only: None,
575 deferrable: None,
576 }
577 }
578
579 pub fn isolation_level(mut self, isolation_level: IsolationLevel) -> Self {
581 self.isolation_level = Some(isolation_level);
582 self
583 }
584
585 pub fn read_only(mut self, read_only: bool) -> Self {
587 self.read_only = Some(read_only);
588 self
589 }
590
591 pub fn deferrable(mut self, deferrable: bool) -> Self {
596 self.deferrable = Some(deferrable);
597 self
598 }
599
600 pub async fn start(self) -> Result<Transaction<'a>, Error> {
605 let options = self.options()?;
606 match self.target {
607 Target::Database(db, access) => db.begin(access, &options).await,
608 Target::Connection(conn) => conn.begin(&options).await,
609 }
610 }
611
612 fn options(&self) -> Result<TransactionOptions, Error> {
613 let isolation = self
614 .isolation_level
615 .map(|level| match level {
616 IsolationLevel::ReadUncommitted => Ok(CoreIsolationLevel::ReadUncommitted),
617 IsolationLevel::ReadCommitted => Ok(CoreIsolationLevel::ReadCommitted),
618 IsolationLevel::RepeatableRead => Ok(CoreIsolationLevel::RepeatableRead),
619 IsolationLevel::Serializable => Ok(CoreIsolationLevel::Serializable),
620 _ => Err(Error::other("unsupported isolation level")),
621 })
622 .transpose()?;
623 Ok(TransactionOptions {
624 isolation,
625 read_only: self.read_only,
626 deferrable: self.deferrable,
627 })
628 }
629}
630
631#[derive(Clone, Copy)]
633enum On<'a> {
634 Database(&'a Database, CoreAccess),
636 Connection(&'a Connection),
637 Transaction(&'a postgres::Transaction, ConnId),
638}
639
640enum Client<'a> {
642 Pooled(postgres::PooledClient),
644 Connection(postgres::ConnClient<'a>),
645 Transaction(&'a postgres::Transaction),
646}
647
648impl Deref for Client<'_> {
649 type Target = tokio_postgres::Client;
650
651 fn deref(&self) -> &Self::Target {
652 match self {
653 Client::Pooled(client) => client,
654 Client::Connection(client) => client,
655 Client::Transaction(tx) => tx.client(),
656 }
657 }
658}
659
660impl<'a> On<'a> {
661 async fn client(self, statement: &str) -> Result<Client<'a>, Error> {
664 let client = match self {
665 On::Database(db, access) => db.pool_for(access)?.client().await.map(Client::Pooled),
666 On::Connection(conn) => conn.inner.client().await.map(Client::Connection),
667 On::Transaction(tx, _) => Ok(Client::Transaction(tx)),
668 }
669 .map_err(db_err)?;
670 match &client {
671 Client::Pooled(client) => client.will_run(statement),
672 Client::Connection(client) => client.will_run(statement),
673 Client::Transaction(tx) => tx.will_run(statement),
674 }
675 Ok(client)
676 }
677
678 fn span(self, query: &str) -> Result<QuerySpan, Error> {
680 Ok(match self {
681 On::Database(db, _) => db.pool()?.query_span(query),
682 On::Connection(conn) => conn.inner.query_span(query),
683 On::Transaction(tx, _) => tx.query_span(query),
684 })
685 }
686
687 fn conn(self) -> Option<ConnId> {
689 match self {
690 On::Database(..) => None,
691 On::Connection(conn) => Some(conn.id),
692 On::Transaction(_, id) => Some(id),
693 }
694 }
695}
696
697impl Database {
698 fn on(&self) -> On<'_> {
699 On::Database(self, CoreAccess::ReadWrite)
700 }
701}
702
703impl DatabaseRef {
704 fn on(&self) -> On<'_> {
705 On::Database(self.db, self.access.core())
706 }
707}
708
709impl Connection {
710 fn on(&self) -> On<'_> {
711 On::Connection(self)
712 }
713}
714
715impl Transaction<'_> {
716 fn on(&self) -> On<'_> {
717 On::Transaction(&self.inner, self.id)
718 }
719}
720
721mod ops {
723 use super::*;
724
725 pub type Params<'a> = Vec<Param<&'a (dyn ToSql + Sync)>>;
727
728 pub fn params<'a>(params: &[&'a (dyn ToSql + Sync)]) -> Params<'a> {
729 params.iter().map(|p| Param(*p)).collect()
730 }
731
732 fn finish<T>(span: QuerySpan, result: Result<T, Error>) -> Result<T, Error> {
734 span.end(result.as_ref().err());
735 result
736 }
737
738 async fn resolve(
741 on: On<'_>,
742 client: &tokio_postgres::Client,
743 statement: StatementRef<'_>,
744 ) -> Result<tokio_postgres::Statement, Error> {
745 match statement {
746 StatementRef::Query(query) => client.prepare(query).await.map_err(db_err),
747 StatementRef::Statement(statement) if on.conn() == Some(statement.conn) => {
748 Ok(statement.inner.clone())
749 }
750 StatementRef::Statement(_) => Err(Error::other(
751 "a prepared statement can only be used on the connection that prepared it, \
752 or in a transaction on that connection",
753 )),
754 }
755 }
756
757 pub async fn query_raw<T, P, I>(
758 on: On<'_>,
759 statement: &T,
760 params: I,
761 ) -> Result<RowStream, Error>
762 where
763 T: ?Sized + ToStatement,
764 P: BorrowToSql,
765 I: IntoIterator<Item = P>,
766 I::IntoIter: ExactSizeIterator,
767 {
768 let statement = statement.__convert();
769 let span = on.span(statement.text())?;
770 let result = async {
771 let client = on.client(statement.text()).await?;
772 let statement = resolve(on, &client, statement).await?;
773 client
774 .query_raw(&statement, params.into_iter().map(Param))
775 .await
776 .map(RowStream::new)
777 .map_err(db_err)
778 }
779 .await;
780 finish(span, result)
781 }
782
783 async fn query_stream(
785 on: On<'_>,
786 statement: StatementRef<'_>,
787 params: Params<'_>,
788 ) -> Result<RowStream, Error> {
789 let span = on.span(statement.text())?;
790 let result = async {
791 let client = on.client(statement.text()).await?;
792 let statement = resolve(on, &client, statement).await?;
793 client
794 .query_raw(&statement, params)
795 .await
796 .map(RowStream::new)
797 .map_err(db_err)
798 }
799 .await;
800 finish(span, result)
801 }
802
803 async fn collect(mut stream: RowStream) -> Result<Vec<Row>, Error> {
804 let mut rows = Vec::new();
805 while let Some(row) = stream.next().await {
806 rows.push(row?);
807 }
808 Ok(rows)
809 }
810
811 pub async fn query(
812 on: On<'_>,
813 statement: StatementRef<'_>,
814 params: Params<'_>,
815 ) -> Result<Vec<Row>, Error> {
816 collect(query_stream(on, statement, params).await?).await
817 }
818
819 pub async fn query_opt(
820 on: On<'_>,
821 statement: StatementRef<'_>,
822 params: Params<'_>,
823 ) -> Result<Option<Row>, Error> {
824 let mut stream = query_stream(on, statement, params).await?;
825 let Some(first) = stream.next().await.transpose()? else {
826 return Ok(None);
827 };
828 if stream.next().await.transpose()?.is_some() {
829 return Err(Error::TooManyRows);
830 }
831 Ok(Some(first))
832 }
833
834 pub async fn query_one(
835 on: On<'_>,
836 statement: StatementRef<'_>,
837 params: Params<'_>,
838 ) -> Result<Row, Error> {
839 query_opt(on, statement, params).await?.ok_or(Error::NoRows)
840 }
841
842 pub async fn query_typed_raw<P, I>(
843 on: On<'_>,
844 query: &str,
845 params: I,
846 ) -> Result<RowStream, Error>
847 where
848 P: BorrowToSql,
849 I: IntoIterator<Item = (P, Type)>,
850 {
851 let span = on.span(query)?;
852 let result = async {
853 let client = on.client(query).await?;
854 client
855 .query_typed_raw(query, params.into_iter().map(|(p, ty)| (Param(p), ty)))
856 .await
857 .map(RowStream::new)
858 .map_err(db_err)
859 }
860 .await;
861 finish(span, result)
862 }
863
864 pub async fn query_typed(
865 on: On<'_>,
866 query: &str,
867 params: Vec<(Param<&(dyn ToSql + Sync)>, Type)>,
868 ) -> Result<Vec<Row>, Error> {
869 let span = on.span(query)?;
870 let result = async {
871 let client = on.client(query).await?;
872 client
873 .query_typed_raw(query, params)
874 .await
875 .map(RowStream::new)
876 .map_err(db_err)
877 }
878 .await;
879 collect(finish(span, result)?).await
880 }
881
882 pub async fn execute_raw<T, P, I>(on: On<'_>, statement: &T, params: I) -> Result<u64, Error>
883 where
884 T: ?Sized + ToStatement,
885 P: BorrowToSql,
886 I: IntoIterator<Item = P>,
887 I::IntoIter: ExactSizeIterator,
888 {
889 let statement = statement.__convert();
890 let span = on.span(statement.text())?;
891 let result = async {
892 let client = on.client(statement.text()).await?;
893 let statement = resolve(on, &client, statement).await?;
894 client
895 .execute_raw(&statement, params.into_iter().map(Param))
896 .await
897 .map_err(db_err)
898 }
899 .await;
900 finish(span, result)
901 }
902
903 pub async fn execute(
904 on: On<'_>,
905 statement: StatementRef<'_>,
906 params: Params<'_>,
907 ) -> Result<u64, Error> {
908 let span = on.span(statement.text())?;
909 let result = async {
910 let client = on.client(statement.text()).await?;
911 let statement = resolve(on, &client, statement).await?;
912 client.execute_raw(&statement, params).await.map_err(db_err)
913 }
914 .await;
915 finish(span, result)
916 }
917
918 pub async fn simple_query(on: On<'_>, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
919 let span = on.span(query)?;
920 let result = async {
921 let client = on.client(query).await?;
922 client.simple_query(query).await.map_err(db_err)
923 }
924 .await;
925 finish(span, result)
926 }
927
928 pub async fn batch_execute(on: On<'_>, query: &str) -> Result<(), Error> {
929 let span = on.span(query)?;
930 let result = async {
931 let client = on.client(query).await?;
932 client.batch_execute(query).await.map_err(db_err)
933 }
934 .await;
935 finish(span, result)
936 }
937
938 pub async fn prepare(on: On<'_>, query: &str, types: &[Type]) -> Result<Statement, Error> {
939 let conn = on.conn().expect("only a connection prepares statements");
940 let client = on.client(query).await?;
941 let inner = client.prepare_typed(query, types).await.map_err(db_err)?;
942 Ok(Statement {
943 inner,
944 conn,
945 query: query.into(),
946 })
947 }
948
949 pub async fn copy_in<U>(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyInSink<U>, Error>
950 where
951 U: Buf + 'static + Send,
952 {
953 let span = on.span(statement.text())?;
954 let result = async {
955 let client = on.client(statement.text()).await?;
956 let statement = resolve(on, &client, statement).await?;
957 client.copy_in(&statement).await.map_err(db_err)
958 }
959 .await;
960 finish(span, result)
961 }
962
963 pub async fn copy_out(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyOutStream, Error> {
964 let span = on.span(statement.text())?;
965 let result = async {
966 let client = on.client(statement.text()).await?;
967 let statement = resolve(on, &client, statement).await?;
968 client.copy_out(&statement).await.map_err(db_err)
969 }
970 .await;
971 finish(span, result)
972 }
973}
974
975pub trait Queryable: Send + Sync {
983 fn execute<T>(
985 &self,
986 statement: &T,
987 params: &[&(dyn ToSql + Sync)],
988 ) -> impl Future<Output = Result<u64, Error>> + Send
989 where
990 T: ?Sized + ToStatement;
991
992 fn execute_raw<T, P, I>(
994 &self,
995 statement: &T,
996 params: I,
997 ) -> impl Future<Output = Result<u64, Error>> + Send
998 where
999 T: ?Sized + ToStatement,
1000 P: BorrowToSql + Send,
1001 I: IntoIterator<Item = P> + Send,
1002 I::IntoIter: ExactSizeIterator + Send;
1003
1004 fn query<T>(
1006 &self,
1007 statement: &T,
1008 params: &[&(dyn ToSql + Sync)],
1009 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1010 where
1011 T: ?Sized + ToStatement;
1012
1013 fn query_one<T>(
1015 &self,
1016 statement: &T,
1017 params: &[&(dyn ToSql + Sync)],
1018 ) -> impl Future<Output = Result<Row, Error>> + Send
1019 where
1020 T: ?Sized + ToStatement;
1021
1022 fn query_opt<T>(
1024 &self,
1025 statement: &T,
1026 params: &[&(dyn ToSql + Sync)],
1027 ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1028 where
1029 T: ?Sized + ToStatement;
1030
1031 fn query_raw<T, P, I>(
1033 &self,
1034 statement: &T,
1035 params: I,
1036 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1037 where
1038 T: ?Sized + ToStatement,
1039 P: BorrowToSql + Send,
1040 I: IntoIterator<Item = P> + Send,
1041 I::IntoIter: ExactSizeIterator + Send;
1042
1043 fn query_typed(
1045 &self,
1046 query: &str,
1047 params: &[(&(dyn ToSql + Sync), Type)],
1048 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send;
1049
1050 fn query_typed_raw<P, I>(
1052 &self,
1053 query: &str,
1054 params: I,
1055 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1056 where
1057 P: BorrowToSql + Send,
1058 I: IntoIterator<Item = (P, Type)> + Send,
1059 I::IntoIter: Send;
1060
1061 fn simple_query(
1063 &self,
1064 query: &str,
1065 ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send;
1066
1067 fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
1069}
1070
1071macro_rules! query_methods {
1074 ($ty:ty) => {
1075 impl $ty {
1076 pub async fn query<T>(
1088 &self,
1089 statement: &T,
1090 params: &[&(dyn ToSql + Sync)],
1091 ) -> Result<Vec<Row>, Error>
1092 where
1093 T: ?Sized + ToStatement,
1094 {
1095 ops::query(self.on(), statement.__convert(), ops::params(params)).await
1096 }
1097
1098 pub async fn query_one<T>(
1102 &self,
1103 statement: &T,
1104 params: &[&(dyn ToSql + Sync)],
1105 ) -> Result<Row, Error>
1106 where
1107 T: ?Sized + ToStatement,
1108 {
1109 ops::query_one(self.on(), statement.__convert(), ops::params(params)).await
1110 }
1111
1112 pub async fn query_opt<T>(
1117 &self,
1118 statement: &T,
1119 params: &[&(dyn ToSql + Sync)],
1120 ) -> Result<Option<Row>, Error>
1121 where
1122 T: ?Sized + ToStatement,
1123 {
1124 ops::query_opt(self.on(), statement.__convert(), ops::params(params)).await
1125 }
1126
1127 pub async fn query_raw<T, P, I>(
1131 &self,
1132 statement: &T,
1133 params: I,
1134 ) -> Result<RowStream, Error>
1135 where
1136 T: ?Sized + ToStatement,
1137 P: BorrowToSql,
1138 I: IntoIterator<Item = P>,
1139 I::IntoIter: ExactSizeIterator,
1140 {
1141 ops::query_raw(self.on(), statement, params).await
1142 }
1143
1144 pub async fn query_typed(
1147 &self,
1148 query: &str,
1149 params: &[(&(dyn ToSql + Sync), Type)],
1150 ) -> Result<Vec<Row>, Error> {
1151 let params = params
1152 .iter()
1153 .map(|(p, ty)| (Param(*p), ty.clone()))
1154 .collect();
1155 ops::query_typed(self.on(), query, params).await
1156 }
1157
1158 pub async fn query_typed_raw<P, I>(
1160 &self,
1161 query: &str,
1162 params: I,
1163 ) -> Result<RowStream, Error>
1164 where
1165 P: BorrowToSql,
1166 I: IntoIterator<Item = (P, Type)>,
1167 {
1168 ops::query_typed_raw(self.on(), query, params).await
1169 }
1170
1171 pub async fn execute<T>(
1176 &self,
1177 statement: &T,
1178 params: &[&(dyn ToSql + Sync)],
1179 ) -> Result<u64, Error>
1180 where
1181 T: ?Sized + ToStatement,
1182 {
1183 ops::execute(self.on(), statement.__convert(), ops::params(params)).await
1184 }
1185
1186 pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
1188 where
1189 T: ?Sized + ToStatement,
1190 P: BorrowToSql,
1191 I: IntoIterator<Item = P>,
1192 I::IntoIter: ExactSizeIterator,
1193 {
1194 ops::execute_raw(self.on(), statement, params).await
1195 }
1196
1197 pub async fn simple_query(
1204 &self,
1205 query: &str,
1206 ) -> Result<Vec<SimpleQueryMessage>, Error> {
1207 ops::simple_query(self.on(), query).await
1208 }
1209
1210 pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
1216 ops::batch_execute(self.on(), query).await
1217 }
1218 }
1219 };
1220}
1221
1222macro_rules! queryable {
1224 ($ty:ty) => {
1225 impl Queryable for $ty {
1226 fn execute<T>(
1227 &self,
1228 statement: &T,
1229 params: &[&(dyn ToSql + Sync)],
1230 ) -> impl Future<Output = Result<u64, Error>> + Send
1231 where
1232 T: ?Sized + ToStatement,
1233 {
1234 <$ty>::execute(self, statement, params)
1235 }
1236
1237 fn execute_raw<T, P, I>(
1238 &self,
1239 statement: &T,
1240 params: I,
1241 ) -> impl Future<Output = Result<u64, Error>> + Send
1242 where
1243 T: ?Sized + ToStatement,
1244 P: BorrowToSql + Send,
1245 I: IntoIterator<Item = P> + Send,
1246 I::IntoIter: ExactSizeIterator + Send,
1247 {
1248 <$ty>::execute_raw(self, statement, params)
1249 }
1250
1251 fn query<T>(
1252 &self,
1253 statement: &T,
1254 params: &[&(dyn ToSql + Sync)],
1255 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1256 where
1257 T: ?Sized + ToStatement,
1258 {
1259 <$ty>::query(self, statement, params)
1260 }
1261
1262 fn query_one<T>(
1263 &self,
1264 statement: &T,
1265 params: &[&(dyn ToSql + Sync)],
1266 ) -> impl Future<Output = Result<Row, Error>> + Send
1267 where
1268 T: ?Sized + ToStatement,
1269 {
1270 <$ty>::query_one(self, statement, params)
1271 }
1272
1273 fn query_opt<T>(
1274 &self,
1275 statement: &T,
1276 params: &[&(dyn ToSql + Sync)],
1277 ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1278 where
1279 T: ?Sized + ToStatement,
1280 {
1281 <$ty>::query_opt(self, statement, params)
1282 }
1283
1284 fn query_raw<T, P, I>(
1285 &self,
1286 statement: &T,
1287 params: I,
1288 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1289 where
1290 T: ?Sized + ToStatement,
1291 P: BorrowToSql + Send,
1292 I: IntoIterator<Item = P> + Send,
1293 I::IntoIter: ExactSizeIterator + Send,
1294 {
1295 <$ty>::query_raw(self, statement, params)
1296 }
1297
1298 fn query_typed(
1299 &self,
1300 query: &str,
1301 params: &[(&(dyn ToSql + Sync), Type)],
1302 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send {
1303 <$ty>::query_typed(self, query, params)
1304 }
1305
1306 fn query_typed_raw<P, I>(
1307 &self,
1308 query: &str,
1309 params: I,
1310 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1311 where
1312 P: BorrowToSql + Send,
1313 I: IntoIterator<Item = (P, Type)> + Send,
1314 I::IntoIter: Send,
1315 {
1316 <$ty>::query_typed_raw(self, query, params)
1317 }
1318
1319 fn simple_query(
1320 &self,
1321 query: &str,
1322 ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send {
1323 <$ty>::simple_query(self, query)
1324 }
1325
1326 fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
1327 <$ty>::batch_execute(self, query)
1328 }
1329 }
1330 };
1331}
1332
1333macro_rules! connection_methods {
1335 ($ty:ty) => {
1336 impl $ty {
1337 pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
1343 ops::prepare(self.on(), query, &[]).await
1344 }
1345
1346 pub async fn prepare_typed(
1349 &self,
1350 query: &str,
1351 parameter_types: &[Type],
1352 ) -> Result<Statement, Error> {
1353 ops::prepare(self.on(), query, parameter_types).await
1354 }
1355
1356 pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
1362 where
1363 T: ?Sized + ToStatement,
1364 U: Buf + 'static + Send,
1365 {
1366 ops::copy_in(self.on(), statement.__convert()).await
1367 }
1368
1369 pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
1372 where
1373 T: ?Sized + ToStatement,
1374 {
1375 ops::copy_out(self.on(), statement.__convert()).await
1376 }
1377 }
1378 };
1379}
1380
1381query_methods!(Database);
1382query_methods!(DatabaseRef);
1383query_methods!(Connection);
1384query_methods!(Transaction<'_>);
1385
1386queryable!(DatabaseRef);
1387queryable!(Connection);
1388queryable!(Transaction<'_>);
1389
1390connection_methods!(Connection);
1391connection_methods!(Transaction<'_>);
1392
1393#[derive(Debug, thiserror::Error)]
1398#[non_exhaustive]
1399pub enum Error {
1400 #[error(transparent)]
1403 Database(#[from] DatabaseError),
1404 #[error("query returned no rows")]
1406 NoRows,
1407 #[error("query returned more than one row")]
1409 TooManyRows,
1410 #[error(transparent)]
1413 Other(Box<dyn std::error::Error + Send + Sync>),
1414}
1415
1416impl Error {
1417 pub fn database_error(&self) -> Option<&DatabaseError> {
1420 match self {
1421 Error::Database(err) => Some(err),
1422 _ => None,
1423 }
1424 }
1425
1426 fn other(message: impl Into<String>) -> Self {
1428 Error::Other(message.into().into())
1429 }
1430}
1431
1432fn db_err(err: impl Into<DbFailure>) -> Error {
1435 match err.into() {
1436 DbFailure::Client(err) => match DatabaseError::from_client_error(&err) {
1437 Some(db) => db.into(),
1438 None => Error::Other(Box::new(err)),
1439 },
1440 DbFailure::Core(err) => match err.database_error() {
1441 Some(db) => db.into(),
1442 None => Error::other(err.to_string()),
1443 },
1444 DbFailure::Config(err) => DatabaseError::connection_failure(format!("{err:#}")).into(),
1447 }
1448}
1449
1450fn test_err(err: crate::Error) -> Error {
1453 Error::Other(Box::new(err))
1454}
1455
1456enum DbFailure {
1458 Client(tokio_postgres::Error),
1459 Core(postgres::Error),
1460 Config(anyhow::Error),
1461}
1462
1463impl From<tokio_postgres::Error> for DbFailure {
1464 fn from(err: tokio_postgres::Error) -> Self {
1465 DbFailure::Client(err)
1466 }
1467}
1468
1469impl From<postgres::Error> for DbFailure {
1470 fn from(err: postgres::Error) -> Self {
1471 DbFailure::Core(err)
1472 }
1473}
1474
1475impl From<anyhow::Error> for DbFailure {
1476 fn from(err: anyhow::Error) -> Self {
1477 DbFailure::Config(err)
1478 }
1479}