use crate::builder::types::{Condition, JoinOn};
use crate::error::{Error, Result};
use crate::value::{IntoValue, IntoValues};
const OPERATORS: [&str; 7] = ["=", "!=", "<", ">", "<=", ">=", "<>"];
pub(crate) fn is_identifier_path(name: &str) -> bool {
crate::hook::is_column_name(name)
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct JoinBuilder {
ons: Vec<JoinOn>,
wheres: Vec<Condition>,
}
impl JoinBuilder {
pub fn new() -> Self {
JoinBuilder::default()
}
pub fn on(&mut self, left: &str, right: &str, operator: &str) -> Result<&mut Self> {
if !is_identifier_path(left) {
return Err(Error::Validation(format!("Invalid column name: {left}")));
}
if !is_identifier_path(right) {
return Err(Error::Validation(format!("Invalid column name: {right}")));
}
if !OPERATORS.contains(&operator) {
return Err(Error::Validation(format!("Invalid join operator: {operator}")));
}
self.ons.push(JoinOn::new(left, operator, right));
Ok(self)
}
pub fn on_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
self.wheres.push(Condition::new(
format!("({})", expression.into()),
bindings.into_values().values().cloned().collect(),
));
self
}
pub fn where_(&mut self, column: &str, operator: &str, value: impl IntoValue) -> Result<&mut Self> {
if !is_identifier_path(column) {
return Err(Error::Validation(format!("Invalid column name: {column}")));
}
if !OPERATORS.contains(&operator) {
return Err(Error::Validation(format!("Invalid join operator: {operator}")));
}
self.wheres.push(Condition::new(format!("{column} {operator} ?"), vec![value.into_value()]));
Ok(self)
}
pub fn where_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
self.wheres.push(Condition::new(
format!("({})", expression.into()),
bindings.into_values().values().cloned().collect(),
));
self
}
pub fn push(
&mut self,
ons: impl IntoIterator<Item = JoinOn>,
wheres: impl IntoIterator<Item = Condition>,
) -> &mut Self {
self.ons.extend(ons);
self.wheres.extend(wheres);
self
}
pub fn ons(&self) -> &[JoinOn] {
&self.ons
}
pub fn wheres(&self) -> &[Condition] {
&self.wheres
}
}