1mod row;
78#[cfg(test)]
79mod tests;
80pub mod types;
81
82use std::fmt::Display;
83use std::future::Future;
84use std::marker::PhantomData;
85use std::ops::Deref;
86use std::sync::{Arc, OnceLock};
87
88use bytes::Buf;
89use encore_sdk_core::postgres::Access as CoreAccess;
90use encore_sdk_core::postgres::{self, Pool, QuerySpan};
91
92use crate::error::{ErrCode, Error};
93use crate::runtime::core;
94use crate::testing;
95
96use self::row::{ConnId, StatementRef};
97use self::types::{BorrowToSql, Param, ToSql, Type};
98
99pub use self::row::{Column, Row, RowIndex, RowStream, Statement, ToStatement};
100pub use tokio_postgres::{
101 CopyInSink, CopyOutStream, IsolationLevel, SimpleColumn, SimpleQueryMessage, SimpleQueryRow,
102};
103
104pub struct Database {
106 name: &'static str,
107 #[allow(dead_code)]
109 migrations: Option<&'static str>,
110 pool: OnceLock<Arc<Pool>>,
111}
112
113impl Database {
114 pub const fn new(name: &'static str) -> Self {
125 Self {
126 name,
127 migrations: None,
128 pool: OnceLock::new(),
129 }
130 }
131
132 pub const fn named(name: &'static str) -> Self {
146 Self::new(name)
147 }
148
149 pub const fn migrations(mut self, path: &'static str) -> Self {
156 self.migrations = Some(path);
157 self
158 }
159
160 pub const fn admin(&'static self) -> DatabaseRef {
164 DatabaseRef {
165 db: self,
166 access: Access::Admin,
167 }
168 }
169
170 pub const fn write(&'static self) -> DatabaseRef {
172 DatabaseRef {
173 db: self,
174 access: Access::Write,
175 }
176 }
177
178 pub const fn read(&'static self) -> DatabaseRef {
189 DatabaseRef {
190 db: self,
191 access: Access::Read { primary: false },
192 }
193 }
194
195 pub const fn read_primary(&'static self) -> DatabaseRef {
198 DatabaseRef {
199 db: self,
200 access: Access::Read { primary: true },
201 }
202 }
203
204 fn pool(&self) -> Result<Arc<Pool>, Error> {
207 if let Some(test) = testing::active()? {
208 return test.database_pool(self.name);
209 }
210 if let Some(pool) = self.pool.get() {
211 return Ok(pool.clone());
212 }
213 let pool = core()
214 .postgres()
215 .database(&self.name.into())
216 .new_pool()
217 .map_err(db_err)?;
218 let _ = self.pool.set(Arc::new(pool));
220 Ok(self.pool.get().expect("pool just set").clone())
221 }
222
223 pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
234 self.begin(CoreAccess::ReadWrite, "START TRANSACTION").await
235 }
236
237 pub fn build_transaction(&self) -> TransactionBuilder<'_> {
248 TransactionBuilder::new(Target::Database(self, CoreAccess::ReadWrite))
249 }
250
251 fn pool_for(&self, access: CoreAccess) -> Result<Pool, Error> {
253 self.pool()?.with_access(access).map_err(db_err)
254 }
255
256 async fn begin(
257 &self,
258 access: CoreAccess,
259 statement: &str,
260 ) -> Result<Transaction<'static>, Error> {
261 let inner = self
262 .pool_for(access)?
263 .begin_with(statement)
264 .await
265 .map_err(db_err)?;
266 Ok(Transaction {
267 inner,
268 id: ConnId::new(),
269 conn: PhantomData,
270 })
271 }
272
273 pub async fn acquire(&self) -> Result<Connection, Error> {
276 self.acquire_as(CoreAccess::ReadWrite).await
277 }
278
279 async fn acquire_as(&self, access: CoreAccess) -> Result<Connection, Error> {
280 let inner = self.pool_for(access)?.acquire().await.map_err(db_err)?;
281 Ok(Connection {
282 inner,
283 id: ConnId::new(),
284 })
285 }
286
287 pub fn connection_string(&self) -> Result<String, Error> {
292 self.connection_string_as(CoreAccess::ReadWrite)
293 }
294
295 fn connection_string_as(&self, access: CoreAccess) -> Result<String, Error> {
296 if let Some(test) = testing::active()? {
297 return test.database_connection_string(self.name, access);
298 }
299 Ok(core()
300 .postgres()
301 .database(&self.name.into())
302 .proxy_conn_string(access))
303 }
304}
305
306#[derive(Clone, Copy)]
314enum Access {
315 Admin,
316 Write,
317 Read { primary: bool },
318}
319
320impl Access {
321 fn core(self) -> CoreAccess {
323 match self {
324 Access::Admin | Access::Write => CoreAccess::ReadWrite,
325 Access::Read { primary: false } => CoreAccess::Read,
326 Access::Read { primary: true } => CoreAccess::ReadPrimary,
327 }
328 }
329}
330
331#[derive(Clone, Copy)]
347pub struct DatabaseRef {
348 db: &'static Database,
349 access: Access,
350}
351
352impl DatabaseRef {
353 pub async fn transaction(&self) -> Result<Transaction<'static>, Error> {
356 self.db.begin(self.access.core(), "START TRANSACTION").await
357 }
358
359 pub fn build_transaction(&self) -> TransactionBuilder<'static> {
362 TransactionBuilder::new(Target::Database(self.db, self.access.core()))
363 }
364
365 pub async fn acquire(&self) -> Result<Connection, Error> {
368 self.db.acquire_as(self.access.core()).await
369 }
370
371 pub fn connection_string(&self) -> Result<String, Error> {
379 self.db.connection_string_as(self.access.core())
380 }
381}
382
383pub struct Connection {
389 inner: postgres::Connection,
390 id: ConnId,
391}
392
393impl Connection {
394 pub async fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
397 self.begin("START TRANSACTION").await
398 }
399
400 pub fn build_transaction(&mut self) -> TransactionBuilder<'_> {
403 TransactionBuilder::new(Target::Connection(self))
404 }
405
406 async fn begin(&mut self, statement: &str) -> Result<Transaction<'_>, Error> {
407 let inner = self.inner.begin_with(statement).await.map_err(db_err)?;
408 Ok(Transaction {
409 inner,
410 id: self.id,
411 conn: PhantomData,
412 })
413 }
414
415 pub fn is_closed(&self) -> bool {
418 self.inner.is_closed()
419 }
420
421 pub async fn close(self) {
424 self.inner.close().await;
425 }
426}
427
428pub struct Transaction<'c> {
433 inner: postgres::Transaction,
434 id: ConnId,
435 conn: PhantomData<&'c mut Connection>,
436}
437
438impl Transaction<'_> {
439 pub async fn commit(self) -> Result<(), Error> {
441 self.inner.commit().await.map_err(db_err)
442 }
443
444 pub async fn rollback(self) -> Result<(), Error> {
446 self.inner.rollback().await.map_err(db_err)
447 }
448}
449
450enum Target<'a> {
452 Database(&'a Database, CoreAccess),
454 Connection(&'a mut Connection),
455}
456
457pub struct TransactionBuilder<'a> {
460 target: Target<'a>,
461 isolation_level: Option<IsolationLevel>,
462 read_only: Option<bool>,
463 deferrable: Option<bool>,
464}
465
466impl<'a> TransactionBuilder<'a> {
467 fn new(target: Target<'a>) -> Self {
468 Self {
469 target,
470 isolation_level: None,
471 read_only: None,
472 deferrable: None,
473 }
474 }
475
476 pub fn isolation_level(mut self, isolation_level: IsolationLevel) -> Self {
478 self.isolation_level = Some(isolation_level);
479 self
480 }
481
482 pub fn read_only(mut self, read_only: bool) -> Self {
484 self.read_only = Some(read_only);
485 self
486 }
487
488 pub fn deferrable(mut self, deferrable: bool) -> Self {
493 self.deferrable = Some(deferrable);
494 self
495 }
496
497 pub async fn start(self) -> Result<Transaction<'a>, Error> {
499 let mut options = Vec::new();
500 if let Some(level) = self.isolation_level {
501 options.push(match level {
502 IsolationLevel::ReadUncommitted => "ISOLATION LEVEL READ UNCOMMITTED",
503 IsolationLevel::ReadCommitted => "ISOLATION LEVEL READ COMMITTED",
504 IsolationLevel::RepeatableRead => "ISOLATION LEVEL REPEATABLE READ",
505 IsolationLevel::Serializable => "ISOLATION LEVEL SERIALIZABLE",
506 _ => return Err(Error::invalid_argument("unsupported isolation level")),
507 });
508 }
509 if let Some(read_only) = self.read_only {
510 options.push(if read_only { "READ ONLY" } else { "READ WRITE" });
511 }
512 if let Some(deferrable) = self.deferrable {
513 options.push(if deferrable {
514 "DEFERRABLE"
515 } else {
516 "NOT DEFERRABLE"
517 });
518 }
519 let statement = format!("START TRANSACTION {}", options.join(", "));
520 match self.target {
521 Target::Database(db, access) => db.begin(access, &statement).await,
522 Target::Connection(conn) => conn.begin(&statement).await,
523 }
524 }
525}
526
527#[derive(Clone, Copy)]
529enum On<'a> {
530 Database(&'a Database, CoreAccess),
532 Connection(&'a Connection),
533 Transaction(&'a postgres::Transaction, ConnId),
534}
535
536enum Client<'a> {
538 Pooled(postgres::PooledClient),
540 Connection(postgres::ConnClient<'a>),
541 Transaction(&'a postgres::Transaction),
542}
543
544impl Deref for Client<'_> {
545 type Target = tokio_postgres::Client;
546
547 fn deref(&self) -> &Self::Target {
548 match self {
549 Client::Pooled(client) => client,
550 Client::Connection(client) => client,
551 Client::Transaction(tx) => tx.client(),
552 }
553 }
554}
555
556impl<'a> On<'a> {
557 async fn client(self, statement: &str) -> Result<Client<'a>, Error> {
560 let client = match self {
561 On::Database(db, access) => db.pool_for(access)?.client().await.map(Client::Pooled),
562 On::Connection(conn) => conn.inner.client().await.map(Client::Connection),
563 On::Transaction(tx, _) => Ok(Client::Transaction(tx)),
564 }
565 .map_err(db_err)?;
566 match &client {
567 Client::Pooled(client) => client.will_run(statement),
568 Client::Connection(client) => client.will_run(statement),
569 Client::Transaction(tx) => tx.will_run(statement),
570 }
571 Ok(client)
572 }
573
574 fn span(self, query: &str) -> Result<QuerySpan, Error> {
576 Ok(match self {
577 On::Database(db, _) => db.pool()?.query_span(query),
578 On::Connection(conn) => conn.inner.query_span(query),
579 On::Transaction(tx, _) => tx.query_span(query),
580 })
581 }
582
583 fn conn(self) -> Option<ConnId> {
585 match self {
586 On::Database(..) => None,
587 On::Connection(conn) => Some(conn.id),
588 On::Transaction(_, id) => Some(id),
589 }
590 }
591}
592
593impl Database {
594 fn on(&self) -> On<'_> {
595 On::Database(self, CoreAccess::ReadWrite)
596 }
597}
598
599impl DatabaseRef {
600 fn on(&self) -> On<'_> {
601 On::Database(self.db, self.access.core())
602 }
603}
604
605impl Connection {
606 fn on(&self) -> On<'_> {
607 On::Connection(self)
608 }
609}
610
611impl Transaction<'_> {
612 fn on(&self) -> On<'_> {
613 On::Transaction(&self.inner, self.id)
614 }
615}
616
617mod ops {
619 use super::*;
620
621 pub type Params<'a> = Vec<Param<&'a (dyn ToSql + Sync)>>;
623
624 pub fn params<'a>(params: &[&'a (dyn ToSql + Sync)]) -> Params<'a> {
625 params.iter().map(|p| Param(*p)).collect()
626 }
627
628 fn finish<T>(span: QuerySpan, result: Result<T, Error>) -> Result<T, Error> {
630 span.end(result.as_ref().err());
631 result
632 }
633
634 async fn resolve(
637 on: On<'_>,
638 client: &tokio_postgres::Client,
639 statement: StatementRef<'_>,
640 ) -> Result<tokio_postgres::Statement, Error> {
641 match statement {
642 StatementRef::Query(query) => client.prepare(query).await.map_err(db_err),
643 StatementRef::Statement(statement) if on.conn() == Some(statement.conn) => {
644 Ok(statement.inner.clone())
645 }
646 StatementRef::Statement(_) => Err(Error::invalid_argument(
647 "a prepared statement can only be used on the connection that prepared it, \
648 or in a transaction on that connection",
649 )),
650 }
651 }
652
653 pub async fn query_raw<T, P, I>(
654 on: On<'_>,
655 statement: &T,
656 params: I,
657 ) -> Result<RowStream, Error>
658 where
659 T: ?Sized + ToStatement,
660 P: BorrowToSql,
661 I: IntoIterator<Item = P>,
662 I::IntoIter: ExactSizeIterator,
663 {
664 let statement = statement.__convert();
665 let span = on.span(statement.text())?;
666 let result = async {
667 let client = on.client(statement.text()).await?;
668 let statement = resolve(on, &client, statement).await?;
669 client
670 .query_raw(&statement, params.into_iter().map(Param))
671 .await
672 .map(RowStream::new)
673 .map_err(db_err)
674 }
675 .await;
676 finish(span, result)
677 }
678
679 async fn query_stream(
681 on: On<'_>,
682 statement: StatementRef<'_>,
683 params: Params<'_>,
684 ) -> Result<RowStream, Error> {
685 let span = on.span(statement.text())?;
686 let result = async {
687 let client = on.client(statement.text()).await?;
688 let statement = resolve(on, &client, statement).await?;
689 client
690 .query_raw(&statement, params)
691 .await
692 .map(RowStream::new)
693 .map_err(db_err)
694 }
695 .await;
696 finish(span, result)
697 }
698
699 async fn collect(mut stream: RowStream) -> Result<Vec<Row>, Error> {
700 let mut rows = Vec::new();
701 while let Some(row) = stream.next().await {
702 rows.push(row?);
703 }
704 Ok(rows)
705 }
706
707 pub async fn query(
708 on: On<'_>,
709 statement: StatementRef<'_>,
710 params: Params<'_>,
711 ) -> Result<Vec<Row>, Error> {
712 collect(query_stream(on, statement, params).await?).await
713 }
714
715 pub async fn query_opt(
716 on: On<'_>,
717 statement: StatementRef<'_>,
718 params: Params<'_>,
719 ) -> Result<Option<Row>, Error> {
720 let mut stream = query_stream(on, statement, params).await?;
721 let Some(first) = stream.next().await.transpose()? else {
722 return Ok(None);
723 };
724 if stream.next().await.transpose()?.is_some() {
725 return Err(Error::new(
726 ErrCode::FailedPrecondition,
727 "query returned an unexpected number of rows",
728 ));
729 }
730 Ok(Some(first))
731 }
732
733 pub async fn query_one(
734 on: On<'_>,
735 statement: StatementRef<'_>,
736 params: Params<'_>,
737 ) -> Result<Row, Error> {
738 query_opt(on, statement, params)
739 .await?
740 .ok_or_else(|| Error::not_found("query returned an unexpected number of rows"))
741 }
742
743 pub async fn query_typed_raw<P, I>(
744 on: On<'_>,
745 query: &str,
746 params: I,
747 ) -> Result<RowStream, Error>
748 where
749 P: BorrowToSql,
750 I: IntoIterator<Item = (P, Type)>,
751 {
752 let span = on.span(query)?;
753 let result = async {
754 let client = on.client(query).await?;
755 client
756 .query_typed_raw(query, params.into_iter().map(|(p, ty)| (Param(p), ty)))
757 .await
758 .map(RowStream::new)
759 .map_err(db_err)
760 }
761 .await;
762 finish(span, result)
763 }
764
765 pub async fn query_typed(
766 on: On<'_>,
767 query: &str,
768 params: Vec<(Param<&(dyn ToSql + Sync)>, Type)>,
769 ) -> Result<Vec<Row>, Error> {
770 let span = on.span(query)?;
771 let result = async {
772 let client = on.client(query).await?;
773 client
774 .query_typed_raw(query, params)
775 .await
776 .map(RowStream::new)
777 .map_err(db_err)
778 }
779 .await;
780 collect(finish(span, result)?).await
781 }
782
783 pub async fn execute_raw<T, P, I>(on: On<'_>, statement: &T, params: I) -> Result<u64, Error>
784 where
785 T: ?Sized + ToStatement,
786 P: BorrowToSql,
787 I: IntoIterator<Item = P>,
788 I::IntoIter: ExactSizeIterator,
789 {
790 let statement = statement.__convert();
791 let span = on.span(statement.text())?;
792 let result = async {
793 let client = on.client(statement.text()).await?;
794 let statement = resolve(on, &client, statement).await?;
795 client
796 .execute_raw(&statement, params.into_iter().map(Param))
797 .await
798 .map_err(db_err)
799 }
800 .await;
801 finish(span, result)
802 }
803
804 pub async fn execute(
805 on: On<'_>,
806 statement: StatementRef<'_>,
807 params: Params<'_>,
808 ) -> Result<u64, Error> {
809 let span = on.span(statement.text())?;
810 let result = async {
811 let client = on.client(statement.text()).await?;
812 let statement = resolve(on, &client, statement).await?;
813 client.execute_raw(&statement, params).await.map_err(db_err)
814 }
815 .await;
816 finish(span, result)
817 }
818
819 pub async fn simple_query(on: On<'_>, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
820 let span = on.span(query)?;
821 let result = async {
822 let client = on.client(query).await?;
823 client.simple_query(query).await.map_err(db_err)
824 }
825 .await;
826 finish(span, result)
827 }
828
829 pub async fn batch_execute(on: On<'_>, query: &str) -> Result<(), Error> {
830 let span = on.span(query)?;
831 let result = async {
832 let client = on.client(query).await?;
833 client.batch_execute(query).await.map_err(db_err)
834 }
835 .await;
836 finish(span, result)
837 }
838
839 pub async fn prepare(on: On<'_>, query: &str, types: &[Type]) -> Result<Statement, Error> {
840 let conn = on.conn().expect("only a connection prepares statements");
841 let client = on.client(query).await?;
842 let inner = client.prepare_typed(query, types).await.map_err(db_err)?;
843 Ok(Statement {
844 inner,
845 conn,
846 query: query.into(),
847 })
848 }
849
850 pub async fn copy_in<U>(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyInSink<U>, Error>
851 where
852 U: Buf + 'static + Send,
853 {
854 let span = on.span(statement.text())?;
855 let result = async {
856 let client = on.client(statement.text()).await?;
857 let statement = resolve(on, &client, statement).await?;
858 client.copy_in(&statement).await.map_err(db_err)
859 }
860 .await;
861 finish(span, result)
862 }
863
864 pub async fn copy_out(on: On<'_>, statement: StatementRef<'_>) -> Result<CopyOutStream, Error> {
865 let span = on.span(statement.text())?;
866 let result = async {
867 let client = on.client(statement.text()).await?;
868 let statement = resolve(on, &client, statement).await?;
869 client.copy_out(&statement).await.map_err(db_err)
870 }
871 .await;
872 finish(span, result)
873 }
874}
875
876pub trait Queryable: Send + Sync {
886 fn execute<T>(
888 &self,
889 statement: &T,
890 params: &[&(dyn ToSql + Sync)],
891 ) -> impl Future<Output = Result<u64, Error>> + Send
892 where
893 T: ?Sized + ToStatement;
894
895 fn execute_raw<T, P, I>(
897 &self,
898 statement: &T,
899 params: I,
900 ) -> impl Future<Output = Result<u64, Error>> + Send
901 where
902 T: ?Sized + ToStatement,
903 P: BorrowToSql + Send,
904 I: IntoIterator<Item = P> + Send,
905 I::IntoIter: ExactSizeIterator + Send;
906
907 fn query<T>(
909 &self,
910 statement: &T,
911 params: &[&(dyn ToSql + Sync)],
912 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
913 where
914 T: ?Sized + ToStatement;
915
916 fn query_one<T>(
918 &self,
919 statement: &T,
920 params: &[&(dyn ToSql + Sync)],
921 ) -> impl Future<Output = Result<Row, Error>> + Send
922 where
923 T: ?Sized + ToStatement;
924
925 fn query_opt<T>(
927 &self,
928 statement: &T,
929 params: &[&(dyn ToSql + Sync)],
930 ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
931 where
932 T: ?Sized + ToStatement;
933
934 fn query_raw<T, P, I>(
936 &self,
937 statement: &T,
938 params: I,
939 ) -> impl Future<Output = Result<RowStream, Error>> + Send
940 where
941 T: ?Sized + ToStatement,
942 P: BorrowToSql + Send,
943 I: IntoIterator<Item = P> + Send,
944 I::IntoIter: ExactSizeIterator + Send;
945
946 fn query_typed(
948 &self,
949 query: &str,
950 params: &[(&(dyn ToSql + Sync), Type)],
951 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send;
952
953 fn query_typed_raw<P, I>(
955 &self,
956 query: &str,
957 params: I,
958 ) -> impl Future<Output = Result<RowStream, Error>> + Send
959 where
960 P: BorrowToSql + Send,
961 I: IntoIterator<Item = (P, Type)> + Send,
962 I::IntoIter: Send;
963
964 fn simple_query(
966 &self,
967 query: &str,
968 ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send;
969
970 fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send;
972}
973
974macro_rules! query_methods {
977 ($ty:ty) => {
978 impl $ty {
979 pub async fn query<T>(
991 &self,
992 statement: &T,
993 params: &[&(dyn ToSql + Sync)],
994 ) -> Result<Vec<Row>, Error>
995 where
996 T: ?Sized + ToStatement,
997 {
998 ops::query(self.on(), statement.__convert(), ops::params(params)).await
999 }
1000
1001 pub async fn query_one<T>(
1005 &self,
1006 statement: &T,
1007 params: &[&(dyn ToSql + Sync)],
1008 ) -> Result<Row, Error>
1009 where
1010 T: ?Sized + ToStatement,
1011 {
1012 ops::query_one(self.on(), statement.__convert(), ops::params(params)).await
1013 }
1014
1015 pub async fn query_opt<T>(
1020 &self,
1021 statement: &T,
1022 params: &[&(dyn ToSql + Sync)],
1023 ) -> Result<Option<Row>, Error>
1024 where
1025 T: ?Sized + ToStatement,
1026 {
1027 ops::query_opt(self.on(), statement.__convert(), ops::params(params)).await
1028 }
1029
1030 pub async fn query_raw<T, P, I>(
1034 &self,
1035 statement: &T,
1036 params: I,
1037 ) -> Result<RowStream, Error>
1038 where
1039 T: ?Sized + ToStatement,
1040 P: BorrowToSql,
1041 I: IntoIterator<Item = P>,
1042 I::IntoIter: ExactSizeIterator,
1043 {
1044 ops::query_raw(self.on(), statement, params).await
1045 }
1046
1047 pub async fn query_typed(
1050 &self,
1051 query: &str,
1052 params: &[(&(dyn ToSql + Sync), Type)],
1053 ) -> Result<Vec<Row>, Error> {
1054 let params = params
1055 .iter()
1056 .map(|(p, ty)| (Param(*p), ty.clone()))
1057 .collect();
1058 ops::query_typed(self.on(), query, params).await
1059 }
1060
1061 pub async fn query_typed_raw<P, I>(
1063 &self,
1064 query: &str,
1065 params: I,
1066 ) -> Result<RowStream, Error>
1067 where
1068 P: BorrowToSql,
1069 I: IntoIterator<Item = (P, Type)>,
1070 {
1071 ops::query_typed_raw(self.on(), query, params).await
1072 }
1073
1074 pub async fn execute<T>(
1079 &self,
1080 statement: &T,
1081 params: &[&(dyn ToSql + Sync)],
1082 ) -> Result<u64, Error>
1083 where
1084 T: ?Sized + ToStatement,
1085 {
1086 ops::execute(self.on(), statement.__convert(), ops::params(params)).await
1087 }
1088
1089 pub async fn execute_raw<T, P, I>(&self, statement: &T, params: I) -> Result<u64, Error>
1091 where
1092 T: ?Sized + ToStatement,
1093 P: BorrowToSql,
1094 I: IntoIterator<Item = P>,
1095 I::IntoIter: ExactSizeIterator,
1096 {
1097 ops::execute_raw(self.on(), statement, params).await
1098 }
1099
1100 pub async fn simple_query(
1107 &self,
1108 query: &str,
1109 ) -> Result<Vec<SimpleQueryMessage>, Error> {
1110 ops::simple_query(self.on(), query).await
1111 }
1112
1113 pub async fn batch_execute(&self, query: &str) -> Result<(), Error> {
1119 ops::batch_execute(self.on(), query).await
1120 }
1121 }
1122 };
1123}
1124
1125macro_rules! queryable {
1127 ($ty:ty) => {
1128 impl Queryable for $ty {
1129 fn execute<T>(
1130 &self,
1131 statement: &T,
1132 params: &[&(dyn ToSql + Sync)],
1133 ) -> impl Future<Output = Result<u64, Error>> + Send
1134 where
1135 T: ?Sized + ToStatement,
1136 {
1137 <$ty>::execute(self, statement, params)
1138 }
1139
1140 fn execute_raw<T, P, I>(
1141 &self,
1142 statement: &T,
1143 params: I,
1144 ) -> impl Future<Output = Result<u64, Error>> + Send
1145 where
1146 T: ?Sized + ToStatement,
1147 P: BorrowToSql + Send,
1148 I: IntoIterator<Item = P> + Send,
1149 I::IntoIter: ExactSizeIterator + Send,
1150 {
1151 <$ty>::execute_raw(self, statement, params)
1152 }
1153
1154 fn query<T>(
1155 &self,
1156 statement: &T,
1157 params: &[&(dyn ToSql + Sync)],
1158 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send
1159 where
1160 T: ?Sized + ToStatement,
1161 {
1162 <$ty>::query(self, statement, params)
1163 }
1164
1165 fn query_one<T>(
1166 &self,
1167 statement: &T,
1168 params: &[&(dyn ToSql + Sync)],
1169 ) -> impl Future<Output = Result<Row, Error>> + Send
1170 where
1171 T: ?Sized + ToStatement,
1172 {
1173 <$ty>::query_one(self, statement, params)
1174 }
1175
1176 fn query_opt<T>(
1177 &self,
1178 statement: &T,
1179 params: &[&(dyn ToSql + Sync)],
1180 ) -> impl Future<Output = Result<Option<Row>, Error>> + Send
1181 where
1182 T: ?Sized + ToStatement,
1183 {
1184 <$ty>::query_opt(self, statement, params)
1185 }
1186
1187 fn query_raw<T, P, I>(
1188 &self,
1189 statement: &T,
1190 params: I,
1191 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1192 where
1193 T: ?Sized + ToStatement,
1194 P: BorrowToSql + Send,
1195 I: IntoIterator<Item = P> + Send,
1196 I::IntoIter: ExactSizeIterator + Send,
1197 {
1198 <$ty>::query_raw(self, statement, params)
1199 }
1200
1201 fn query_typed(
1202 &self,
1203 query: &str,
1204 params: &[(&(dyn ToSql + Sync), Type)],
1205 ) -> impl Future<Output = Result<Vec<Row>, Error>> + Send {
1206 <$ty>::query_typed(self, query, params)
1207 }
1208
1209 fn query_typed_raw<P, I>(
1210 &self,
1211 query: &str,
1212 params: I,
1213 ) -> impl Future<Output = Result<RowStream, Error>> + Send
1214 where
1215 P: BorrowToSql + Send,
1216 I: IntoIterator<Item = (P, Type)> + Send,
1217 I::IntoIter: Send,
1218 {
1219 <$ty>::query_typed_raw(self, query, params)
1220 }
1221
1222 fn simple_query(
1223 &self,
1224 query: &str,
1225 ) -> impl Future<Output = Result<Vec<SimpleQueryMessage>, Error>> + Send {
1226 <$ty>::simple_query(self, query)
1227 }
1228
1229 fn batch_execute(&self, query: &str) -> impl Future<Output = Result<(), Error>> + Send {
1230 <$ty>::batch_execute(self, query)
1231 }
1232 }
1233 };
1234}
1235
1236macro_rules! connection_methods {
1238 ($ty:ty) => {
1239 impl $ty {
1240 pub async fn prepare(&self, query: &str) -> Result<Statement, Error> {
1246 ops::prepare(self.on(), query, &[]).await
1247 }
1248
1249 pub async fn prepare_typed(
1252 &self,
1253 query: &str,
1254 parameter_types: &[Type],
1255 ) -> Result<Statement, Error> {
1256 ops::prepare(self.on(), query, parameter_types).await
1257 }
1258
1259 pub async fn copy_in<T, U>(&self, statement: &T) -> Result<CopyInSink<U>, Error>
1265 where
1266 T: ?Sized + ToStatement,
1267 U: Buf + 'static + Send,
1268 {
1269 ops::copy_in(self.on(), statement.__convert()).await
1270 }
1271
1272 pub async fn copy_out<T>(&self, statement: &T) -> Result<CopyOutStream, Error>
1275 where
1276 T: ?Sized + ToStatement,
1277 {
1278 ops::copy_out(self.on(), statement.__convert()).await
1279 }
1280 }
1281 };
1282}
1283
1284query_methods!(Database);
1285query_methods!(DatabaseRef);
1286query_methods!(Connection);
1287query_methods!(Transaction<'_>);
1288
1289queryable!(DatabaseRef);
1290queryable!(Connection);
1291queryable!(Transaction<'_>);
1292
1293connection_methods!(Connection);
1294connection_methods!(Transaction<'_>);
1295
1296fn db_err(err: impl Display) -> Error {
1297 Error::wrap(ErrCode::Unavailable, err)
1298}