ignis-db 0.2.0

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

use crate::common::qualified_column_name;
use crate::schema::Column as SchemaColumn;
use std::marker::PhantomData;

/// A type-safe column reference that preserves type information
#[derive(Debug, Clone)]
pub struct TypedColumn<T> {
    /// The actual column data
    pub column: SchemaColumn,
    /// The table or view this column belongs to
    pub source_name: String,
    /// Schema name if present
    pub schema: Option<String>,
    /// Phantom data to preserve type information
    _phantom: PhantomData<T>,
}

impl<T> TypedColumn<T> {
    /// Create a new typed column
    pub fn new(column: SchemaColumn, source_name: String, schema: Option<String>) -> Self {
        Self {
            column,
            source_name,
            schema,
            _phantom: PhantomData,
        }
    }

    /// Get the column name
    pub fn name(&self) -> &str {
        &self.column.name
    }

    /// Get the fully qualified column name
    pub fn qualified_name(&self) -> String {
        qualified_column_name(self.schema.as_deref(), &self.source_name, &self.column.name)
    }

    /// Create an equality condition
    pub fn eq(&self, value: T) -> WhereCondition
    where
        T: ToString,
    {
        WhereCondition::Eq(self.qualified_name(), value.to_string())
    }

    /// Create a greater than condition
    pub fn gt(&self, value: T) -> WhereCondition
    where
        T: ToString,
    {
        WhereCondition::Gt(self.qualified_name(), value.to_string())
    }

    /// Create a less than condition
    pub fn lt(&self, value: T) -> WhereCondition
    where
        T: ToString,
    {
        WhereCondition::Lt(self.qualified_name(), value.to_string())
    }

    /// Create an IN condition
    pub fn in_values(&self, values: Vec<T>) -> WhereCondition
    where
        T: ToString,
    {
        WhereCondition::In(
            self.qualified_name(),
            values.into_iter().map(|v| v.to_string()).collect(),
        )
    }

    /// Create a LIKE condition (for string columns)
    pub fn like(&self, pattern: &str) -> WhereCondition {
        WhereCondition::Like(self.qualified_name(), pattern.to_string())
    }

    /// Create an IS NULL condition
    pub fn is_null(&self) -> WhereCondition {
        WhereCondition::IsNull(self.qualified_name())
    }

    /// Create an IS NOT NULL condition
    pub fn is_not_null(&self) -> WhereCondition {
        WhereCondition::IsNotNull(self.qualified_name())
    }
}

/// Type-safe WHERE conditions
#[derive(Debug, Clone)]
pub enum WhereCondition {
    Eq(String, String),
    Gt(String, String),
    Lt(String, String),
    Gte(String, String),
    Lte(String, String),
    In(String, Vec<String>),
    Like(String, String),
    IsNull(String),
    IsNotNull(String),
    And(Box<WhereCondition>, Box<WhereCondition>),
    Or(Box<WhereCondition>, Box<WhereCondition>),
}

impl WhereCondition {
    /// Combine with AND
    pub fn and(self, other: WhereCondition) -> WhereCondition {
        WhereCondition::And(Box::new(self), Box::new(other))
    }

    /// Combine with OR
    pub fn or(self, other: WhereCondition) -> WhereCondition {
        WhereCondition::Or(Box::new(self), Box::new(other))
    }

    /// Convert to SQL string with proper escaping
    /// WARNING: This method should only be used for trusted column names
    /// For user-provided data, use parameterized queries instead
    pub fn to_sql(&self) -> String {
        match self {
            WhereCondition::Eq(col, _val) => format!("{} = ?", col),
            WhereCondition::Gt(col, _val) => format!("{} > ?", col),
            WhereCondition::Lt(col, _val) => format!("{} < ?", col),
            WhereCondition::Gte(col, _val) => format!("{} >= ?", col),
            WhereCondition::Lte(col, _val) => format!("{} <= ?", col),
            WhereCondition::In(col, vals) => {
                let placeholders = (0..vals.len()).map(|_| "?").collect::<Vec<_>>().join(", ");
                format!("{} IN ({})", col, placeholders)
            }
            WhereCondition::Like(col, _pattern) => format!("{} LIKE ?", col),
            WhereCondition::IsNull(col) => format!("{} IS NULL", col),
            WhereCondition::IsNotNull(col) => format!("{} IS NOT NULL", col),
            WhereCondition::And(left, right) => {
                format!("({} AND {})", left.to_sql(), right.to_sql())
            }
            WhereCondition::Or(left, right) => format!("({} OR {})", left.to_sql(), right.to_sql()),
        }
    }

    /// Get the values for parameter binding
    /// This method returns the actual values that should be bound to the placeholders
    pub fn get_bind_values(&self) -> Vec<String> {
        match self {
            WhereCondition::Eq(_, val) => vec![val.clone()],
            WhereCondition::Gt(_, val) => vec![val.clone()],
            WhereCondition::Lt(_, val) => vec![val.clone()],
            WhereCondition::Gte(_, val) => vec![val.clone()],
            WhereCondition::Lte(_, val) => vec![val.clone()],
            WhereCondition::In(_, vals) => vals.clone(),
            WhereCondition::Like(_, pattern) => vec![pattern.clone()],
            WhereCondition::IsNull(_) => vec![],
            WhereCondition::IsNotNull(_) => vec![],
            WhereCondition::And(left, right) => {
                let mut values = left.get_bind_values();
                values.extend(right.get_bind_values());
                values
            }
            WhereCondition::Or(left, right) => {
                let mut values = left.get_bind_values();
                values.extend(right.get_bind_values());
                values
            }
        }
    }
}

/// Type-safe column selector for queries
#[derive(Debug, Clone)]
pub struct ColumnSelector<T> {
    columns: Vec<TypedColumn<T>>,
}

impl<T> ColumnSelector<T> {
    /// Create a new column selector
    pub fn new() -> Self {
        Self {
            columns: Vec::new(),
        }
    }

    /// Add a column to select
    pub fn column(mut self, column: TypedColumn<T>) -> Self {
        self.columns.push(column);
        self
    }

    /// Add multiple columns
    pub fn columns(mut self, columns: Vec<TypedColumn<T>>) -> Self {
        self.columns.extend(columns);
        self
    }

    /// Get the column names
    pub fn get_names(&self) -> Vec<String> {
        self.columns.iter().map(|c| c.name().to_string()).collect()
    }

    /// Get the qualified column names
    pub fn get_qualified_names(&self) -> Vec<String> {
        self.columns.iter().map(|c| c.qualified_name()).collect()
    }
}

/// Type-safe order by clause
#[derive(Debug, Clone)]
pub struct OrderBy<T> {
    column: TypedColumn<T>,
    direction: OrderDirection,
}

#[derive(Debug, Clone)]
pub enum OrderDirection {
    Asc,
    Desc,
}

impl<T> OrderBy<T> {
    /// Create ascending order
    pub fn asc(column: TypedColumn<T>) -> Self {
        Self {
            column,
            direction: OrderDirection::Asc,
        }
    }

    /// Create descending order
    pub fn desc(column: TypedColumn<T>) -> Self {
        Self {
            column,
            direction: OrderDirection::Desc,
        }
    }

    /// Convert to SQL string
    pub fn to_sql(&self) -> String {
        let dir = match self.direction {
            OrderDirection::Asc => "ASC",
            OrderDirection::Desc => "DESC",
        };
        format!("{} {}", self.column.qualified_name(), dir)
    }
}

/// Convert TypedColumn to String for flexible query building
impl<T> Into<String> for TypedColumn<T> {
    fn into(self) -> String {
        self.qualified_name()
    }
}

/// Convert reference to TypedColumn to String
impl<T> Into<String> for &TypedColumn<T> {
    fn into(self) -> String {
        self.qualified_name()
    }
}