fletch-orm 1.0.0

Lightweight database toolkit built on SQLx
Documentation
//! A built SQL statement with its SQL string and collected bind values.

use sqlx::{Database, Executor, FromRow};

use crate::bind::DatabaseBindable;
use crate::error::FletchError;
use crate::value::Value;

/// A built SQL statement with its SQL string and collected bind values.
#[derive(Debug, Clone)]
pub struct BuiltQuery {
    pub sql: String,
    pub values: Vec<Value>,
}

impl BuiltQuery {
    /// Execute the query and return all mapped rows.
    pub async fn fetch_all<'e, DB, T, Ex>(self, executor: Ex) -> Result<Vec<T>, FletchError>
    where
        DB: DatabaseBindable,
        T: for<'r> FromRow<'r, <DB as Database>::Row> + Send + Unpin,
        Ex: Executor<'e, Database = DB> + Send,
    {
        DB::fetch_all_rows::<T, _>(self, executor).await
    }

    /// Execute the query and return a single mapped row.
    pub async fn fetch_one<'e, DB, T, Ex>(self, executor: Ex) -> Result<T, FletchError>
    where
        DB: DatabaseBindable,
        T: for<'r> FromRow<'r, <DB as Database>::Row> + Send + Unpin,
        Ex: Executor<'e, Database = DB> + Send,
    {
        DB::fetch_one_row::<T, _>(self, executor).await
    }

    /// Execute the query without returning rows.
    pub async fn execute<'e, DB, Ex>(self, executor: Ex) -> Result<u64, FletchError>
    where
        DB: DatabaseBindable,
        Ex: Executor<'e, Database = DB> + Send,
    {
        DB::execute_query(self, executor)
            .await
            .map(|outcome| outcome.rows_affected)
    }
}