1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use std::ops::{Deref, DerefMut};

use futures_core::future::BoxFuture;

use crate::connection::Connection;
use crate::cursor::HasCursor;
use crate::database::Database;
use crate::describe::Describe;
use crate::executor::{Execute, Executor, RefExecutor};
use crate::runtime::spawn;

/// Represents an in-progress database transaction.
///
/// A transaction ends with a call to [`commit`] or [`rollback`] in which the wrapped connection (
/// or outer transaction) is returned. If neither are called before the transaction
/// goes out-of-scope, [`rollback`] is called. In other words, [`rollback`] is called on `drop`
/// if the transaction is still in-progress.
///
/// ```rust,ignore
/// // Acquire a new connection and immediately begin a transaction
/// let mut tx = pool.begin().await?;
///
/// sqlx::query("INSERT INTO articles (slug) VALUES ('this-is-a-slug')")
///     .execute(&mut tx)
///     // As we didn't fill in all the required fields in this INSERT,
///     // this statement will fail. Since we used `?`, this function
///     // will immediately return with the error which will cause
///     // this transaction to be rolled back.
///     .await?;
/// ```
///
/// [`commit`]: #method.commit
/// [`rollback`]: #method.rollback
// Transaction<PoolConnection<PgConnection>>
// Transaction<PgConnection>
pub struct Transaction<C>
where
    C: Connection,
{
    inner: Option<C>,
    depth: u32,
}

impl<C> Transaction<C>
where
    C: Connection,
{
    pub(crate) async fn new(depth: u32, mut inner: C) -> crate::Result<Self> {
        if depth == 0 {
            inner.execute("BEGIN").await?;
        } else {
            let stmt = format!("SAVEPOINT _sqlx_savepoint_{}", depth);

            inner.execute(&*stmt).await?;
        }

        Ok(Self {
            inner: Some(inner),
            depth: depth + 1,
        })
    }

    /// Creates a new save point in the current transaction and returns
    /// a new `Transaction` object to manage its scope.
    pub async fn begin(self) -> crate::Result<Transaction<Transaction<C>>> {
        Transaction::new(self.depth, self).await
    }

    /// Commits the current transaction or save point.
    /// Returns the inner connection or transaction.
    pub async fn commit(mut self) -> crate::Result<C> {
        let mut inner = self.inner.take().expect(ERR_FINALIZED);
        let depth = self.depth;

        if depth == 1 {
            inner.execute("COMMIT").await?;
        } else {
            let stmt = format!("RELEASE SAVEPOINT _sqlx_savepoint_{}", depth - 1);

            inner.execute(&*stmt).await?;
        }

        Ok(inner)
    }

    /// Rollback the current transaction or save point.
    /// Returns the inner connection or transaction.
    pub async fn rollback(mut self) -> crate::Result<C> {
        let mut inner = self.inner.take().expect(ERR_FINALIZED);
        let depth = self.depth;

        if depth == 1 {
            inner.execute("ROLLBACK").await?;
        } else {
            let stmt = format!("ROLLBACK TO SAVEPOINT _sqlx_savepoint_{}", depth - 1);

            inner.execute(&*stmt).await?;
        }

        Ok(inner)
    }
}

const ERR_FINALIZED: &str = "(bug) transaction already finalized";

impl<C> Deref for Transaction<C>
where
    C: Connection,
{
    type Target = C;

    fn deref(&self) -> &Self::Target {
        self.inner.as_ref().expect(ERR_FINALIZED)
    }
}

impl<C> DerefMut for Transaction<C>
where
    C: Connection,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner.as_mut().expect(ERR_FINALIZED)
    }
}

impl<C> Connection for Transaction<C>
where
    C: Connection,
{
    // Close is equivalent to
    fn close(mut self) -> BoxFuture<'static, crate::Result<()>> {
        Box::pin(async move {
            let mut inner = self.inner.take().expect(ERR_FINALIZED);

            if self.depth == 1 {
                // This is the root transaction, call rollback
                let res = inner.execute("ROLLBACK").await;

                // No matter the result of the above, call close
                let _ = inner.close().await;

                // Now raise the error if there was one
                res?;
            } else {
                // This is not the root transaction, forward to a nested
                // transaction (to eventually call rollback)
                inner.close().await?
            }

            Ok(())
        })
    }

    #[inline]
    fn ping(&mut self) -> BoxFuture<'_, crate::Result<()>> {
        self.deref_mut().ping()
    }
}

impl<DB, C> Executor for Transaction<C>
where
    DB: Database,
    C: Connection<Database = DB>,
{
    type Database = C::Database;

    fn execute<'e, 'q: 'e, 'c: 'e, E: 'e>(
        &'c mut self,
        query: E,
    ) -> BoxFuture<'e, crate::Result<u64>>
    where
        E: Execute<'q, Self::Database>,
    {
        (**self).execute(query)
    }

    fn fetch<'e, 'q, E>(&'e mut self, query: E) -> <Self::Database as HasCursor<'e, 'q>>::Cursor
    where
        E: Execute<'q, Self::Database>,
    {
        (**self).fetch(query)
    }

    #[doc(hidden)]
    fn describe<'e, 'q, E: 'e>(
        &'e mut self,
        query: E,
    ) -> BoxFuture<'e, crate::Result<Describe<Self::Database>>>
    where
        E: Execute<'q, Self::Database>,
    {
        (**self).describe(query)
    }
}

impl<'e, DB, C> RefExecutor<'e> for &'e mut Transaction<C>
where
    DB: Database,
    C: Connection<Database = DB>,
{
    type Database = DB;

    fn fetch_by_ref<'q, E>(self, query: E) -> <Self::Database as HasCursor<'e, 'q>>::Cursor
    where
        E: Execute<'q, Self::Database>,
    {
        (**self).fetch(query)
    }
}

impl<C> Drop for Transaction<C>
where
    C: Connection,
{
    fn drop(&mut self) {
        if self.depth > 0 {
            if let Some(inner) = self.inner.take() {
                spawn(async move {
                    let _ = inner.close().await;
                });
            }
        }
    }
}