Trait diesel::connection::Connection
[−]
[src]
pub trait Connection: SimpleConnection + Sized + Send { type Backend: Backend; fn establish(database_url: &str) -> ConnectionResult<Self>; fn transaction<T, E, F>(&self, f: F) -> Result<T, E>
where
F: FnOnce() -> Result<T, E>,
E: From<Error>, { ... } fn begin_test_transaction(&self) -> QueryResult<()> { ... } fn test_transaction<T, E, F>(&self, f: F) -> T
where
F: FnOnce() -> Result<T, E>, { ... } }
Perform connections to a backend.
Associated Types
Required Methods
fn establish(database_url: &str) -> ConnectionResult<Self>
Establishes a new connection to the database at the given URL. The URL should be a valid connection string for a given backend. See the documentation for the specific backend for specifics.
Provided Methods
fn transaction<T, E, F>(&self, f: F) -> Result<T, E> where
F: FnOnce() -> Result<T, E>,
E: From<Error>,
F: FnOnce() -> Result<T, E>,
E: From<Error>,
Executes the given function inside of a database transaction. When a transaction is already occurring, savepoints will be used to emulate a nested transaction.
The error returned from the function must implement
From<diesel::result::Error>
.
Examples:
use diesel::result::Error; fn main() { let conn = establish_connection(); let _ = conn.transaction::<_, Error, _>(|| { let new_user = NewUser { name: "Ruby".into() }; diesel::insert(&new_user).into(users::table).execute(&conn)?; assert_eq!(users::table.load::<User>(&conn), Ok(vec![ User { id: 1, name: "Sean".into() }, User { id: 2, name: "Tess".into() }, User { id: 3, name: "Ruby".into() }, ])); Ok(()) }); let _ = conn.transaction::<(), Error, _>(|| { let new_user = NewUser { name: "Pascal".into() }; diesel::insert(&new_user).into(users::table).execute(&conn)?; assert_eq!(users::table.load::<User>(&conn), Ok(vec![ User { id: 1, name: "Sean".into() }, User { id: 2, name: "Tess".into() }, User { id: 3, name: "Ruby".into() }, User { id: 4, name: "Pascal".into() }, ])); Err(Error::RollbackTransaction) // Oh noeees, something bad happened :( }); assert_eq!(users::table.load::<User>(&conn), Ok(vec![ User { id: 1, name: "Sean".into() }, User { id: 2, name: "Tess".into() }, User { id: 3, name: "Ruby".into() }, ])); }
fn begin_test_transaction(&self) -> QueryResult<()>
Creates a transaction that will never be committed. This is useful for tests. Panics if called while inside of a transaction.
fn test_transaction<T, E, F>(&self, f: F) -> T where
F: FnOnce() -> Result<T, E>,
F: FnOnce() -> Result<T, E>,
Executes the given function inside a transaction, but does not commit
it. Panics if the given function returns an Err
.
Implementors
impl Connection for PgConnection type Backend = Pg; type TransactionManager = AnsiTransactionManager;