Struct DatabasePool

Source
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

Source

pub async fn new(_database_url: &str) -> Result<Self, Box<dyn Error>>

Source

pub async fn query_json( &self, _query: &str, _params: &[&str], ) -> Result<Vec<Value>, Box<dyn Error>>

Source

pub async fn execute( &self, _query: &str, _params: &[&str], ) -> Result<u64, Box<dyn Error>>

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more