Expand description
§Database Integration
This module provides comprehensive database integration for Torch applications, featuring connection pooling, query builders, migrations, and ORM-like functionality. It’s built on top of SQLx for type-safe, async database operations.
§Features
- Connection Pooling: Efficient connection management with configurable pool sizes
- Type Safety: Compile-time checked queries with SQLx
- Async/Await: Full async support for non-blocking database operations
- Multiple Databases: Support for PostgreSQL, MySQL, SQLite
- Query Builder: Fluent API for building complex queries
- Migrations: Database schema versioning and migrations
- JSON Support: Automatic JSON serialization/deserialization
- Transaction Support: ACID transactions with rollback support
Note: This module requires the database
feature to be enabled.
§Quick Start
§Basic Setup
use torch_web::{App, database::DatabasePool};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create database pool
let db = DatabasePool::new("postgresql://user:pass@localhost/mydb").await?;
let app = App::new()
.with_state(db)
.get("/users", |State(db): State<DatabasePool>| async move {
let users = db.query_json("SELECT * FROM users", &[]).await?;
Response::ok().json(&users)
})
.post("/users", |State(db): State<DatabasePool>, Json(user): Json<CreateUser>| async move {
let result = db.execute(
"INSERT INTO users (name, email) VALUES ($1, $2)",
&[&user.name, &user.email]
).await?;
Response::created().json(&serde_json::json!({"id": result.last_insert_id()}))
});
app.listen("127.0.0.1:3000").await
}
§With Query Builder
use torch_web::{App, database::{DatabasePool, QueryBuilder}};
let app = App::new()
.with_state(db)
.get("/users", |State(db): State<DatabasePool>, Query(params): Query<UserFilters>| async move {
let mut query = QueryBuilder::new("users")
.select(&["id", "name", "email", "created_at"]);
if let Some(name) = params.name {
query = query.where_like("name", &format!("%{}%", name));
}
if let Some(active) = params.active {
query = query.where_eq("active", &active.to_string());
}
let users = query.fetch_json(&db).await?;
Response::ok().json(&users)
});
§With Transactions
use torch_web::{App, database::DatabasePool};
let app = App::new()
.post("/transfer", |State(db): State<DatabasePool>, Json(transfer): Json<Transfer>| async move {
let mut tx = db.begin_transaction().await?;
// Debit from source account
tx.execute(
"UPDATE accounts SET balance = balance - $1 WHERE id = $2",
&[&transfer.amount.to_string(), &transfer.from_account.to_string()]
).await?;
// Credit to destination account
tx.execute(
"UPDATE accounts SET balance = balance + $1 WHERE id = $2",
&[&transfer.amount.to_string(), &transfer.to_account.to_string()]
).await?;
// Record the transfer
tx.execute(
"INSERT INTO transfers (from_account, to_account, amount) VALUES ($1, $2, $3)",
&[&transfer.from_account.to_string(), &transfer.to_account.to_string(), &transfer.amount.to_string()]
).await?;
tx.commit().await?;
Response::ok().json(&serde_json::json!({"status": "success"}))
});
Structs§
- Database
Middleware - Database middleware for automatic connection injection
- Database
Pool - High-performance database connection pool manager.
- Migration
Runner - Migration runner for database schema management
- Query
Builder - Simple query builder for common operations
Traits§
- Request
Database Ext - Extension trait to add database access to Request
Functions§
- database_
health_ check - Database health check