Skip to main content

TryFromDb

Trait TryFromDb 

Source
pub trait TryFromDb<T>: Sized {
    type Error;

    // Required method
    fn try_from_db<'async_trait>(
        value: T,
        db: Arc<Box<dyn Database>>,
    ) -> Pin<Box<dyn Future<Output = Result<Self, Self::Error>> + Send + 'async_trait>>
       where Self: 'async_trait;
}
Expand description

Trait for converting types from database representations with database context

Similar to TryFrom but provides access to the database instance during conversion. This is useful when converting database rows into domain objects that may need to perform additional queries to load related data.

§Type Parameters

  • T - The input type to convert from (typically a database row or value)

§Example

use switchy_database::{TryFromDb, Database, DatabaseError, Row};
use std::sync::Arc;

struct User {
    id: i64,
    name: String,
}

#[async_trait]
impl TryFromDb<Row> for User {
    type Error = DatabaseError;

    async fn try_from_db(row: Row, db: Arc<Box<dyn Database>>) -> Result<Self, Self::Error> {
        Ok(User {
            id: row.get("id").unwrap().as_i64().unwrap(),
            name: row.get("name").unwrap().as_str().unwrap().to_string(),
        })
    }
}

Required Associated Types§

Source

type Error

The error type returned when conversion fails

Required Methods§

Source

fn try_from_db<'async_trait>( value: T, db: Arc<Box<dyn Database>>, ) -> Pin<Box<dyn Future<Output = Result<Self, Self::Error>> + Send + 'async_trait>>
where Self: 'async_trait,

Attempts to convert from T to Self with database context

§Errors
  • Returns Self::Error if conversion fails

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<T, U> TryFromDb<Option<U>> for Option<T>
where U: Send + 'static, T: TryFromDb<U>,

Source§

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

Source§

fn try_from_db<'async_trait>( value: Option<U>, db: Arc<Box<dyn Database>>, ) -> Pin<Box<dyn Future<Output = Result<Option<T>, <T as TryFromDb<U>>::Error>> + Send + 'async_trait>>
where Option<T>: 'async_trait,

Source§

impl<T, U> TryFromDb<Vec<U>> for Vec<T>
where U: Send + 'static, T: TryFromDb<U> + Send,

Source§

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

Source§

fn try_from_db<'async_trait>( value: Vec<U>, db: Arc<Box<dyn Database>>, ) -> Pin<Box<dyn Future<Output = Result<Vec<T>, <T as TryFromDb<U>>::Error>> + Send + 'async_trait>>
where Vec<T>: 'async_trait,

Implementors§