use super::{OrderBy, Source, TypedColumn, WhereCondition};
use crate::schema::{Table, View};
pub trait ColumnLike {
fn qualified_name(&self) -> String;
}
impl<T> ColumnLike for TypedColumn<T> {
fn qualified_name(&self) -> String {
self.qualified_name()
}
}
#[derive(Debug, Clone)]
pub struct TypedQuery {
pub source: Option<Source>,
pub select_columns: Vec<String>,
pub where_conditions: Option<WhereCondition>,
pub order_by: Vec<String>,
pub limit: Option<usize>,
pub offset: Option<usize>,
}
impl TypedQuery {
pub fn new() -> Self {
Self {
source: None,
select_columns: Vec::new(),
where_conditions: None,
order_by: Vec::new(),
limit: None,
offset: None,
}
}
pub fn from_table(mut self, table: Table) -> Self {
self.source = Some(Source::Table(table));
self
}
pub fn from_view(mut self, view: View) -> Self {
self.source = Some(Source::View(view));
self
}
pub fn select_columns_from<I>(mut self, columns: I) -> Self
where
I: IntoIterator,
I::Item: Into<String>,
{
self.select_columns = columns.into_iter().map(|c| c.into()).collect();
self
}
pub fn select_column<T>(mut self, column: TypedColumn<T>) -> Self {
self.select_columns.push(column.qualified_name());
self
}
pub fn where_clause(mut self, condition: WhereCondition) -> Self {
self.where_conditions = Some(condition);
self
}
pub fn order_by<T>(mut self, order: OrderBy<T>) -> Self {
self.order_by.push(order.to_sql());
self
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn offset(mut self, offset: usize) -> Self {
self.offset = Some(offset);
self
}
pub fn to_sql(&self) -> String {
let mut sql = String::from("SELECT ");
if self.select_columns.is_empty() {
sql.push('*');
} else {
sql.push_str(&self.select_columns.join(", "));
}
if let Some(ref source) = self.source {
sql.push_str(" FROM ");
sql.push_str(&source.qualified_name());
}
if let Some(ref conditions) = self.where_conditions {
sql.push_str(" WHERE ");
sql.push_str(&conditions.to_sql());
}
if !self.order_by.is_empty() {
sql.push_str(" ORDER BY ");
sql.push_str(&self.order_by.join(", "));
}
if let Some(_limit) = self.limit {
sql.push_str(" LIMIT ?");
}
if let Some(_offset) = self.offset {
sql.push_str(" OFFSET ?");
}
sql
}
}
pub trait TypedQueryBuilder {
fn query() -> TypedQuery;
}