Function with_connection_string

Source
pub async fn with_connection_string<B, F, R, E>(
    backend: B,
    connection_string: &str,
    operation: F,
) -> Result<R, <B as DatabaseBackend>::Error>
where B: DatabaseBackend, F: FnOnce(&<B as DatabaseBackend>::Connection) -> Pin<Box<dyn Future<Output = Result<R, E>> + Send>> + Send, E: Error + Send + Sync + 'static, <B as DatabaseBackend>::Error: From<E>,
Expand description

Execute a function with a newly created connection using a connection string

This function creates a connection to the database using the provided connection string and backend, then executes the operation with that connection. The connection is automatically closed when the operation completes.

This is the most efficient way to perform a one-off database operation without the overhead of creating and managing a connection pool.

ยงExample

use testkit_core::{with_connection_string, DatabaseBackend, boxed_async};
use std::fmt::{Display, Formatter};

// Define a custom error type for our example
#[derive(Debug)]
struct ExampleError(String);

impl std::error::Error for ExampleError {}

impl Display for ExampleError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

async fn example<B: DatabaseBackend>(backend: B, connection_string: &str) -> Result<(), B::Error>
where B::Error: From<ExampleError> {
    with_connection_string(backend, connection_string, |conn| boxed_async!(async move {
        // Perform operations with the connection
        Ok::<(), ExampleError>(())
    })).await
}