utopia_query/builder/
join.rs1use crate::builder::types::{Condition, JoinOn};
4use crate::error::{Error, Result};
5use crate::value::{IntoValue, IntoValues};
6
7const OPERATORS: [&str; 7] = ["=", "!=", "<", ">", "<=", ">=", "<>"];
8
9pub(crate) fn is_identifier_path(name: &str) -> bool {
11 crate::hook::is_column_name(name)
12}
13
14#[derive(Debug, Clone, PartialEq, Default)]
19pub struct JoinBuilder {
20 ons: Vec<JoinOn>,
21 wheres: Vec<Condition>,
22}
23
24impl JoinBuilder {
25 pub fn new() -> Self {
27 JoinBuilder::default()
28 }
29
30 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 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 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 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 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 pub fn ons(&self) -> &[JoinOn] {
103 &self.ons
104 }
105
106 pub fn wheres(&self) -> &[Condition] {
110 &self.wheres
111 }
112}