### Deadpool with Custom Setup Example Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Demonstrates setting up a Diesel Async connection pool with Deadpool, including custom connection setup logic and verified recycling. This example configures session parameters like application_name and statement_timeout. ```rust use diesel_async::pooled_connection::{ AsyncDieselConnectionManager, ManagerConfig, RecyclingMethod, }; use diesel_async::pooled_connection::deadpool::Pool; use diesel_async::{AsyncPgConnection, RunQueryDsl}; use futures_util::FutureExt; #[tokio::main] async fn main() -> Result<(), Box> { // Configure the manager with custom setup and verified recycling let config = ManagerConfig { recycling_method: RecyclingMethod::Verified, custom_setup: Box::new(|url| { async move { let mut conn = AsyncPgConnection::establish(url).await?; // Set session parameters conn.batch_execute( "SET application_name = 'my_app'; SET statement_timeout = '30s';" ) .await?; Ok(conn) } .boxed() }), }; let manager = AsyncDieselConnectionManager::::new_with_config( "postgresql://localhost/mydb", config, ); // Create the pool let pool = Pool::builder(manager) .max_size(10) .build()?; // Use a connection from the pool let mut conn = pool.get().await?; // Execute queries let result = diesel::select(1_i32) .get_result::(&mut conn) .await?; println!("Result: {}", result); Ok(()) } ``` -------------------------------- ### Deadpool with Custom Setup Example Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md A complete example demonstrating how to set up a Deadpool pool with custom connection configuration, including verified recycling and session parameter setup. ```APIDOC ## Complete Example: Deadpool with Custom Setup ```rust use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::pooled_connection::deadpool::Pool; use diesel_async::{AsyncPgConnection, RunQueryDsl}; use diesel_async::pooled_connection::{ManagerConfig, RecyclingMethod}; use futures_util::FutureExt; #[tokio::main] async fn main() -> Result<(), Box> { // Configure the manager with custom setup and verified recycling let config = ManagerConfig { recycling_method: RecyclingMethod::Verified, custom_setup: Box::new(|url| { async move { let mut conn = AsyncPgConnection::establish(url).await?; // Set session parameters conn.batch_execute( "SET application_name = 'my_app'; SET statement_timeout = '30s';" ) .await?; Ok(conn) } .boxed() }), }; let manager = AsyncDieselConnectionManager::::new_with_config( "postgresql://localhost/mydb", config, ); // Create the pool let pool = Pool::builder(manager) .max_size(10) .build()?; // Use a connection from the pool let mut conn = pool.get().await?; // Execute queries let result = diesel::select(1_i32) .get_result::(&mut conn) .await?; println!("Result: {}", result); Ok(()) } ``` ``` -------------------------------- ### Example SQL Migration - Up Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-migrations.md This is an example of an `up.sql` file for a Diesel migration, creating a `users` table. ```sql CREATE TABLE users ( id SERIAL PRIMARY KEY, name VARCHAR NOT NULL, email VARCHAR UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ``` -------------------------------- ### Custom Async Connection Setup Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/INDEX.md Details how to configure a custom setup routine for new connections managed by `AsyncDieselConnectionManager`. ```rust use diesel_async::pooled_connection::{ AsyncDieselConnectionManager, ManagerConfig }; let config = ManagerConfig { recycling_method: Default::default(), custom_setup: Box::new(|url| { async move { let mut conn = AsyncPgConnection::establish(url).await?; conn.batch_execute("SET app_name = 'myapp'").await?; Ok(conn) } .boxed() }), }; let manager = AsyncDieselConnectionManager::new_with_config(url, config); ``` -------------------------------- ### Example SQL Migration - Down Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-migrations.md This is an example of a `down.sql` file for a Diesel migration, dropping the `users` table. ```sql DROP TABLE users; ``` -------------------------------- ### Custom Connection Setup with Diesel Async Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Execute custom setup logic on each new connection. This includes setting application name, search path, and statement timeout for PostgreSQL connections. ```rust use diesel_async::pooled_connection::ManagerConfig; use futures_util::FutureExt; let config = ManagerConfig { recycling_method: Default::default(), custom_setup: Box::new(|url| { async move { let mut conn = AsyncPgConnection::establish(url).await?; // Set application name conn.batch_execute("SET application_name = 'my_app'") .await?; // Set default search path conn.batch_execute("SET search_path = 'public'") .await?; // Configure statement timeout conn.batch_execute("SET statement_timeout = '30s'") .await?; Ok(conn) } .boxed() }), }; let manager = AsyncDieselConnectionManager::::new_with_config( "postgresql://localhost/db", config, ); ``` -------------------------------- ### Diesel Async first Query Example Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-run-query-dsl.md An example demonstrating how to use the `first` method to retrieve the first user from a query, ordered by ID. It requires awaiting the future and handling potential errors. ```rust let first_user: User = users::table .order_by(users::id) .first::(&mut conn) .await?; ``` -------------------------------- ### Recommended Minimal Setup (PostgreSQL) Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Configure your project for PostgreSQL support with diesel and diesel-async. Ensure tokio is also included with the 'full' feature. ```toml [dependencies] diesel = { version = "2.3", features = ["postgres"] } diesel_async = { version = "0.9", features = ["postgres"] } tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Run Pending Async Migrations Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/INDEX.md Provides an example of how to set up and run pending database migrations asynchronously. ```rust use diesel_async::AsyncMigrationHarness; use diesel_migrations::FileBasedMigrations; let conn = AsyncPgConnection::establish(&url).await?; let migrations = FileBasedMigrations::find_migrations_directory()?; let mut harness = AsyncMigrationHarness::new(conn); harness.run_pending_migrations(migrations)?; ``` -------------------------------- ### Recommended Minimal Setup (SQLite) Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Configure your project for SQLite support with diesel and diesel-async. Ensure tokio is also included with the 'full' feature. ```toml [dependencies] diesel = { version = "2.3", features = ["sqlite"] } diesel_async = { version = "0.9", features = ["sqlite"] } tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### SQLite Configuration Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/README.md Example of configuring Diesel Async for SQLite. ```toml diesel_async = { version = "0.9", features = ["sqlite"] } ``` -------------------------------- ### Recommended Minimal Setup (MySQL) Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Configure your project for MySQL/MariaDB support with diesel and diesel-async. Ensure tokio is also included with the 'full' feature. ```toml [dependencies] diesel = { version = "2.3", features = ["mysql"] } diesel_async = { version = "0.9", features = ["mysql"] } tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### SetupCallback Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Custom connection setup function type that allows custom initialization of connections beyond the standard AsyncConnection::establish. ```APIDOC ## SetupCallback Custom connection setup function type. ```rust pub type SetupCallback = Box BoxFuture> + Send + Sync>; ``` Allows custom initialization of connections beyond the standard `AsyncConnection::establish`. **Example:** ```rust use diesel_async::pooled_connection::ManagerConfig; use diesel_async::AsyncPgConnection; use futures_util::FutureExt; let config = ManagerConfig { recycling_method: Default::default(), custom_setup: Box::new(|url| { async move { let mut conn = AsyncPgConnection::establish(url).await?; // Custom setup: set application name conn.batch_execute("SET application_name = 'my_app'") .await?; Ok(conn) } .boxed() }), }; ``` ``` -------------------------------- ### All Backends and Pool Implementations Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/README.md Example of configuring Diesel Async to support all backends and pooling implementations, including migrations. ```toml diesel_async = { version = "0.9", features = [ "postgres", "mysql", "sqlite", "deadpool", "bb8", "mobc", "r2d2", "migrations" ] } ``` -------------------------------- ### MySQL with Migrations Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/README.md Example of configuring Diesel Async for MySQL with migration support. ```toml diesel_async = { version = "0.9", features = ["mysql", "migrations"] } ``` -------------------------------- ### Custom Connection Setup Callback Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Defines a type alias for a custom connection setup function. This allows for advanced initialization logic beyond the standard `establish` method, such as setting application names or performing other pre-connection tasks. ```rust pub type SetupCallback = Box BoxFuture> + Send + Sync>; ``` ```rust use diesel_async::pooled_connection::ManagerConfig; use diesel_async::AsyncPgConnection; use futures_util::FutureExt; let config = ManagerConfig { recycling_method: Default::default(), custom_setup: Box::new(|url| { async move { let mut conn = AsyncPgConnection::establish(url).await?; // Custom setup: set application name conn.batch_execute("SET application_name = 'my_app'") .await?; Ok(conn) } .boxed() }), }; ``` -------------------------------- ### Invalid Tokio Runtime Setup for Migrations Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-migrations.md This setup will panic because it uses a `current_thread` Tokio runtime, which is incompatible with the migration harness. ```rust // ❌ WILL PANIC - current_thread runtime #[tokio::main(flavor = "current_thread")] async fn main() { let harness = AsyncMigrationHarness::new(conn); harness.run_pending_migrations(migrations)?; // Panic! } ``` -------------------------------- ### Full Setup (All Backends + Deadpool) Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Enable support for PostgreSQL, MySQL, and SQLite backends, along with the deadpool connection pool and migrations. Tokio is included with the 'full' feature. ```toml [dependencies] diesel = { version = "2.3", features = ["postgres", "mysql", "sqlite"] } diesel_async = { version = "0.9", features = [ "postgres", "mysql", "sqlite", "deadpool", "migrations" ] } tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Mobc Pool Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Example of setting up and using a Mobc pool with diesel_async. ```APIDOC ## Mobc **Source:** `src/pooled_connection/mobc.rs` ```rust use diesel_async::pooled_connection::mobc::Pool; use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::AsyncPgConnection; let config = AsyncDieselConnectionManager::::new(database_url); let pool = Pool::new(config); let mut conn = pool.get().await?; ``` **Type Aliases:** | Type | Source | |------|--------| | `Pool` | `mobc::Pool>` | | `PoolError` | `mobc::Error` | ``` -------------------------------- ### PostgreSQL with Pooling Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/README.md Example of configuring Diesel Async for PostgreSQL with the deadpool pooling implementation. ```toml diesel_async = { version = "0.9", features = ["postgres", "deadpool"] } ``` -------------------------------- ### Async SQLite Connection Example Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-wrappers.md Demonstrates establishing an asynchronous SQLite connection using `SyncConnectionWrapper` and executing a simple query asynchronously. Requires the `tokio` runtime. ```rust use diesel::prelude::*; use diesel::sqlite::SqliteConnection; use diesel_async::{AsyncConnection, RunQueryDsl}; use diesel_async::sync_connection_wrapper::SyncConnectionWrapper; #[tokio::main] async fn main() -> Result<(), Box> { let mut conn = SyncConnectionWrapper::::establish( "sqlite:///test.db" ).await?; // Use async connection methods let result = diesel::select(42_i32) .get_result::(&mut conn) .await?; println!("Result: {}", result); Ok(()) } ``` -------------------------------- ### Deadpool Pool Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Example of setting up and using a Deadpool pool with diesel_async. ```APIDOC ## Deadpool **Source:** `src/pooled_connection/deadpool.rs` ```rust use diesel_async::pooled_connection::deadpool::Pool; use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::AsyncPgConnection; let config = AsyncDieselConnectionManager::::new(database_url); let pool: Pool = Pool::builder(config).build()?; let mut conn = pool.get().await?; ``` **Type Aliases:** | Type | Source | |------|--------| | `Pool` | `deadpool::managed::Pool>` | | `PoolBuilder` | `deadpool::managed::PoolBuilder>` | | `Object` | `deadpool::managed::Object>` | | `PoolError` | `deadpool::managed::PoolError` | ``` -------------------------------- ### Begin Transaction with Custom SQL Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-transactions.md Allows starting a transaction with custom SQL, useful for setting isolation levels. Ensure the connection is not already in a transaction. ```rust pub async fn begin_transaction_sql( conn: &mut Conn, sql: &str, ) -> QueryResult<()> where Conn: AsyncConnection, { // ... implementation details ... } // Example usage: // Use READ COMMITTED isolation level // AnsiTransactionManager::begin_transaction_sql( // &mut conn, // "BEGIN ISOLATION LEVEL READ COMMITTED" // ).await?; ``` -------------------------------- ### CustomQuery Recycling Method Example Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Allows custom validation queries for database-specific checks or extended diagnostics. The provided example uses `SELECT NOW()`. ```rust RecyclingMethod::CustomQuery(Cow::Borrowed("SELECT NOW()")) ``` -------------------------------- ### BB8 Pool Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Example of setting up and using a BB8 pool with diesel_async. ```APIDOC ## BB8 **Source:** `src/pooled_connection/bb8.rs` ```rust use diesel_async::pooled_connection::bb8::Pool; use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::AsyncPgConnection; let config = AsyncDieselConnectionManager::::new(database_url); let pool = Pool::builder().build(config).await?; let mut conn = pool.get().await?; ``` **Type Aliases:** | Type | Source | |------|--------| | `Pool` | `bb8::Pool>` | | `PoolError` | `bb8::RunError` | ``` -------------------------------- ### RecyclingMethod Enum Examples Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/types.md Demonstrates how to instantiate the RecyclingMethod enum for different validation strategies. ```rust use diesel_async::pooled_connection::RecyclingMethod; // Fast validation let method = RecyclingMethod::Fast; // Custom query let method = RecyclingMethod::CustomQuery( std::borrow::Cow::Borrowed("SELECT 1") ); // Custom function let method = RecyclingMethod::CustomFunction(Box::new(|conn| { Box::pin(async move { Ok(()) }) })); ``` -------------------------------- ### Establish File-based SQLite Connection with SyncConnectionWrapper Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Configure a file-based SQLite database connection using SyncConnectionWrapper. This example demonstrates establishing a connection to a persistent SQLite file. ```rust use diesel::sqlite::SqliteConnection; use diesel_async::sync_connection_wrapper::SyncConnectionWrapper; // File-based SQLite let mut conn = SyncConnectionWrapper::::establish( "sqlite:///path/to/mydb.sqlite" ).await?; ``` -------------------------------- ### PoolError Enum Example Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/types.md Shows how to handle PoolError variants using a match statement to differentiate between connection and query errors. ```rust use diesel_async::pooled_connection::PoolError; match pool_error { PoolError::ConnectionError(e) => { eprintln!("Connection failed: {}", e); } PoolError::QueryError(e) => { eprintln!("Query failed: {}", e); } } ``` -------------------------------- ### Async MySQL Connection Setup Queries Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-connections.md These SQL queries are automatically executed upon establishing an AsyncMysqlConnection to ensure proper UTF-8 encoding and consistent timezone handling. ```sql SET time_zone = '+00:00'; SET character_set_client = 'utf8mb4'; SET character_set_connection = 'utf8mb4'; SET character_set_results = 'utf8mb4'; ``` -------------------------------- ### Handle MySQL Authentication Failure Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/errors.md Example of attempting to establish a MySQL connection with incorrect credentials and handling the resulting authentication error. ```rust match AsyncMysqlConnection::establish("mysql://root:wrong@localhost/db").await { Ok(conn) => println!("Connected!"), Err(e) => eprintln!("Authentication failed: {}", e), } ``` -------------------------------- ### Correct Tokio Runtime Setup for Migrations Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-migrations.md This demonstrates two correct ways to set up the Tokio runtime for Diesel's asynchronous migrations: using the default multithreaded runtime or using `spawn_blocking`. ```rust // ✅ Works - multithreaded runtime #[tokio::main] async fn main() { let harness = AsyncMigrationHarness::new(conn); harness.run_pending_migrations(migrations)?; } ``` ```rust // ✅ Alternative - spawn_blocking #[tokio::main(flavor = "current_thread")] async fn main() { tokio::task::spawn_blocking(|| { let harness = AsyncMigrationHarness::new(conn); harness.run_pending_migrations(migrations)?; }).await?; } ``` -------------------------------- ### Get Connection String from Environment Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Retrieve the database connection string from the DATABASE_URL environment variable. Panics if the variable is not set. ```rust use std::env; // Get connection string from environment let database_url = env::var("DATABASE_URL") .expect("DATABASE_URL must be set"); let conn = AsyncPgConnection::establish(&database_url).await?; ``` -------------------------------- ### Connection String with SSL Mode Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Example of a PostgreSQL connection string that specifies SSL mode to be required. ```plaintext postgresql://localhost/db?sslmode=require ``` -------------------------------- ### Deadpool Connection Pooling Setup Source: https://github.com/diesel-rs/diesel_async/blob/main/README.md Configures and builds a connection pool using Deadpool for managing asynchronous PostgreSQL connections. Requires the `deadpool` feature for `diesel-async`. ```rust use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::pooled_connection::deadpool::Pool; use diesel_async::RunQueryDsl; // create a new connection pool with the default config let config = AsyncDieselConnectionManager::::new(std::env::var("DATABASE_URL")?); let pool = Pool::builder(config).build()?; // checkout a connection from the pool let mut conn = pool.get().await?; // use the connection as ordinary diesel-async connection let res = users::table.select(User::as_select()).load::(&mut conn).await?; ``` -------------------------------- ### Create AsyncDieselConnectionManager with Custom Config Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Instantiate AsyncDieselConnectionManager with a custom configuration, allowing for specific recycling methods and connection setup logic. ```rust use diesel_async::pooled_connection::{AsyncDieselConnectionManager, ManagerConfig, RecyclingMethod}; let config = ManagerConfig { recycling_method: RecyclingMethod::Verified, custom_setup: Box::new(|url| AsyncPgConnection::establish(url).boxed()), }; let manager = AsyncDieselConnectionManager::::new_with_config( "postgresql://localhost/db", config, ); ``` -------------------------------- ### BB8 Connection Pooling Setup Source: https://github.com/diesel-rs/diesel_async/blob/main/README.md Configures and builds a connection pool using BB8 for managing asynchronous PostgreSQL connections. Requires the `bb8` feature for `diesel-async`. ```rust use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::pooled_connection::bb8::Pool; use diesel_async::RunQueryDsl; // create a new connection pool with the default config let config = AsyncDieselConnectionManager::::new(std::env::var("DATABASE_URL")?); let pool = Pool::builder().build(config).await?; // checkout a connection from the pool let mut conn = pool.get().await?; // use the connection as ordinary diesel-async connection let res = users::table.select(User::as_select()).load::(&mut conn).await?; ``` -------------------------------- ### PostgreSQL with Connection Pool (Deadpool) Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Configure diesel-async for PostgreSQL with the deadpool connection pool. This setup combines database support with pooling capabilities. ```toml [dependencies] diesel = { version = "2.3", features = ["postgres"] } diesel_async = { version = "0.9", features = ["postgres", "deadpool"] } ``` -------------------------------- ### Begin a Test Transaction (Rollback on Drop) Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-async-connection.md Starts a transaction that is automatically rolled back when the connection is dropped. This is useful for tests to ensure a clean state. Panics if already in a transaction or if the connection is broken. ```rust #[tokio::test] async fn test_query() { let mut conn = establish_connection().await; conn.begin_test_transaction().await.unwrap(); // All database modifications in this test are automatically rolled back } ``` -------------------------------- ### Track Connection Events with Custom Instrumentation Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Implement the `Instrumentation` trait to log connection events like query start and finish. This requires defining a custom struct and implementing the `on_connection_event` method. The instrumentation is then set on an established `AsyncPgConnection`. ```rust use diesel::connection::Instrumentation; use diesel_async::AsyncConnection; struct MyInstrumentation; impl Instrumentation for MyInstrumentation { fn on_connection_event(&mut self, event: InstrumentationEvent) { match event { InstrumentationEvent::StartQuery { .. } => { println!("Query started"); } InstrumentationEvent::FinishQuery { .. } => { println!("Query finished"); } _ => {} } } } let mut conn = AsyncPgConnection::establish(&database_url).await?; conn.set_instrumentation(MyInstrumentation); ``` -------------------------------- ### SetupCallback Type Alias Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/types.md Defines a custom connection setup function for pool managers. It takes a connection URL string and returns a boxed future that resolves to a connection result. This is used for custom initialization beyond standard connection establishment. ```rust pub type SetupCallback = Box BoxFuture> + Send + Sync>; ``` -------------------------------- ### Execute Nested Transactions with Savepoints Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-transactions.md This example shows how to implement nested transactions using savepoints. An inner transaction that returns an error will roll back to its savepoint, allowing the outer transaction to continue. ```rust conn.transaction::<_, Error, _>(async |conn| { // Outer transaction (depth = 1) diesel::insert_into(users) .values(name.eq("Bob")) .execute(conn) .await?; // Nested transaction (depth = 2, uses SAVEPOINT) match conn.transaction::<_, Error, _>(async |conn| { diesel::insert_into(users) .values(name.eq("Charlie")) .execute(conn) .await?; Err(Error::RollbackTransaction) }).await { Err(Error::RollbackTransaction) => { // Savepoint was rolled back, but outer transaction continues } _ => {} } Ok(()) }).await?; ``` -------------------------------- ### Start a Test Transaction Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-transactions.md Starts a transaction that will automatically be rolled back when the test function ends. Use this to isolate test database changes. ```rust #[tokio::test] async fn test_insert() { let mut conn = establish_connection().await; conn.begin_test_transaction().await.unwrap(); // All changes automatically rolled back when test ends diesel::insert_into(users) .values(name.eq("Test User")) .execute(&mut conn) .await .unwrap(); } ``` -------------------------------- ### Basic Async Query with Diesel Async Source: https://github.com/diesel-rs/diesel_async/blob/main/README.md Demonstrates setting up an async connection and executing a standard Diesel query using the async DSL. Ensure your `DATABASE_URL` environment variable is set. ```rust use diesel::prelude::*; use diesel_async::{RunQueryDsl, AsyncConnection, AsyncPgConnection}; // ordinary diesel model setup table! { users { id -> Integer, name -> Text, } } #[derive(Queryable, Selectable)] #[diesel(table_name = users)] struct User { id: i32, name: String, } // create an async connection let mut connection = AsyncPgConnection::establish(&std::env::var("DATABASE_URL")?).await?; // use ordinary diesel query dsl to construct your query let data: Vec = users::table .filter(users::id.gt(0)) .or_filter(users::name.like("%Luke")) .select(User::as_select()) // execute the query via the provided // async `diesel_async::RunQueryDsl` .load(&mut connection) .await?; ``` -------------------------------- ### Execute Basic Async Query Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/INDEX.md Demonstrates how to establish an asynchronous connection and execute a simple count query. ```rust use diesel_async::{AsyncConnection, RunQueryDsl}; let mut conn = AsyncPgConnection::establish(&url).await?; // Execute a query let count = users::table .filter(users::age.gt(18)) .count() .get_result::(&mut conn) .await?; ``` -------------------------------- ### from Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-wrappers.md Creates a wrapper from an existing async connection. This is a convenient way to adapt an already established async connection for synchronous use. ```APIDOC ## from ### Description Creates a wrapper from an existing async connection. ### Method `from` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Example ```rust let async_conn = AsyncPgConnection::establish(&url).await?; let sync_conn = AsyncConnectionWrapper::from(async_conn); ``` ``` -------------------------------- ### ManagerConfig Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/types.md Configuration options for connection managers, including recycling strategies and custom setup callbacks. ```APIDOC ## Struct: ManagerConfig Configuration for connection managers. ### Generic Parameters - `C`: Async connection type ### Fields - `recycling_method` (RecyclingMethod): Connection validation strategy. - `custom_setup` (SetupCallback): Custom setup function. ``` -------------------------------- ### Configure PostgreSQL with TLS using tokio-postgres-rustls Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Set up a PostgreSQL connection with TLS using the `tokio-postgres-rustls` crate. This involves parsing a connection string into a `Config` object, creating a `MakeRustlsConnect` instance with a default `rustls::ClientConfig`, and then establishing the connection. ```rust use tokio_postgres_rustls::MakeRustlsConnect; use tokio_postgres::Config; let config: Config = "postgresql://localhost/db".parse()?; let tls = MakeRustlsConnect::new(rustls::ClientConfig::default()); let (client, connection) = config.connect(tls).await?; let async_conn = AsyncPgConnection::try_from_client_and_connection( client, connection )?; ``` -------------------------------- ### AlreadyInTransaction Error Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/errors.md This error occurs when attempting to start a new transaction while one is already active. ```APIDOC ## AlreadyInTransaction ### Description This error is raised when `begin_transaction()` or `begin_test_transaction()` is called while a transaction is already in progress. ### Trigger Conditions - Call `begin_transaction()` when already in a transaction - Call `begin_test_transaction()` when already in a transaction ### Location `AnsiTransactionManager::begin_transaction_sql()` (src:216) ### Code Example ```rust use diesel::result::Error; use diesel_async::AsyncConnection; match conn.transaction::<_, Error, _>(async |conn| { // Try to begin another transaction conn.transaction::<_, Error, _>(async |_| { Ok(()) }).await }).await { Err(Error::AlreadyInTransaction) => { println!("Cannot nest explicit begin_transaction calls") } _ => {} } ``` ``` -------------------------------- ### Set Up Async Connection Pool Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/README.md Configures and builds an asynchronous connection pool using `AsyncDieselConnectionManager`. The `max_size` parameter controls the maximum number of connections in the pool. ```rust let manager = AsyncDieselConnectionManager::::new(url); let pool = Pool::builder(manager).max_size(10).build()?; let mut conn = pool.get().await?; ``` -------------------------------- ### establish Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-wrappers.md Opens a new async connection and wraps it for synchronous use. It takes a database URL and returns a Result containing the wrapped connection or an error. ```APIDOC ## establish ### Description Opens a new async connection and wraps it for sync use. ### Method `establish` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **database_url** (&str) - Yes - Async connection URL ### Returns `ConnectionResult>` - Wrapped connection or error. ### Example ```rust use diesel_async::AsyncPgConnection; use diesel_async::async_connection_wrapper::AsyncConnectionWrapper; let mut conn = AsyncConnectionWrapper::::establish( "postgresql://localhost/db" )?; ``` ``` -------------------------------- ### ManagerConfig Structure Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Defines the configuration for connection managers, including the recycling method and a custom setup callback. ```rust pub struct ManagerConfig { pub recycling_method: RecyclingMethod, pub custom_setup: SetupCallback, } ``` -------------------------------- ### Async Connection Pooling with Deadpool Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/INDEX.md Illustrates setting up an asynchronous connection pool using Deadpool for managing database connections. ```rust use diesel_async::pooled_connection::{ AsyncDieselConnectionManager, deadpool::Pool }; let manager = AsyncDieselConnectionManager::::new(url); let pool = Pool::builder(manager).max_size(10).build()?; let mut conn = pool.get().await?; ``` -------------------------------- ### BlockOn Trait Definition Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-wrappers.md Defines the `BlockOn` trait for custom future execution and a method to get a runtime instance. ```rust pub trait BlockOn { fn block_on(&self, f: F) -> F::Output where F: Future; fn get_runtime() -> Self; } ``` -------------------------------- ### Create and Use Mobc Pool with Diesel-Async Source: https://github.com/diesel-rs/diesel_async/blob/main/README.md Demonstrates how to set up an AsyncDieselConnectionManager with Mobc and checkout a connection for query execution. Ensure the DATABASE_URL environment variable is set. ```rust use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::pooled_connection::mobc::Pool; use diesel_async::RunQueryDsl; // create a new connection pool with the default config let config = AsyncDieselConnectionManager::::new(std::env::var("DATABASE_URL")?); let pool = Pool::new(config); // checkout a connection from the pool let mut conn = pool.get().await?; // use the connection as ordinary diesel-async connection let res = users::table.select(User::as_select()).load::(&mut conn).await?; ``` -------------------------------- ### Handle Invalid PostgreSQL Connection Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/errors.md Example of attempting to establish a PostgreSQL connection with an invalid host and handling the potential ConnectionError. ```rust use diesel_async::AsyncPgConnection; match AsyncPgConnection::establish("postgresql://invalid_host/db").await { Ok(conn) => println!("Connected!"), Err(e) => eprintln!("Connection failed: {}", e), } ``` -------------------------------- ### Establish Async Database Connection Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-async-connection.md Use this to create and open a new asynchronous database connection. The URL format depends on the specific database backend (e.g., PostgreSQL, MySQL, SQLite). ```rust use diesel_async::{AsyncConnection, AsyncPgConnection}; let mut conn = AsyncPgConnection::establish("postgresql://user:pass@localhost/dbname") .await?; ``` -------------------------------- ### ManagerConfig Struct Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/types.md Configuration options for connection managers. Allows specifying connection recycling strategy and custom setup functions. ```rust pub struct ManagerConfig { pub recycling_method: RecyclingMethod, pub custom_setup: SetupCallback, } ``` -------------------------------- ### Establish Async Connection Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/README.md Establishes an asynchronous connection to a PostgreSQL database. Ensure the database URL is correctly formatted. ```rust let mut conn = AsyncPgConnection::establish("postgresql://localhost/db").await?; ``` -------------------------------- ### CustomQuery Recycling Method Usage Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md An example of using `CustomQuery` with a specific SQL statement to validate connection. Useful for database-specific checks. ```rust RecyclingMethod::CustomQuery( Cow::Borrowed("SELECT 1 FROM pg_tables LIMIT 1") ) ``` -------------------------------- ### Establish AsyncPgConnection from Environment Variable Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Use this snippet to establish an asynchronous PostgreSQL connection using a URL from the DATABASE_URL environment variable. Ensure the DATABASE_URL is set before execution. ```rust use std::env; use diesel_async::AsyncPgConnection; let database_url = env::var("DATABASE_URL") .expect("DATABASE_URL not set"); let conn = AsyncPgConnection::establish(&database_url).await?; ``` -------------------------------- ### Custom SpawnBlocking Implementation Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-connections.md Example of implementing the SpawnBlocking trait to customize how blocking tasks are spawned for SyncConnectionWrapper. This allows for custom runtime integration. ```rust use diesel_async::sync_connection_wrapper::{SyncConnectionWrapper, SpawnBlocking}; struct CustomRuntime; impl SpawnBlocking for CustomRuntime { fn spawn_blocking<'a, R>( &mut self, task: impl FnOnce() -> R + Send + 'static, ) -> BoxFuture<'a, Result>> where R: Send + 'static, { // Custom implementation Box::pin(async move { Ok(task()) }) } fn get_runtime() -> Self { CustomRuntime } } ``` -------------------------------- ### establish Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-async-connection.md Establishes a new asynchronous connection to the database using a connection URL. ```APIDOC ## establish ### Description Establishes a new connection to the database. ### Method `establish` ### Signature ```rust pub fn establish(database_url: &str) -> impl Future> + Send ``` ### Parameters #### Path Parameters - **database_url** (string) - Required - Database connection URL in backend-specific format ### Returns `ConnectionResult` - A result containing the established connection or a connection error. ### Description Creates and opens a new database connection using the provided connection string. The URL format varies by backend (PostgreSQL, MySQL, SQLite). This is typically the first step when using diesel-async. ### Example ```rust use diesel_async::{AsyncConnection, AsyncPgConnection}; let mut conn = AsyncPgConnection::establish("postgresql://user:pass@localhost/dbname") .await?; ``` ``` -------------------------------- ### PostgreSQL with Connection Pool (BB8) Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Configure diesel-async for PostgreSQL with the bb8 connection pool. This setup combines database support with pooling capabilities. ```toml [dependencies] diesel = { version = "2.3", features = ["postgres"] } diesel_async = { version = "0.9", features = ["postgres", "bb8"] } ``` -------------------------------- ### Establish Async Connection with SyncConnectionWrapper Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-wrappers.md Opens a new synchronous database connection and wraps it for asynchronous use. Requires the 'sync-connection-wrapper' feature. ```rust use diesel::sqlite::SqliteConnection; use diesel_async::sync_connection_wrapper::SyncConnectionWrapper; let mut conn = SyncConnectionWrapper::::establish( "sqlite:///path/to/db.sqlite" ).await?; ``` -------------------------------- ### Pipelined vs Sequential Query Execution Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-connections.md Demonstrates how to execute multiple queries concurrently using pipelining for improved performance compared to sequential execution. ```rust // Sequential execution let result1 = query1.get_result::(&mut conn).await?; let result2 = query2.get_result::(&mut conn).await?; // Pipelined execution (concurrent polling) let f1 = query1.get_result::(&mut &conn); let f2 = query2.get_result::(&mut &conn); let (r1, r2) = futures_util::try_join!(f1, f2)?; ``` -------------------------------- ### Establish AsyncPgConnection Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-connections.md Establishes an asynchronous connection to a PostgreSQL database using a connection URL. Ensure the URL format is correct and all necessary parameters are provided. ```rust use diesel_async::AsyncPgConnection; let mut conn = AsyncPgConnection::establish("postgresql://user:pass@localhost/mydb") .await?; ``` -------------------------------- ### Run Migrations with AsyncMysqlConnection Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-migrations.md Execute pending database migrations using an asynchronous MySQL connection. This snippet demonstrates the setup for MySQL backend. ```rust use diesel_async::AsyncMysqlConnection; use diesel_async::AsyncMigrationHarness; let connection = AsyncMysqlConnection::establish(&database_url).await?; let migrations = FileBasedMigrations::find_migrations_directory()?; let mut harness = AsyncMigrationHarness::new(connection); harness.run_pending_migrations(migrations)?; ``` -------------------------------- ### SQLite with Migrations Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/configuration.md Configure diesel-async for SQLite support and enable the migrations feature. The diesel_migrations crate is also required. ```toml [dependencies] diesel = { version = "2.3", features = ["sqlite"] } diesel_async = { version = "0.9", features = ["sqlite", "migrations"] } diesel_migrations = "2.3" ``` -------------------------------- ### begin_transaction Method Signature Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-transactions.md Starts a new transaction or creates a savepoint if already within a transaction. This method increments the transaction depth counter. ```rust async fn begin_transaction(conn: &mut Conn) -> QueryResult <()> ``` -------------------------------- ### Pipelined Queries with Futures (PostgreSQL) Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/INDEX.md Shows how to execute multiple queries concurrently using `try_join!` for pipelining, specifically for PostgreSQL. ```rust let f1 = diesel::select(1_i32).get_result::(&mut &conn); let f2 = diesel::select(2_i32).get_result::(&mut &conn); let (r1, r2) = futures_util::try_join!(f1, f2)?; ``` -------------------------------- ### Handling AlreadyInTransaction Error Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/errors.md Demonstrates how to detect and handle the `Error::AlreadyInTransaction` variant, which occurs when attempting to start a new transaction while one is already active. ```rust use diesel::result::Error; use diesel_async::AsyncConnection; match conn.transaction::<_, Error, _>(async |conn| { // Try to begin another transaction conn.transaction::<_, Error, _>(async |_| { Ok(()) }).await }).await { Err(Error::AlreadyInTransaction) => { println!("Cannot nest explicit begin_transaction calls") } _ => {} } ``` -------------------------------- ### Establish a new AsyncConnectionWrapper Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-wrappers.md Opens a new async connection and wraps it for synchronous use. Requires the database URL as input. ```rust use diesel_async::AsyncPgConnection; use diesel_async::async_connection_wrapper::AsyncConnectionWrapper; let mut conn = AsyncConnectionWrapper::::establish( "postgresql://localhost/db" )?; ``` -------------------------------- ### Create AsyncDieselConnectionManager with Default Config Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Instantiate AsyncDieselConnectionManager using a database connection URL. Uses default configuration for connection pooling. ```rust use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::AsyncPgConnection; let manager = AsyncDieselConnectionManager::::new( "postgresql://user:pass@localhost/db" ); ``` -------------------------------- ### Establish Async MySQL Connection Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-connections.md Connect to a MySQL database asynchronously using a provided database URL. Ensure the URL follows the format: mysql://[user[:password]@]host[:port]/database_name. ```rust use diesel_async::AsyncMysqlConnection; let mut conn = AsyncMysqlConnection::establish("mysql://user:pass@localhost/mydb") .await?; ``` -------------------------------- ### CustomFunction Recycling Method Example Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Provides maximum flexibility for connection validation using a custom asynchronous callback function. The callback receives a mutable connection reference. ```rust RecyclingMethod::CustomFunction(Box::new(|conn| { async move { // Custom validation logic Ok(()) }.boxed() })) ``` -------------------------------- ### AsyncDieselConnectionManager::new_with_config Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Constructs a new AsyncDieselConnectionManager with custom configuration. ```APIDOC ## AsyncDieselConnectionManager::new_with_config ### Description Creates a connection manager with custom configuration. ### Signature ```rust pub fn new_with_config( connection_url: impl Into, manager_config: ManagerConfig, ) -> Self ``` ### Parameters #### Path Parameters - **connection_url** (impl Into) - Required - Database connection URL - **manager_config** (ManagerConfig) - Required - Custom manager configuration ### Returns A new `AsyncDieselConnectionManager` instance with custom config. ### Example ```rust use diesel_async::pooled_connection::{AsyncDieselConnectionManager, ManagerConfig, RecyclingMethod}; let config = ManagerConfig { recycling_method: RecyclingMethod::Verified, custom_setup: Box::new(|url| AsyncPgConnection::establish(url).boxed()), }; let manager = AsyncDieselConnectionManager::::new_with_config( "postgresql://localhost/db", config, ); ``` ``` -------------------------------- ### embed_migrations! Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-migrations.md Compile migrations into the binary. ```APIDOC ## embed_migrations! ### Description Compile migrations into the binary. ### Macro `embed_migrations!` ### Returns `EmbeddedMigrations`: A static `EmbeddedMigrations` instance. ``` -------------------------------- ### Run Pending Migrations with AsyncPgConnection Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-migrations.md Execute pending database migrations using an asynchronous PostgreSQL connection. Ensure the DATABASE_URL environment variable is set. ```rust #[tokio::main] async fn main() -> Result<(), Box> { use diesel_async::AsyncMigrationHarness; use diesel_migrations::FileBasedMigrations; use diesel_async::AsyncPgConnection; let database_url = std::env::var("DATABASE_URL")?; let connection = AsyncPgConnection::establish(&database_url).await?; let migrations = FileBasedMigrations::find_migrations_directory()?; let mut harness = AsyncMigrationHarness::new(connection); harness.run_pending_migrations(migrations)?; let conn = harness.into_inner(); println!("Migrations completed successfully!"); Ok(()) } ``` -------------------------------- ### Running Migrations with AsyncConnectionWrapper Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-wrappers.md Demonstrates how to use `AsyncConnectionWrapper` to run Diesel migrations within a synchronous `main` function. This is useful for CLI tools or applications that need to manage database schema changes synchronously. ```rust use diesel_async::AsyncPgConnection; use diesel_async::async_connection_wrapper::AsyncConnectionWrapper; use diesel_migrations::{FileBasedMigrations, MigrationHarness}; fn main() -> Result<(), Box> { let database_url = std::env::var("DATABASE_URL")?; // Create wrapper (outside async context) let mut conn = AsyncConnectionWrapper::::establish( &database_url )?; // Use with sync diesel-migrations API let migrations = FileBasedMigrations::find_migrations_directory()?; conn.run_pending_migrations(migrations)?; println!("Migrations completed!"); Ok(()) } ``` -------------------------------- ### Pipelining Queries within a Transaction Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-transactions.md Execute multiple queries concurrently within an asynchronous transaction. This example demonstrates running two select statements in parallel and collecting their results. ```rust use diesel_async::RunQueryDsl; use futures_util::try_join; conn.transaction::<_, Error, _>(async |conn| { let f1 = diesel::select(1_i32).get_result::(&mut &conn); let f2 = diesel::select(2_i32).get_result::(&mut &conn); let (r1, r2) = try_join!(f1, f2)?; Ok((r1, r2)) }).await?; ``` -------------------------------- ### AsyncDieselConnectionManager::new Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-pooled-connection.md Constructs a new AsyncDieselConnectionManager with default configuration. ```APIDOC ## AsyncDieselConnectionManager::new ### Description Creates a new connection manager with default configuration. ### Signature ```rust pub fn new(connection_url: impl Into) -> Self where C: AsyncConnection + 'static, ``` ### Parameters #### Path Parameters - **connection_url** (impl Into) - Required - Database connection URL ### Returns A new `AsyncDieselConnectionManager` instance. ### Example ```rust use diesel_async::pooled_connection::AsyncDieselConnectionManager; use diesel_async::AsyncPgConnection; let manager = AsyncDieselConnectionManager::::new( "postgresql://user:pass@localhost/db" ); ``` ``` -------------------------------- ### Execute a Query and Get Affected Rows Count Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-run-query-dsl.md Use this when you don't need the returned data, only the count of modified rows. It executes commands like INSERT, UPDATE, or DELETE. ```rust use diesel_async::RunQueryDsl; use diesel::insert_into; let inserted_rows = insert_into(users) .values(name.eq("Alice")) .execute(&mut conn) .await?; println!("Inserted {} rows", inserted_rows); ``` -------------------------------- ### Implement BlockOn for Custom Runtimes Source: https://github.com/diesel-rs/diesel_async/blob/main/_autodocs/api-reference-wrappers.md Implement the `BlockOn` trait for custom runtimes to manage asynchronous operations within a synchronous context. This example shows a basic implementation using the `futures` crate. ```rust use diesel_async::async_connection_wrapper::BlockOn; use std::future::Future; struct MyRuntime; impl BlockOn for MyRuntime { fn block_on(&self, f: F) -> F::Output where F: Future, { // Custom implementation - example using futures futures::executor::block_on(f) } fn get_runtime() -> Self { MyRuntime } } // Use it let conn: AsyncConnectionWrapper = AsyncConnectionWrapper::establish("postgresql://localhost/db")?; ```