Skip to main content

utopia_query/builder/
join.rs

1//! [`JoinBuilder`]: the conditions of a join built with a closure.
2
3use crate::builder::types::{Condition, JoinOn};
4use crate::error::{Error, Result};
5use crate::value::{IntoValue, IntoValues};
6
7const OPERATORS: [&str; 7] = ["=", "!=", "<", ">", "<=", ">=", "<>"];
8
9/// `/^[a-zA-Z_][a-zA-Z0-9_.]*$/D`.
10pub(crate) fn is_identifier_path(name: &str) -> bool {
11    crate::hook::is_column_name(name)
12}
13
14/// The conditions of one join: column comparisons (`on`) and conditions
15/// with bindings (`where`, raw SQL).
16///
17/// PHP: `Utopia\Query\Builder\JoinBuilder`.
18#[derive(Debug, Clone, PartialEq, Default)]
19pub struct JoinBuilder {
20    ons: Vec<JoinOn>,
21    wheres: Vec<Condition>,
22}
23
24impl JoinBuilder {
25    /// No conditions.
26    pub fn new() -> Self {
27        JoinBuilder::default()
28    }
29
30    /// `left operator right` (columns; PHP's default operator is `=`).
31    ///
32    /// PHP: `on()`.
33    pub fn on(&mut self, left: &str, right: &str, operator: &str) -> Result<&mut Self> {
34        if !is_identifier_path(left) {
35            return Err(Error::Validation(format!("Invalid column name: {left}")));
36        }
37        if !is_identifier_path(right) {
38            return Err(Error::Validation(format!("Invalid column name: {right}")));
39        }
40        if !OPERATORS.contains(&operator) {
41            return Err(Error::Validation(format!("Invalid join operator: {operator}")));
42        }
43        self.ons.push(JoinOn::new(left, operator, right));
44        Ok(self)
45    }
46
47    /// A raw ON condition with its bindings, enclosed in parentheses like
48    /// `where_raw()`.
49    ///
50    /// PHP: `onRaw()`.
51    pub fn on_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
52        self.wheres.push(Condition::new(
53            format!("({})", expression.into()),
54            bindings.into_values().values().cloned().collect(),
55        ));
56        self
57    }
58
59    /// `column operator ?` with `value` bound.
60    ///
61    /// PHP: `where()`.
62    pub fn where_(&mut self, column: &str, operator: &str, value: impl IntoValue) -> Result<&mut Self> {
63        if !is_identifier_path(column) {
64            return Err(Error::Validation(format!("Invalid column name: {column}")));
65        }
66        if !OPERATORS.contains(&operator) {
67            return Err(Error::Validation(format!("Invalid join operator: {operator}")));
68        }
69        self.wheres.push(Condition::new(format!("{column} {operator} ?"), vec![value.into_value()]));
70        Ok(self)
71    }
72
73    /// A raw condition for the join's ON clause, enclosed in parentheses:
74    /// the ON conditions are joined with AND, so an OR inside a bare
75    /// `a = b OR 1 = 1` would escape the other conditions, including those a
76    /// join-filter hook adds.
77    ///
78    /// PHP: `whereRaw()`.
79    pub fn where_raw(&mut self, expression: impl Into<String>, bindings: impl IntoValues) -> &mut Self {
80        self.wheres.push(Condition::new(
81            format!("({})", expression.into()),
82            bindings.into_values().values().cloned().collect(),
83        ));
84        self
85    }
86
87    /// Adds a comparison and a condition as they are, for a join whose conditions were
88    /// checked where they were written (PHP's `JoinBuilder`).
89    pub fn push(
90        &mut self,
91        ons: impl IntoIterator<Item = JoinOn>,
92        wheres: impl IntoIterator<Item = Condition>,
93    ) -> &mut Self {
94        self.ons.extend(ons);
95        self.wheres.extend(wheres);
96        self
97    }
98
99    /// The column comparisons.
100    ///
101    /// PHP: `$ons`.
102    pub fn ons(&self) -> &[JoinOn] {
103        &self.ons
104    }
105
106    /// The conditions with bindings.
107    ///
108    /// PHP: `$wheres`.
109    pub fn wheres(&self) -> &[Condition] {
110        &self.wheres
111    }
112}