ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Type-safe query builder with compile-time column validation

use super::{OrderBy, Source, TypedColumn, WhereCondition};
use crate::schema::{Table, View};

/// Trait for column-like objects that can be used in queries
pub trait ColumnLike {
    /// Get the qualified column name
    fn qualified_name(&self) -> String;
}

impl<T> ColumnLike for TypedColumn<T> {
    fn qualified_name(&self) -> String {
        self.qualified_name()
    }
}

/// A type-safe query builder (generic over column types)
#[derive(Debug, Clone)]
pub struct TypedQuery {
    /// The source table or view
    pub source: Option<Source>,
    /// Selected columns (as strings for flexibility)
    pub select_columns: Vec<String>,
    /// WHERE conditions (type-safe)
    pub where_conditions: Option<WhereCondition>,
    /// ORDER BY clauses (as strings for flexibility)
    pub order_by: Vec<String>,
    /// LIMIT clause
    pub limit: Option<usize>,
    /// OFFSET clause
    pub offset: Option<usize>,
}

impl TypedQuery {
    /// Create a new typed query
    pub fn new() -> Self {
        Self {
            source: None,
            select_columns: Vec::new(),
            where_conditions: None,
            order_by: Vec::new(),
            limit: None,
            offset: None,
        }
    }

    /// Set the source table
    pub fn from_table(mut self, table: Table) -> Self {
        self.source = Some(Source::Table(table));
        self
    }

    /// Set the source view
    pub fn from_view(mut self, view: View) -> Self {
        self.source = Some(Source::View(view));
        self
    }

    /// Select specific columns by converting them to strings
    pub fn select_columns_from<I>(mut self, columns: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<String>,
    {
        self.select_columns = columns.into_iter().map(|c| c.into()).collect();
        self
    }

    /// Add a single column to select (accepts any TypedColumn<T>)
    pub fn select_column<T>(mut self, column: TypedColumn<T>) -> Self {
        self.select_columns.push(column.qualified_name());
        self
    }

    /// Set WHERE conditions (type-safe)
    pub fn where_clause(mut self, condition: WhereCondition) -> Self {
        self.where_conditions = Some(condition);
        self
    }

    /// Add ORDER BY (accepts any OrderBy<T>)
    pub fn order_by<T>(mut self, order: OrderBy<T>) -> Self {
        self.order_by.push(order.to_sql());
        self
    }

    /// Set LIMIT
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set OFFSET
    pub fn offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Generate SQL from the typed query
    pub fn to_sql(&self) -> String {
        let mut sql = String::from("SELECT ");

        // Add columns
        if self.select_columns.is_empty() {
            sql.push('*');
        } else {
            sql.push_str(&self.select_columns.join(", "));
        }

        // Add FROM clause
        if let Some(ref source) = self.source {
            sql.push_str(" FROM ");
            sql.push_str(&source.qualified_name());
        }

        // Add WHERE clause
        if let Some(ref conditions) = self.where_conditions {
            sql.push_str(" WHERE ");
            sql.push_str(&conditions.to_sql());
        }

        // Add ORDER BY
        if !self.order_by.is_empty() {
            sql.push_str(" ORDER BY ");
            sql.push_str(&self.order_by.join(", "));
        }

        // Add LIMIT
        if let Some(_limit) = self.limit {
            sql.push_str(" LIMIT ?");
        }

        // Add OFFSET
        if let Some(_offset) = self.offset {
            sql.push_str(" OFFSET ?");
        }

        sql
    }
}

/// Builder methods for creating typed queries from macro-generated modules
pub trait TypedQueryBuilder {
    /// Start a new query for this source
    fn query() -> TypedQuery;
}