|
| 1 | +//! Demonstrates how to configure a connection pool using `SqlitePoolOptions`. |
| 2 | +//! |
| 3 | +//! Run with: |
| 4 | +//! |
| 5 | +//! ```not_rust |
| 6 | +//! cargo run -p sqlx-example-sqlite-pool-configuration |
| 7 | +//! ``` |
| 8 | +
|
| 9 | +use sqlx::sqlite::SqlitePoolOptions; |
| 10 | +use std::time::Duration; |
| 11 | + |
| 12 | +#[tokio::main(flavor = "current_thread")] |
| 13 | +async fn main() -> Result<(), sqlx::Error> { |
| 14 | + let pool = SqlitePoolOptions::new() |
| 15 | + // Set the maximum number of connections the pool should maintain. |
| 16 | + .max_connections(5) |
| 17 | + // Set the minimum number of idle connections the pool should maintain. |
| 18 | + .min_connections(1) |
| 19 | + // Set the maximum amount of time to wait for a connection to become available. |
| 20 | + .acquire_timeout(Duration::from_secs(3)) |
| 21 | + // Set the maximum idle duration for individual connections. |
| 22 | + // Connections that sit idle longer than this are closed. |
| 23 | + .idle_timeout(Duration::from_secs(60 * 10)) |
| 24 | + // Set the maximum lifetime of individual connections. |
| 25 | + // Connections older than this are closed regardless of idle time. |
| 26 | + .max_lifetime(Duration::from_secs(60 * 30)) |
| 27 | + // Connect to an in-memory SQLite database. |
| 28 | + .connect(":memory:") |
| 29 | + .await?; |
| 30 | + |
| 31 | + // Create a table and insert some data to verify the pool works. |
| 32 | + sqlx::query("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)") |
| 33 | + .execute(&pool) |
| 34 | + .await?; |
| 35 | + |
| 36 | + sqlx::query("INSERT INTO users (name) VALUES (?)") |
| 37 | + .bind("Alice") |
| 38 | + .execute(&pool) |
| 39 | + .await?; |
| 40 | + |
| 41 | + sqlx::query("INSERT INTO users (name) VALUES (?)") |
| 42 | + .bind("Bob") |
| 43 | + .execute(&pool) |
| 44 | + .await?; |
| 45 | + |
| 46 | + // Query the data back. |
| 47 | + let rows: Vec<(i64, String)> = sqlx::query_as("SELECT id, name FROM users ORDER BY id") |
| 48 | + .fetch_all(&pool) |
| 49 | + .await?; |
| 50 | + |
| 51 | + for (id, name) in &rows { |
| 52 | + println!("user: id={id}, name={name}"); |
| 53 | + } |
| 54 | + |
| 55 | + // Print pool statistics. |
| 56 | + println!("\nPool statistics:"); |
| 57 | + println!(" size: {}", pool.size()); |
| 58 | + println!(" idle: {}", pool.num_idle()); |
| 59 | + |
| 60 | + pool.close().await; |
| 61 | + println!(" closed: true"); |
| 62 | + |
| 63 | + Ok(()) |
| 64 | +} |
0 commit comments