pub struct DatabasePool { /* private fields */ }
Expand description
High-performance database connection pool manager.
DatabasePool
manages a pool of database connections for efficient resource
utilization and optimal performance. It provides async methods for executing
queries, managing transactions, and handling database operations.
§Features
- Connection Pooling: Maintains a pool of reusable database connections
- Async Operations: All database operations are async and non-blocking
- Type Safety: Compile-time query validation with SQLx
- JSON Support: Automatic conversion of query results to JSON
- Transaction Support: ACID transactions with commit/rollback
- Error Handling: Comprehensive error handling and recovery
§Examples
§Basic Connection
use torch_web::database::DatabasePool;
let db = DatabasePool::new("postgresql://user:pass@localhost/mydb").await?;
§Custom Pool Configuration
use torch_web::database::DatabasePool;
let db = DatabasePool::with_config(
"postgresql://user:pass@localhost/mydb",
DatabaseConfig {
max_connections: 50,
min_connections: 5,
acquire_timeout: Duration::from_secs(30),
idle_timeout: Some(Duration::from_secs(600)),
max_lifetime: Some(Duration::from_secs(1800)),
}
).await?;
§Query Execution
use torch_web::database::DatabasePool;
let db = DatabasePool::new("postgresql://localhost/mydb").await?;
// Simple query
let users = db.query_json("SELECT * FROM users WHERE active = $1", &["true"]).await?;
// Insert with return value
let result = db.execute(
"INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id",
&["John Doe", "john@example.com"]
).await?;
// Query single row
let user = db.query_one_json(
"SELECT * FROM users WHERE id = $1",
&["123"]
).await?;
§Transaction Example
use torch_web::database::DatabasePool;
let db = DatabasePool::new("postgresql://localhost/mydb").await?;
let mut tx = db.begin_transaction().await?;
// Multiple operations in transaction
tx.execute("UPDATE accounts SET balance = balance - 100 WHERE id = 1").await?;
tx.execute("UPDATE accounts SET balance = balance + 100 WHERE id = 2").await?;
tx.execute("INSERT INTO transfers (from_id, to_id, amount) VALUES (1, 2, 100)").await?;
// Commit all changes
tx.commit().await?;
Implementations§
Source§impl DatabasePool
impl DatabasePool
Auto Trait Implementations§
impl Freeze for DatabasePool
impl RefUnwindSafe for DatabasePool
impl Send for DatabasePool
impl Sync for DatabasePool
impl Unpin for DatabasePool
impl UnwindSafe for DatabasePool
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more