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 Client<'_> {
661 async fn prepare_cached(
664 &self,
665 query: &str,
666 ) -> Result<tokio_postgres::Statement, tokio_postgres::Error> {
667 match self {
668 Client::Pooled(client) => client.prepare_cached(query).await,
669 Client::Connection(client) => client.prepare_cached(query).await,
670 Client::Transaction(tx) => tx.prepare_cached(query).await,
671 }
672 }
673
674 async fn run_cached<T, F, Fut>(&self, query: &str, run: F) -> Result<T, tokio_postgres::Error>
679 where
680 F: Fn(tokio_postgres::Statement) -> Fut,
681 Fut: Future<Output = Result<T, tokio_postgres::Error>>,
682 {
683 match self {
684 Client::Pooled(client) => client.run_cached(query, run).await,
685 Client::Connection(client) => client.run_cached(query, run).await,
686 Client::Transaction(tx) => tx.run_cached(query, run).await,
687 }
688 }
689
690 fn statement_failed(&self, err: &tokio_postgres::Error) {
693 match self {
694 Client::Pooled(client) => client.statement_failed(err),
695 Client::Connection(client) => client.statement_failed(err),
696 Client::Transaction(tx) => tx.statement_failed(err),
697 };
698 }
699}
700
701impl<'a> On<'a> {
702 async fn client(self, statement: &str) -> Result<Client<'a>, Error> {
705 let client = match self {
706 On::Database(db, access) => db.pool_for(access)?.client().await.map(Client::Pooled),
707 On::Connection(conn) => conn.inner.client().await.map(Client::Connection),
708 On::Transaction(tx, _) => Ok(Client::Transaction(tx)),
709 }
710 .map_err(db_err)?;
711 match &client {
712 Client::Pooled(client) => client.will_run(statement),
713 Client::Connection(client) => client.will_run(statement),
714 Client::Transaction(tx) => tx.will_run(statement),
715 }
716 Ok(client)
717 }
718
719 fn span(self, query: &str) -> Result<QuerySpan, Error> {
721 Ok(match self {
722 On::Database(db, _) => db.pool()?.query_span(query),
723 On::Connection(conn) => conn.inner.query_span(query),
724 On::Transaction(tx, _) => tx.query_span(query),
725 })
726 }
727
728 fn conn(self) -> Option<ConnId> {
730 match self {
731 On::Database(..) => None,
732 On::Connection(conn) => Some(conn.id),
733 On::Transaction(_, id) => Some(id),
734 }
735 }
736}
737
738impl Database {
739 fn on(&self) -> On<'_> {
740 On::Database(self, CoreAccess::ReadWrite)
741 }
742}
743
744impl DatabaseRef {
745 fn on(&self) -> On<'_> {
746 On::Database(self.db, self.access.core())
747 }
748}
749
750impl Connection {
751 fn on(&self) -> On<'_> {
752 On::Connection(self)
753 }
754}
755
756impl Transaction<'_> {
757 fn on(&self) -> On<'_> {
758 On::Transaction(&self.inner, self.id)
759 }
760}
761
762mod ops {
764 use super::*;
765
766 pub type Params<'a> = Vec<Param<&'a (dyn ToSql + Sync)>>;
768
769 pub fn params<'a>(params: &[&'a (dyn ToSql + Sync)]) -> Params<'a> {
770 params.iter().map(|p| Param(*p)).collect()
771 }
772
773 fn finish<T>(span: QuerySpan, result: Result<T, Error>) -> Result<T, Error> {
775 span.end(result.as_ref().err());
776 result
777 }
778
779 async fn resolve(
782 on: On<'_>,
783 client: &Client<'_>,
784 statement: StatementRef<'_>,
785 ) -> Result<tokio_postgres::Statement, Error> {
786 match statement {
787 StatementRef::Query(query) => client.prepare_cached(query).await.map_err(db_err),
788 StatementRef::Statement(statement) if on.conn() == Some(statement.conn) => {
789 Ok(statement.inner.clone())
790 }
791 StatementRef::Statement(_) => Err(Error::other(
792 "a prepared statement can only be used on the connection that prepared it, \
793 or in a transaction on that connection",
794 )),
795 }
796 }
797
798 async fn run_statement<T, F, Fut>(
804 on: On<'_>,
805 client: &Client<'_>,
806 statement: StatementRef<'_>,
807 run: F,
808 ) -> Result<T, Error>
809 where
810 F: Fn(tokio_postgres::Statement) -> Fut,
811 Fut: Future<Output = Result<T, tokio_postgres::Error>>,
812 {
813 match statement {
814 StatementRef::Query(query) => client.run_cached(query, run).await.map_err(db_err),
815 statement => {
816 let statement = resolve(on, client, statement).await?;
817 run(statement)
818 .await
819 .inspect_err(|err| client.statement_failed(err))
820 .map_err(db_err)
821 }
822 }
823 }
824
825 pub async fn query_raw<T, P, I>(
826 on: On<'_>,
827 statement: &T,
828 params: I,
829 ) -> Result<RowStream, Error>
830 where
831 T: ?Sized + ToStatement,
832 P: BorrowToSql,
833 I: IntoIterator<Item = P>,
834 I::IntoIter: ExactSizeIterator,
835 {
836 let statement = statement.__convert();
837 let span = on.span(statement.text())?;
838 let result = async {
839 let client = on.client(statement.text()).await?;
840 let statement = resolve(on, &client, statement).await?;
843 client
844 .query_raw(&statement, params.into_iter().map(Param))
845 .await
846 .inspect_err(|err| client.statement_failed(err))
847 .map(RowStream::new)
848 .map_err(db_err)
849 }
850 .await;
851 finish(span, result)
852 }
853
854 async fn query_stream(
856 on: On<'_>,
857 statement: StatementRef<'_>,
858 params: Params<'_>,
859 ) -> Result<RowStream, Error> {
860 let span = on.span(statement.text())?;
861 let result = async {
862 let client = &on.client(statement.text()).await?;
863 let params = ¶ms;
864 run_statement(on, client, statement, |statement| async move {
865 let params = params.iter().map(|p| Param(p.0));
866 client.query_raw(&statement, params).await
867 })
868 .await
869 .map(RowStream::new)
870 }
871 .await;
872 finish(span, result)
873 }
874
875 async fn collect(mut stream: RowStream) -> Result<Vec<Row>, Error> {
876 let mut rows = Vec::new();
877 while let Some(row) = stream.next().await {
878 rows.push(row?);
879 }
880 Ok(rows)
881 }
882
883 pub async fn query(
884 on: On<'_>,
885 statement: StatementRef<'_>,
886 params: Params<'_>,
887 ) -> Result<Vec<Row>, Error> {
888 collect(query_stream(on, statement, params).await?).await
889 }
890
891 pub async fn query_opt(
892 on: On<'_>,
893 statement: StatementRef<'_>,
894 params: Params<'_>,
895 ) -> Result<Option<Row>, Error> {
896 let mut stream = query_stream(on, statement, params).await?;
897 let Some(first) = stream.next().await.transpose()? else {
898 return Ok(None);
899 };
900 if stream.next().await.transpose()?.is_some() {
901 return Err(Error::TooManyRows);
902 }
903 Ok(Some(first))
904 }
905
906 pub async fn query_one(
907 on: On<'_>,
908 statement: StatementRef<'_>,
909 params: Params<'_>,
910 ) -> Result<Row, Error> {
911 query_opt(on, statement, params).await?.ok_or(Error::NoRows)
912 }
913
914 pub async fn query_typed_raw<P, I>(
915 on: On<'_>,
916 query: &str,
917 params: I,
918 ) -> Result<RowStream, Error>
919 where
920 P: BorrowToSql,
921 I: IntoIterator<Item = (P, Type)>,
922 {
923 let span = on.span(query)?;
924 let result = async {
925 let client = on.client(query).await?;
926 client
927 .query_typed_raw(query, params.into_iter().map(|(p, ty)| (Param(p), ty)))
928 .await
929 .map(RowStream::new)
930 .map_err(db_err)
931 }
932 .await;
933 finish(span, result)
934 }
935
936 pub async fn query_typed(
937 on: On<'_>,
938 query: &str,
939 params: Vec<(Param<&(dyn ToSql + Sync)>, Type)>,
940 ) -> Result<Vec<Row>, Error> {
941 let span = on.span(query)?;
942 let result = async {
943 let client = on.client(query).await?;
944 client
945 .query_typed_raw(query, params)
946 .await
947 .map(RowStream::new)
948 .map_err(db_err)
949 }
950 .await;
951 collect(finish(span, result)?).await
952 }
953
954 pub async fn execute_raw<T, P, I>(on: On<'_>, statement: &T, params: I) -> Result<u64, Error>
955 where
956 T: ?Sized + ToStatement,
957 P: BorrowToSql,
958 I: IntoIterator<Item = P>,
959 I::IntoIter: ExactSizeIterator,
960 {
961 let statement = statement.__convert();
962 let span = on.span(statement.text())?;
963 let result = async {
964 let client = on.client(statement.text()).await?;
965 let statement = resolve(on, &client, statement).await?;
967 client
968 .execute_raw(&statement, params.into_iter().map(Param))
969 .await
970 .inspect_err(|err| client.statement_failed(err))
971 .map_err(db_err)
972 }
973 .await;
974 finish(span, result)
975 }
976
977 pub async fn execute(
978 on: On<'_>,
979 statement: StatementRef<'_>,
980 params: Params<'_>,
981 ) -> Result<u64, Error> {
982 let span = on.span(statement.text())?;
983 let result = async {
984 let client = &on.client(statement.text()).await?;
985 let params = ¶ms;
986 run_statement(on, client, statement, |statement| async move {
987 let params = params.iter().map(|p| Param(p.0));
988 client.execute_raw(&statement, params).await
989 })
990 .await
991 }
992 .await;
993 finish(span, result)
994 }
995
996 pub async fn simple_query(on: On<'_>, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
997 let span = on.span(query)?;
998 let result = async {
999 let client = on.client(query).await?;
1000 client.simple_query(query).await.map_err(db_err)
1001 }
1002 .await;
1003 finish(span, result)
1004 }
1005
1006 pub async fn batch_execute(on: On<'_>, query: &str) -> Result<(), Error> {
1007 let span = on.span(query)?;
1008 let result = async {
1009 let client = on.client(query).await?;
1010 client.batch_execute(query).await.map_err(db_err)
1011 }
1012 .await;
1013 finish(span, result)
1014 }
1015
1016 pub async fn prepare(on: On<'_>, query: &str, types: &[Type]) -> Result<Statement, Error> {
1017 let conn = on.conn().expect("only a connection prepares statements");
1018 let client = on.client(query).await?;
1019 let inner = client.prepare_typed(query, types).await.map_err(db_err)?;
1020 Ok(Statement {
1021 inner,
1022 conn,
1023 query: query.into(),
1024 })
1025 }
1026
1027 pub async fn copy_in<U>(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyInSink<U>, Error>
1028 where
1029 U: Buf + 'static + Send,
1030 {
1031 let span = on.span(statement.text())?;
1032 let result = async {
1033 let client = on.client(statement.text()).await?;
1034 let statement = resolve(on, &client, statement).await?;
1035 client.copy_in(&statement).await.map_err(db_err)
1036 }
1037 .await;
1038 finish(span, result)
1039 }
1040
1041 pub async fn copy_out(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyOutStream, Error> {
1042 let span = on.span(statement.text())?;
1043 let result = async {
1044 let client = on.client(statement.text()).await?;
1045 let statement = resolve(on, &client, statement).await?;
1046 client.copy_out(&statement).await.map_err(db_err)
1047 }
1048 .await;
1049 finish(span, result)
1050 }
1051}
1052
1053pub trait Queryable: Send + Sync {
1061 fn execute<T>(
1063 &self,
1064 statement: &T,
1065 params: &[&(dyn ToSql + Sync)],
1066 ) -> impl Future<Output = Result<u64, Error>> + Send
1067 where
1068 T: ?Sized + ToStatement;
1069
1070 fn execute_raw<T, P, I>(
1072 &self,
1073 statement: &T,
1074 params: I,
1075 ) -> impl Future<Output = Result<u64, Error>> + Send
1076 where
1077 T: ?Sized + ToStatement,
1078 P: BorrowToSql + Send,
1079 I: IntoIterator<Item = P> + Send,
1080 I::IntoIter: ExactSizeIterator + Send;
1081
1082 fn query<T>(
1084 &self,
1085 statement: &T,
1086 params: &[&(dyn ToSql + Sync)],
1087 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1088 where
1089 T: ?Sized + ToStatement;
1090
1091 fn query_one<T>(
1093 &self,
1094 statement: &T,
1095 params: &[&(dyn ToSql + Sync)],
1096 ) -> impl Future<Output = Result<Row, Error>> + Send
1097 where
1098 T: ?Sized + ToStatement;
1099
1100 fn query_opt<T>(
1102 &self,
1103 statement: &T,
1104 params: &[&(dyn ToSql + Sync)],
1105 ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1106 where
1107 T: ?Sized + ToStatement;
1108
1109 fn query_raw<T, P, I>(
1111 &self,
1112 statement: &T,
1113 params: I,
1114 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1115 where
1116 T: ?Sized + ToStatement,
1117 P: BorrowToSql + Send,
1118 I: IntoIterator<Item = P> + Send,
1119 I::IntoIter: ExactSizeIterator + Send;
1120
1121 fn query_typed(
1123 &self,
1124 query: &str,
1125 params: &[(&(dyn ToSql + Sync), Type)],
1126 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send;
1127
1128 fn query_typed_raw<P, I>(
1130 &self,
1131 query: &str,
1132 params: I,
1133 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1134 where
1135 P: BorrowToSql + Send,
1136 I: IntoIterator<Item = (P, Type)> + Send,
1137 I::IntoIter: Send;
1138
1139 fn simple_query(
1141 &self,
1142 query: &str,
1143 ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send;
1144
1145 fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
1147}
1148
1149macro_rules! query_methods {
1152 ($ty:ty) => {
1153 impl $ty {
1154 pub async fn query<T>(
1166 &self,
1167 statement: &T,
1168 params: &[&(dyn ToSql + Sync)],
1169 ) -> Result<Vec<Row>, Error>
1170 where
1171 T: ?Sized + ToStatement,
1172 {
1173 ops::query(self.on(), statement.__convert(), ops::params(params)).await
1174 }
1175
1176 pub async fn query_one<T>(
1180 &self,
1181 statement: &T,
1182 params: &[&(dyn ToSql + Sync)],
1183 ) -> Result<Row, Error>
1184 where
1185 T: ?Sized + ToStatement,
1186 {
1187 ops::query_one(self.on(), statement.__convert(), ops::params(params)).await
1188 }
1189
1190 pub async fn query_opt<T>(
1195 &self,
1196 statement: &T,
1197 params: &[&(dyn ToSql + Sync)],
1198 ) -> Result<Option<Row>, Error>
1199 where
1200 T: ?Sized + ToStatement,
1201 {
1202 ops::query_opt(self.on(), statement.__convert(), ops::params(params)).await
1203 }
1204
1205 pub async fn query_raw<T, P, I>(
1209 &self,
1210 statement: &T,
1211 params: I,
1212 ) -> Result<RowStream, Error>
1213 where
1214 T: ?Sized + ToStatement,
1215 P: BorrowToSql,
1216 I: IntoIterator<Item = P>,
1217 I::IntoIter: ExactSizeIterator,
1218 {
1219 ops::query_raw(self.on(), statement, params).await
1220 }
1221
1222 pub async fn query_typed(
1225 &self,
1226 query: &str,
1227 params: &[(&(dyn ToSql + Sync), Type)],
1228 ) -> Result<Vec<Row>, Error> {
1229 let params = params
1230 .iter()
1231 .map(|(p, ty)| (Param(*p), ty.clone()))
1232 .collect();
1233 ops::query_typed(self.on(), query, params).await
1234 }
1235
1236 pub async fn query_typed_raw<P, I>(
1238 &self,
1239 query: &str,
1240 params: I,
1241 ) -> Result<RowStream, Error>
1242 where
1243 P: BorrowToSql,
1244 I: IntoIterator<Item = (P, Type)>,
1245 {
1246 ops::query_typed_raw(self.on(), query, params).await
1247 }
1248
1249 pub async fn execute<T>(
1254 &self,
1255 statement: &T,
1256 params: &[&(dyn ToSql + Sync)],
1257 ) -> Result<u64, Error>
1258 where
1259 T: ?Sized + ToStatement,
1260 {
1261 ops::execute(self.on(), statement.__convert(), ops::params(params)).await
1262 }
1263
1264 pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
1266 where
1267 T: ?Sized + ToStatement,
1268 P: BorrowToSql,
1269 I: IntoIterator<Item = P>,
1270 I::IntoIter: ExactSizeIterator,
1271 {
1272 ops::execute_raw(self.on(), statement, params).await
1273 }
1274
1275 pub async fn simple_query(
1282 &self,
1283 query: &str,
1284 ) -> Result<Vec<SimpleQueryMessage>, Error> {
1285 ops::simple_query(self.on(), query).await
1286 }
1287
1288 pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
1294 ops::batch_execute(self.on(), query).await
1295 }
1296 }
1297 };
1298}
1299
1300macro_rules! queryable {
1302 ($ty:ty) => {
1303 impl Queryable for $ty {
1304 fn execute<T>(
1305 &self,
1306 statement: &T,
1307 params: &[&(dyn ToSql + Sync)],
1308 ) -> impl Future<Output = Result<u64, Error>> + Send
1309 where
1310 T: ?Sized + ToStatement,
1311 {
1312 <$ty>::execute(self, statement, params)
1313 }
1314
1315 fn execute_raw<T, P, I>(
1316 &self,
1317 statement: &T,
1318 params: I,
1319 ) -> impl Future<Output = Result<u64, Error>> + Send
1320 where
1321 T: ?Sized + ToStatement,
1322 P: BorrowToSql + Send,
1323 I: IntoIterator<Item = P> + Send,
1324 I::IntoIter: ExactSizeIterator + Send,
1325 {
1326 <$ty>::execute_raw(self, statement, params)
1327 }
1328
1329 fn query<T>(
1330 &self,
1331 statement: &T,
1332 params: &[&(dyn ToSql + Sync)],
1333 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1334 where
1335 T: ?Sized + ToStatement,
1336 {
1337 <$ty>::query(self, statement, params)
1338 }
1339
1340 fn query_one<T>(
1341 &self,
1342 statement: &T,
1343 params: &[&(dyn ToSql + Sync)],
1344 ) -> impl Future<Output = Result<Row, Error>> + Send
1345 where
1346 T: ?Sized + ToStatement,
1347 {
1348 <$ty>::query_one(self, statement, params)
1349 }
1350
1351 fn query_opt<T>(
1352 &self,
1353 statement: &T,
1354 params: &[&(dyn ToSql + Sync)],
1355 ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1356 where
1357 T: ?Sized + ToStatement,
1358 {
1359 <$ty>::query_opt(self, statement, params)
1360 }
1361
1362 fn query_raw<T, P, I>(
1363 &self,
1364 statement: &T,
1365 params: I,
1366 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1367 where
1368 T: ?Sized + ToStatement,
1369 P: BorrowToSql + Send,
1370 I: IntoIterator<Item = P> + Send,
1371 I::IntoIter: ExactSizeIterator + Send,
1372 {
1373 <$ty>::query_raw(self, statement, params)
1374 }
1375
1376 fn query_typed(
1377 &self,
1378 query: &str,
1379 params: &[(&(dyn ToSql + Sync), Type)],
1380 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send {
1381 <$ty>::query_typed(self, query, params)
1382 }
1383
1384 fn query_typed_raw<P, I>(
1385 &self,
1386 query: &str,
1387 params: I,
1388 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1389 where
1390 P: BorrowToSql + Send,
1391 I: IntoIterator<Item = (P, Type)> + Send,
1392 I::IntoIter: Send,
1393 {
1394 <$ty>::query_typed_raw(self, query, params)
1395 }
1396
1397 fn simple_query(
1398 &self,
1399 query: &str,
1400 ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send {
1401 <$ty>::simple_query(self, query)
1402 }
1403
1404 fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
1405 <$ty>::batch_execute(self, query)
1406 }
1407 }
1408 };
1409}
1410
1411macro_rules! connection_methods {
1413 ($ty:ty) => {
1414 impl $ty {
1415 pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
1421 ops::prepare(self.on(), query, &[]).await
1422 }
1423
1424 pub async fn prepare_typed(
1427 &self,
1428 query: &str,
1429 parameter_types: &[Type],
1430 ) -> Result<Statement, Error> {
1431 ops::prepare(self.on(), query, parameter_types).await
1432 }
1433
1434 pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
1440 where
1441 T: ?Sized + ToStatement,
1442 U: Buf + 'static + Send,
1443 {
1444 ops::copy_in(self.on(), statement.__convert()).await
1445 }
1446
1447 pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
1450 where
1451 T: ?Sized + ToStatement,
1452 {
1453 ops::copy_out(self.on(), statement.__convert()).await
1454 }
1455 }
1456 };
1457}
1458
1459query_methods!(Database);
1460query_methods!(DatabaseRef);
1461query_methods!(Connection);
1462query_methods!(Transaction<'_>);
1463
1464queryable!(DatabaseRef);
1465queryable!(Connection);
1466queryable!(Transaction<'_>);
1467
1468connection_methods!(Connection);
1469connection_methods!(Transaction<'_>);
1470
1471#[derive(Debug, thiserror::Error)]
1476#[non_exhaustive]
1477pub enum Error {
1478 #[error(transparent)]
1481 Database(#[from] DatabaseError),
1482 #[error("query returned no rows")]
1484 NoRows,
1485 #[error("query returned more than one row")]
1487 TooManyRows,
1488 #[error(transparent)]
1491 Other(Box<dyn std::error::Error + Send + Sync>),
1492}
1493
1494impl Error {
1495 pub fn database_error(&self) -> Option<&DatabaseError> {
1498 match self {
1499 Error::Database(err) => Some(err),
1500 _ => None,
1501 }
1502 }
1503
1504 fn other(message: impl Into<String>) -> Self {
1506 Error::Other(message.into().into())
1507 }
1508}
1509
1510fn db_err(err: impl Into<DbFailure>) -> Error {
1513 match err.into() {
1514 DbFailure::Client(err) => match DatabaseError::from_client_error(&err) {
1515 Some(db) => db.into(),
1516 None => Error::Other(Box::new(err)),
1517 },
1518 DbFailure::Core(err) => match err.database_error() {
1519 Some(db) => db.into(),
1520 None => Error::other(err.to_string()),
1521 },
1522 DbFailure::Config(err) => DatabaseError::connection_failure(format!("{err:#}")).into(),
1525 }
1526}
1527
1528fn test_err(err: crate::Error) -> Error {
1531 Error::Other(Box::new(err))
1532}
1533
1534enum DbFailure {
1536 Client(tokio_postgres::Error),
1537 Core(postgres::Error),
1538 Config(anyhow::Error),
1539}
1540
1541impl From<tokio_postgres::Error> for DbFailure {
1542 fn from(err: tokio_postgres::Error) -> Self {
1543 DbFailure::Client(err)
1544 }
1545}
1546
1547impl From<postgres::Error> for DbFailure {
1548 fn from(err: postgres::Error) -> Self {
1549 DbFailure::Core(err)
1550 }
1551}
1552
1553impl From<anyhow::Error> for DbFailure {
1554 fn from(err: anyhow::Error) -> Self {
1555 DbFailure::Config(err)
1556 }
1557}