diesel/connection/
mod.rs

1//! Types related to database connections
2
3mod statement_cache;
4mod transaction_manager;
5
6use std::fmt::Debug;
7
8use backend::Backend;
9use deserialize::{Queryable, QueryableByName};
10use query_builder::{AsQuery, QueryFragment, QueryId};
11use result::*;
12use sql_types::HasSqlType;
13
14#[doc(hidden)]
15pub use self::statement_cache::{MaybeCached, StatementCache, StatementCacheKey};
16pub use self::transaction_manager::{AnsiTransactionManager, TransactionManager};
17
18/// Perform simple operations on a backend.
19///
20/// You should likely use [`Connection`](trait.Connection.html) instead.
21pub trait SimpleConnection {
22    /// Execute multiple SQL statements within the same string.
23    ///
24    /// This function is used to execute migrations,
25    /// which may contain more than one SQL statement.
26    fn batch_execute(&self, query: &str) -> QueryResult<()>;
27}
28
29/// A connection to a database
30pub trait Connection: SimpleConnection + Sized + Send {
31    /// The backend this type connects to
32    type Backend: Backend;
33    #[doc(hidden)]
34    type TransactionManager: TransactionManager<Self>;
35
36    /// Establishes a new connection to the database
37    ///
38    /// The argument to this method varies by backend.
39    /// See the documentation for that backend's connection class
40    /// for details about what it accepts.
41    fn establish(database_url: &str) -> ConnectionResult<Self>;
42
43    /// Executes the given function inside of a database transaction
44    ///
45    /// If there is already an open transaction,
46    /// savepoints will be used instead.
47    ///
48    /// If the transaction fails to commit due to a `SerializationFailure`, a rollback will be attempted.
49    /// If the rollback succeeds, the original error will be returned, otherwise the error generated by
50    /// the rollback will be returned. In the second case the connection should be considered broken
51    /// as it contains a uncommitted unabortable open transaction.
52    /// # Example
53    ///
54    /// ```rust
55    /// # #[macro_use] extern crate diesel;
56    /// # include!("../doctest_setup.rs");
57    /// use diesel::result::Error;
58    ///
59    /// # fn main() {
60    /// #     run_test().unwrap();
61    /// # }
62    /// #
63    /// # fn run_test() -> QueryResult<()> {
64    /// #     use schema::users::dsl::*;
65    /// #     let conn = establish_connection();
66    /// conn.transaction::<_, Error, _>(|| {
67    ///     diesel::insert_into(users)
68    ///         .values(name.eq("Ruby"))
69    ///         .execute(&conn)?;
70    ///
71    ///     let all_names = users.select(name).load::<String>(&conn)?;
72    ///     assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names);
73    ///
74    ///     Ok(())
75    /// })?;
76    ///
77    /// conn.transaction::<(), _, _>(|| {
78    ///     diesel::insert_into(users)
79    ///         .values(name.eq("Pascal"))
80    ///         .execute(&conn)?;
81    ///
82    ///     let all_names = users.select(name).load::<String>(&conn)?;
83    ///     assert_eq!(vec!["Sean", "Tess", "Ruby", "Pascal"], all_names);
84    ///
85    ///     // If we want to roll back the transaction, but don't have an
86    ///     // actual error to return, we can return `RollbackTransaction`.
87    ///     Err(Error::RollbackTransaction)
88    /// });
89    ///
90    /// let all_names = users.select(name).load::<String>(&conn)?;
91    /// assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names);
92    /// #     Ok(())
93    /// # }
94    /// ```
95    fn transaction<T, E, F>(&self, f: F) -> Result<T, E>
96    where
97        F: FnOnce() -> Result<T, E>,
98        E: From<Error>,
99    {
100        let transaction_manager = self.transaction_manager();
101        transaction_manager.begin_transaction(self)?;
102        match f() {
103            Ok(value) => {
104                transaction_manager.commit_transaction(self)?;
105                Ok(value)
106            }
107            Err(e) => {
108                transaction_manager.rollback_transaction(self)?;
109                Err(e)
110            }
111        }
112    }
113
114    /// Creates a transaction that will never be committed. This is useful for
115    /// tests. Panics if called while inside of a transaction.
116    fn begin_test_transaction(&self) -> QueryResult<()> {
117        let transaction_manager = self.transaction_manager();
118        assert_eq!(transaction_manager.get_transaction_depth(), 0);
119        transaction_manager.begin_transaction(self)
120    }
121
122    /// Executes the given function inside a transaction, but does not commit
123    /// it. Panics if the given function returns an error.
124    ///
125    /// # Example
126    ///
127    /// ```rust
128    /// # #[macro_use] extern crate diesel;
129    /// # include!("../doctest_setup.rs");
130    /// use diesel::result::Error;
131    ///
132    /// # fn main() {
133    /// #     run_test().unwrap();
134    /// # }
135    /// #
136    /// # fn run_test() -> QueryResult<()> {
137    /// #     use schema::users::dsl::*;
138    /// #     let conn = establish_connection();
139    /// conn.test_transaction::<_, Error, _>(|| {
140    ///     diesel::insert_into(users)
141    ///         .values(name.eq("Ruby"))
142    ///         .execute(&conn)?;
143    ///
144    ///     let all_names = users.select(name).load::<String>(&conn)?;
145    ///     assert_eq!(vec!["Sean", "Tess", "Ruby"], all_names);
146    ///
147    ///     Ok(())
148    /// });
149    ///
150    /// // Even though we returned `Ok`, the transaction wasn't committed.
151    /// let all_names = users.select(name).load::<String>(&conn)?;
152    /// assert_eq!(vec!["Sean", "Tess"], all_names);
153    /// #     Ok(())
154    /// # }
155    /// ```
156    fn test_transaction<T, E, F>(&self, f: F) -> T
157    where
158        F: FnOnce() -> Result<T, E>,
159        E: Debug,
160    {
161        let mut user_result = None;
162        let _ = self.transaction::<(), _, _>(|| {
163            user_result = f().ok();
164            Err(Error::RollbackTransaction)
165        });
166        user_result.expect("Transaction did not succeed")
167    }
168
169    #[doc(hidden)]
170    fn execute(&self, query: &str) -> QueryResult<usize>;
171
172    #[doc(hidden)]
173    fn query_by_index<T, U>(&self, source: T) -> QueryResult<Vec<U>>
174    where
175        T: AsQuery,
176        T::Query: QueryFragment<Self::Backend> + QueryId,
177        Self::Backend: HasSqlType<T::SqlType>,
178        U: Queryable<T::SqlType, Self::Backend>;
179
180    #[doc(hidden)]
181    fn query_by_name<T, U>(&self, source: &T) -> QueryResult<Vec<U>>
182    where
183        T: QueryFragment<Self::Backend> + QueryId,
184        U: QueryableByName<Self::Backend>;
185
186    #[doc(hidden)]
187    fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize>
188    where
189        T: QueryFragment<Self::Backend> + QueryId;
190
191    #[doc(hidden)]
192    fn transaction_manager(&self) -> &Self::TransactionManager;
193}