Skip to main content

fletch_orm/
built_query.rs

1//! A built SQL statement with its SQL string and collected bind values.
2
3use sqlx::{Database, Executor, FromRow};
4
5use crate::bind::DatabaseBindable;
6use crate::error::FletchError;
7use crate::value::Value;
8
9/// A built SQL statement with its SQL string and collected bind values.
10#[derive(Debug, Clone)]
11pub struct BuiltQuery {
12    pub sql: String,
13    pub values: Vec<Value>,
14}
15
16impl BuiltQuery {
17    /// Execute the query and return all mapped rows.
18    pub async fn fetch_all<'e, DB, T, Ex>(self, executor: Ex) -> Result<Vec<T>, FletchError>
19    where
20        DB: DatabaseBindable,
21        T: for<'r> FromRow<'r, <DB as Database>::Row> + Send + Unpin,
22        Ex: Executor<'e, Database = DB> + Send,
23    {
24        DB::fetch_all_rows::<T, _>(self, executor).await
25    }
26
27    /// Execute the query and return a single mapped row.
28    pub async fn fetch_one<'e, DB, T, Ex>(self, executor: Ex) -> Result<T, FletchError>
29    where
30        DB: DatabaseBindable,
31        T: for<'r> FromRow<'r, <DB as Database>::Row> + Send + Unpin,
32        Ex: Executor<'e, Database = DB> + Send,
33    {
34        DB::fetch_one_row::<T, _>(self, executor).await
35    }
36
37    /// Execute the query without returning rows.
38    pub async fn execute<'e, DB, Ex>(self, executor: Ex) -> Result<u64, FletchError>
39    where
40        DB: DatabaseBindable,
41        Ex: Executor<'e, Database = DB> + Send,
42    {
43        DB::execute_query(self, executor)
44            .await
45            .map(|outcome| outcome.rows_affected)
46    }
47}