|
| 1 | +use tokio_postgres::types::{ToSql, Type}; |
| 2 | +use tokio_postgres::{Error, Row}; |
| 3 | + |
| 4 | +use crate::{Client, Statement}; |
| 5 | + |
| 6 | +pub struct Transaction<'a> { |
| 7 | + client: &'a mut Client, |
| 8 | + done: bool, |
| 9 | +} |
| 10 | + |
| 11 | +impl<'a> Drop for Transaction<'a> { |
| 12 | + fn drop(&mut self) { |
| 13 | + if !self.done { |
| 14 | + let _ = self.rollback_inner(); |
| 15 | + } |
| 16 | + } |
| 17 | +} |
| 18 | + |
| 19 | +impl<'a> Transaction<'a> { |
| 20 | + pub(crate) fn new(client: &'a mut Client) -> Transaction<'a> { |
| 21 | + Transaction { |
| 22 | + client, |
| 23 | + done: false, |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + pub fn commit(mut self) -> Result<(), Error> { |
| 28 | + self.done = true; |
| 29 | + self.client.batch_execute("COMMIT") |
| 30 | + } |
| 31 | + |
| 32 | + pub fn rollback(mut self) -> Result<(), Error> { |
| 33 | + self.done = true; |
| 34 | + self.rollback_inner() |
| 35 | + } |
| 36 | + |
| 37 | + fn rollback_inner(&mut self) -> Result<(), Error> { |
| 38 | + self.client.batch_execute("ROLLBACK") |
| 39 | + } |
| 40 | + |
| 41 | + pub fn prepare(&mut self, query: &str) -> Result<Statement, Error> { |
| 42 | + self.client.prepare(query) |
| 43 | + } |
| 44 | + |
| 45 | + pub fn prepare_typed(&mut self, query: &str, types: &[Type]) -> Result<Statement, Error> { |
| 46 | + self.client.prepare_typed(query, types) |
| 47 | + } |
| 48 | + |
| 49 | + pub fn execute(&mut self, statement: &Statement, params: &[&dyn ToSql]) -> Result<u64, Error> { |
| 50 | + self.client.execute(statement, params) |
| 51 | + } |
| 52 | + |
| 53 | + pub fn query( |
| 54 | + &mut self, |
| 55 | + statement: &Statement, |
| 56 | + params: &[&dyn ToSql], |
| 57 | + ) -> Result<Vec<Row>, Error> { |
| 58 | + self.client.query(statement, params) |
| 59 | + } |
| 60 | + |
| 61 | + pub fn batch_execute(&mut self, query: &str) -> Result<(), Error> { |
| 62 | + self.client.batch_execute(query) |
| 63 | + } |
| 64 | +} |
0 commit comments