nextsql_tokio_postgres_adapter/
lib.rs1pub use nextsql_backend_rust_runtime::tokio_postgres_impl::{
10 convert_params, to_owned_param, OwnedParam, PgClient, PgRow, PgTransaction,
11};
12pub use nextsql_backend_rust_runtime::{Client, QueryExecutor, Row, ToSqlParam, Transaction};
13
14pub fn owned_params_to_refs(owned: &[OwnedParam]) -> Vec<&(dyn tokio_postgres::types::ToSql + Sync)> {
17 owned
18 .iter()
19 .map(|p| p as &(dyn tokio_postgres::types::ToSql + Sync))
20 .collect()
21}
22
23pub struct PooledPgClient {
28 conn: deadpool_postgres::Object,
29}
30
31impl PooledPgClient {
32 pub fn new(conn: deadpool_postgres::Object) -> Self {
33 Self { conn }
34 }
35
36 pub fn inner(&self) -> &tokio_postgres::Client {
38 use std::ops::Deref;
39 self.conn.deref()
40 }
41
42 fn inner_mut(&mut self) -> &mut tokio_postgres::Client {
43 use std::ops::DerefMut;
44 self.conn.deref_mut()
45 }
46}
47
48impl QueryExecutor for PooledPgClient {
49 type Error = tokio_postgres::Error;
50 type Row = PgRow;
51
52 fn query(
53 &self,
54 sql: &str,
55 params: &[&dyn ToSqlParam],
56 ) -> impl std::future::Future<Output = Result<Vec<Self::Row>, Self::Error>> + Send {
57 let owned_params = convert_params(params);
58 let sql = sql.to_owned();
59 let client = self.inner();
60 async move {
61 let param_refs = owned_params_to_refs(&owned_params);
62 let rows = client.query(&sql, ¶m_refs).await?;
63 Ok(rows.into_iter().map(PgRow).collect())
64 }
65 }
66
67 fn execute(
68 &self,
69 sql: &str,
70 params: &[&dyn ToSqlParam],
71 ) -> impl std::future::Future<Output = Result<u64, Self::Error>> + Send {
72 let owned_params = convert_params(params);
73 let sql = sql.to_owned();
74 let client = self.inner();
75 async move {
76 let param_refs = owned_params_to_refs(&owned_params);
77 client.execute(&sql, ¶m_refs).await
78 }
79 }
80}
81
82impl Client for PooledPgClient {
83 type Transaction<'a> = PgTransaction<'a>;
84
85 fn transaction(
86 &mut self,
87 ) -> impl std::future::Future<Output = Result<Self::Transaction<'_>, Self::Error>> + Send {
88 async move {
89 let tx = self.inner_mut().transaction().await?;
90 Ok(PgTransaction::new(tx))
91 }
92 }
93}