ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Clean, ergonomic projections without boilerplate

use super::TypedQuery;
use std::marker::PhantomData;

/// A clean row accessor that returns values directly (no .into() needed)
pub struct CleanRow {
    source_name: String,
    schema: Option<String>,
}

impl CleanRow {
    pub fn new(source_name: String, schema: Option<String>) -> Self {
        Self {
            source_name,
            schema,
        }
    }

    /// Get column values directly as their target types
    pub fn column<T>(&self, name: &str) -> CleanColumn<T> {
        CleanColumn {
            name: name.to_string(),
            source_name: self.source_name.clone(),
            schema: self.schema.clone(),
            _phantom: PhantomData,
        }
    }

    // Common column accessors - in real implementation would extract from row data
    pub fn id(&self) -> i32 {
        0
    }
    pub fn name(&self) -> String {
        String::new()
    }
    pub fn email(&self) -> String {
        String::new()
    }
    pub fn age(&self) -> i32 {
        0
    }
    pub fn active(&self) -> bool {
        false
    }
    pub fn title(&self) -> String {
        String::new()
    }
    pub fn views(&self) -> i32 {
        0
    }
    pub fn user_id(&self) -> i32 {
        0
    }
    pub fn created_at(&self) -> chrono::DateTime<chrono::Utc> {
        chrono::Utc::now()
    }
}

/// A column that can be extracted cleanly
pub struct CleanColumn<T> {
    name: String,
    source_name: String,
    schema: Option<String>,
    _phantom: PhantomData<T>,
}

impl<T> CleanColumn<T> {
    pub fn qualified_name(&self) -> String {
        if let Some(ref schema) = self.schema {
            format!("\"{}\".\"{}\".\"{}\"", schema, self.source_name, self.name)
        } else {
            format!("\"{}\".\"{}\"", self.source_name, self.name)
        }
    }
}

/// Enhanced typed query with clean projection syntax
impl TypedQuery {
    /// Ultra-clean struct projection (no .into() needed!)
    pub fn select_clean<S, P>(self, projection: P) -> CleanProjectedQuery<S>
    where
        P: Fn(CleanRow) -> S + 'static,
        S: AutoProjection,
    {
        let _row = CleanRow::new(
            self.source
                .as_ref()
                .map(|s| s.name().to_string())
                .unwrap_or_default(),
            self.source
                .as_ref()
                .and_then(|s| s.schema().map(|s| s.to_string())),
        );

        // For demo, we'll use the auto-projection columns
        let projection_sql = S::column_names();

        CleanProjectedQuery {
            base_query: self,
            projection_sql,
            _projection: Box::new(projection),
            _phantom: PhantomData,
        }
    }

    /// Automatic projection based on struct field names
    pub fn select_auto<S>(self) -> CleanProjectedQuery<S>
    where
        S: AutoProjection + Default,
    {
        let projection_sql = S::column_names();

        CleanProjectedQuery {
            base_query: self,
            projection_sql,
            _projection: Box::new(|_| S::default()),
            _phantom: PhantomData,
        }
    }
}

/// A query with clean projection
pub struct CleanProjectedQuery<T> {
    base_query: TypedQuery,
    projection_sql: Vec<String>,
    _projection: Box<dyn Fn(CleanRow) -> T>,
    _phantom: PhantomData<T>,
}

impl<T> CleanProjectedQuery<T> {
    /// Generate SQL for the clean projected query
    pub fn to_sql(&self) -> String {
        let mut sql = String::from("SELECT ");
        sql.push_str(&self.projection_sql.join(", "));

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

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

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

        if let Some(_limit) = self.base_query.limit {
            sql.push_str(&format!(" LIMIT ?"));
        }

        if let Some(_offset) = self.base_query.offset {
            sql.push_str(&format!(" OFFSET ?"));
        }

        sql
    }

    /// Execute and collect results (mock implementation)
    pub fn collect<C: FromIterator<T>>(self) -> C {
        // In real implementation, this would execute SQL and map results
        std::iter::empty().collect()
    }
}

/// Trait for automatic field mapping
pub trait AutoProjection {
    /// Get the column names for this projection
    fn column_names() -> Vec<String>;

    /// Map from database row to struct (in real implementation)
    fn from_row(row: &CleanRow) -> Self;
}

/// Macro to automatically implement AutoProjection
#[macro_export]
macro_rules! auto_projection {
    ($struct_name:ident { $($field:ident: $column:ident),* $(,)? }) => {
        impl $crate::dsl::clean_projection::AutoProjection for $struct_name {
            fn column_names() -> Vec<String> {
                vec![
                    $(
                        format!("\"{}\"", stringify!($column)),
                    )*
                ]
            }

            fn from_row(row: &$crate::dsl::clean_projection::CleanRow) -> Self {
                Self {
                    $(
                        $field: row.$column(),
                    )*
                }
            }
        }
    };

    // Simplified version where field names match column names
    ($struct_name:ident { $($field:ident),* $(,)? }) => {
        impl $crate::dsl::clean_projection::AutoProjection for $struct_name {
            fn column_names() -> Vec<String> {
                vec![
                    $(
                        format!("\"{}\"", stringify!($field)),
                    )*
                ]
            }

            fn from_row(row: &$crate::dsl::clean_projection::CleanRow) -> Self {
                Self {
                    $(
                        $field: row.$field(),
                    )*
                }
            }
        }
    };
}

/// Shorthand query builders
impl TypedQuery {
    /// Super clean syntax for common patterns
    pub fn select<S>(self) -> CleanProjectedQuery<S>
    where
        S: AutoProjection + Default,
    {
        self.select_auto()
    }

    /// Clean where + select in one call
    pub fn where_select<S, W>(self, where_clause: W) -> CleanProjectedQuery<S>
    where
        W: Into<super::WhereCondition>,
        S: AutoProjection + Default,
    {
        self.where_clause(where_clause.into()).select()
    }
}