Skip to main content

tank_postgres/
transaction.rs

1use crate::{
2    PostgresConnection, PostgresDriver, PostgresPrepared, ValueWrap,
3    util::stream_postgres_row_to_tank_row,
4};
5use tank_core::{
6    AsQuery, Error, Executor, Query, QueryResult, RawQuery, Result, Row, Transaction,
7    future::{Either, TryFutureExt},
8    stream::{Stream, TryStreamExt},
9};
10
11/// Postgres transaction.
12pub struct PostgresTransaction<'c>(pub(crate) tokio_postgres::Transaction<'c>);
13
14impl<'c> PostgresTransaction<'c> {
15    pub async fn new(client: &'c mut PostgresConnection) -> Result<Self> {
16        Ok(Self(
17            client
18                .client
19                .transaction()
20                .await
21                .inspect_err(|e| log::error!("{e:#}"))?,
22        ))
23    }
24}
25
26impl Executor for PostgresTransaction<'_> {
27    type Driver = PostgresDriver;
28
29    async fn do_prepare(&mut self, sql: &str) -> Result<PostgresPrepared> {
30        Ok(PostgresPrepared::new(
31            self.0
32                .prepare(sql)
33                .await
34                .inspect_err(|e| log::error!("{e:#}"))?,
35        ))
36    }
37    fn run<'s>(
38        &'s mut self,
39        query: impl AsQuery<PostgresDriver> + 's,
40    ) -> impl Stream<Item = Result<QueryResult<impl Row + 's>>> + Send {
41        let mut query = query.as_query(&self.driver());
42        stream_postgres_row_to_tank_row(async move || match query.as_mut() {
43            Query::Raw(RawQuery(sql)) => {
44                let stream = self
45                    .0
46                    .query_raw(sql.as_str(), Vec::<ValueWrap>::new())
47                    .await?;
48                Ok(Either::Left(stream))
49            }
50            Query::Prepared(prepared) => {
51                let params = prepared.take_params()?;
52                let portal = self
53                    .0
54                    .bind_raw(&prepared.statement, params.into_iter())
55                    .await?;
56                Ok(Either::Right(self.0.query_portal_raw(&portal, 0).await?))
57            }
58        })
59        .inspect_err(|e| log::error!("{e:#}"))
60    }
61}
62
63impl<'c> Transaction<'c> for PostgresTransaction<'c> {
64    fn commit(self) -> impl Future<Output = Result<()>> + Send {
65        self.0.commit().map_err(|e| {
66            let error = Error::new(e);
67            log::error!("{error:#}");
68            error
69        })
70    }
71
72    fn rollback(self) -> impl Future<Output = Result<()>> + Send {
73        self.0.rollback().map_err(|e| {
74            let error = Error::new(e);
75            log::error!("{error:#}");
76            error
77        })
78    }
79}