Skip to main content

QueryBook

Trait QueryBook 

Source
pub trait QueryBook<T: SqlEntity> {
    // Required method
    fn get_sql_source(&self) -> &'static str;
}
Expand description

A trait to mark types that are query books. Query books are responsible of building the queries that will be sent to the database server. This is the place where SQL templates are defined and populated with the parameters. By essence, a QueryBook takes its data from a SQL source and defines the SQL computation that will return the data.

The example shown therafter could be brought by the ReadQueryBook trait and is presented here for the sake of example.

§Examples

use std::marker::PhantomData;
use uuid::Uuid;
use agrum::{QueryBook, SqlEntity, SqlQuery, ToSqlAny, WhereCondition};

#[derive(Default)]
struct CompanyQueryBook<T: SqlEntity> {
    _phantom: PhantomData<T>,
}

impl<T: SqlEntity> QueryBook<T> for CompanyQueryBook<T> {
    fn get_sql_source(&self) -> &'static str {
        "some_schema.company"
    }
}

impl<T: SqlEntity> CompanyQueryBook<T> {
    fn get_by_id<'a>(&self, company_id: &'a Uuid) -> SqlQuery<'a, T> {
        self.select(WhereCondition::new("company_id = $?", vec![company_id]))
    }

    fn get_sql_definition(&self) -> &'static str {
        "select {:projection:} from {:source:} where {:condition:}"
    }

    fn select<'a>(&self, conditions: WhereCondition<'a>) -> SqlQuery<'a, T> {
        let mut query = SqlQuery::new(self.get_sql_definition());
        let (conditions, parameters) = conditions.expand();
        query
            .set_variable("projection", &T::get_projection().to_string())
            .set_variable("source", self.get_sql_source())
            .set_variable("condition", &conditions.to_string())
            .set_parameters(parameters);
        query
    }
}

Required Methods§

Source

fn get_sql_source(&self) -> &'static str

Return the definition of the SQL data source. It could be a table name or a view name or a values list or function or even a sub-query.

Implementors§