sqlgen 0.1.6

A library to generate SQL Statements.
Documentation
use crate::prelude::*;

#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[derive(Debug)]
pub enum TableSource {
    Table {
        table: Table,
    },
    JoinedTable {
        join_type: JoinType,
        table_source: Box<TableSource>,
        on: SearchCondition,
    },
}

#[derive(Debug)]
pub struct JoinTableSourceBuilder {
    select_query_builder: SelectQueryBuilder,
    join_table_source: TableSource,
    join_type: JoinType,
}

impl JoinTableSourceBuilder {
    pub(crate) fn join(
        join_type: JoinType,
        select_query_builder: SelectQueryBuilder,
        join_table_source: TableSource,
    ) -> Self {
        Self {
            select_query_builder,
            join_table_source,
            join_type,
        }
    }

    pub fn on(self, search_condition: impl Into<SearchCondition>) -> Result<SelectQueryBuilder> {
        let table_source = TableSource::JoinedTable {
            join_type: self.join_type,
            table_source: Box::new(self.join_table_source),
            on: search_condition.into(),
        };

        self.select_query_builder.push_from(table_source)
    }
}

impl Sql for TableSource {
    fn sql(&self, s: String, ctx: &Context) -> Result<String> {
        match self {
            TableSource::Table { table } => {
                let s = table.sql(s, ctx);

                s
            }
            TableSource::JoinedTable {
                join_type,
                table_source,
                on,
            } => {
                let s = join_type.sql(s, ctx)?;
                // let s = lhs.sql(s, ctx);
                let mut s = table_source.sql(s, ctx)?;
                s.push_str(" ON ");
                let s = on.sql(s, ctx);

                s
            }
        }
    }
}

impl<T> From<T> for TableSource
where
    T: AsRef<str>,
{
    fn from(value: T) -> Self {
        let table = Table::new(value.as_ref());

        TableSource::Table { table }
    }
}