lumus_sql_builder/sqlite/
join.rs

1use super::BuildableStatement;
2use crate::errors::SqlBuilderError;
3
4/// Represents the possible join types.
5#[derive(Debug)]
6pub enum JoinType {
7    Inner,
8    Left,
9    Right,
10    RightOuter,
11    LeftOuter,
12    Full,
13}
14
15/// Implementation of the `BuildableStatement` trait for `JoinType`, allowing it to be printed.
16impl BuildableStatement for JoinType {
17    fn build(&self) -> String {
18        String::from(match self {
19            Self::Inner => "INNER",
20            Self::Left => "LEFT",
21            Self::Right => "RIGHT",
22            Self::RightOuter => "RIGHT OUTER",
23            Self::LeftOuter => "LEFT OUTER",
24            Self::Full => "FULL",
25        })
26    }
27}
28
29/// Represents a ´JOIN´ clause builder for SQL queries
30#[derive(Debug)]
31pub struct Join {
32    table: String,
33    join_type: JoinType,
34    on: String,
35}
36
37impl Join {
38    /// Creates a new `Select` instance with the specified table name.
39    /// # Example
40    /// ```
41    /// use lumus_sql_builder::sqlite::{Join, JoinType};
42    /// let join = Join::new("phones p", JoinType::Inner, "p.user_id = u.user_id").build().unwrap();
43    /// assert_eq!(join, "INNER JOIN phones p ON p.user_id = u.user_id");
44    /// ```
45    pub fn new(table: &str, join_type: JoinType, on: &str) -> Self {
46        Self {
47            table: table.to_string(),
48            join_type,
49            on: on.to_string(),
50        }
51    }
52
53    pub fn build(self) -> Result<String, SqlBuilderError> {
54        if self.table.is_empty() {
55            return Err(SqlBuilderError::EmptyTableName);
56        }
57
58        if self.on.is_empty() {
59            return Err(SqlBuilderError::EmptyOnClause);
60        }
61
62        Ok(format!(
63            "{} JOIN {} ON {}",
64            self.join_type.build(),
65            self.table,
66            self.on
67        ))
68    }
69}