ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! LINQ-style projections for type-safe database queries

use super::{TypedColumn, TypedQuery};
use std::marker::PhantomData;

/// A projection that can transform query results
pub trait Projection<T> {
    type Output;

    /// Apply the projection to transform the input type
    fn project(&self, input: T) -> Self::Output;

    /// Get the SQL column list for this projection
    fn sql_columns(&self) -> Vec<String>;
}

/// A selector for extracting single fields
pub struct FieldSelector<T, F> {
    selector: fn(T) -> F,
    column_name: String,
    _phantom: PhantomData<(T, F)>,
}

impl<T, F> FieldSelector<T, F> {
    pub fn new(selector: fn(T) -> F, column_name: String) -> Self {
        Self {
            selector,
            column_name,
            _phantom: PhantomData,
        }
    }
}

impl<T, F> Projection<T> for FieldSelector<T, F> {
    type Output = F;

    fn project(&self, input: T) -> Self::Output {
        (self.selector)(input)
    }

    fn sql_columns(&self) -> Vec<String> {
        vec![self.column_name.clone()]
    }
}

/// A selector for creating new structs
pub struct StructSelector<T, S> {
    selector: fn(T) -> S,
    column_names: Vec<String>,
    _phantom: PhantomData<(T, S)>,
}

impl<T, S> StructSelector<T, S> {
    pub fn new(selector: fn(T) -> S, column_names: Vec<String>) -> Self {
        Self {
            selector,
            column_names,
            _phantom: PhantomData,
        }
    }
}

impl<T, S> Projection<T> for StructSelector<T, S> {
    type Output = S;

    fn project(&self, input: T) -> Self::Output {
        (self.selector)(input)
    }

    fn sql_columns(&self) -> Vec<String> {
        self.column_names.clone()
    }
}

/// A typed row accessor for LINQ-style operations
pub struct TypedRow {
    source_name: String,
    schema: Option<String>,
}

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

    /// Get a typed column accessor
    pub fn column<T>(&self, name: &str) -> TypedColumn<T> {
        TypedColumn::new(
            crate::schema::Column::new(name.to_string(), Default::default()),
            self.source_name.clone(),
            self.schema.clone(),
        )
    }

    // Common column accessors for examples and convenience
    pub fn id(&self) -> TypedColumn<i32> {
        self.column("id")
    }
    pub fn name(&self) -> TypedColumn<String> {
        self.column("name")
    }
    pub fn email(&self) -> TypedColumn<String> {
        self.column("email")
    }
    pub fn age(&self) -> TypedColumn<i32> {
        self.column("age")
    }
    pub fn active(&self) -> TypedColumn<bool> {
        self.column("active")
    }
    pub fn title(&self) -> TypedColumn<String> {
        self.column("title")
    }
    pub fn views(&self) -> TypedColumn<i32> {
        self.column("views")
    }
    pub fn user_id(&self) -> TypedColumn<i32> {
        self.column("user_id")
    }
    pub fn created_at(&self) -> TypedColumn<chrono::DateTime<chrono::Utc>> {
        self.column("created_at")
    }
}

/// Enhanced typed query with LINQ-style projections
impl TypedQuery {
    /// Select a single field (equivalent to C# Select(p => p.Name))
    pub fn select_field<F, P>(self, projection: P) -> ProjectedQuery<F>
    where
        P: Fn(TypedRow) -> TypedColumn<F> + 'static,
    {
        let row = TypedRow::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())),
        );

        let column = projection(row);
        let column_sql = column.qualified_name();

        ProjectedQuery {
            base_query: self,
            projection_sql: vec![column_sql],
            _phantom: PhantomData,
        }
    }

    /// Select into a custom struct (equivalent to C# Select(p => new PersonSummary { ... }))
    pub fn select_into<S, P>(self, _projection: P) -> ProjectedQuery<S>
    where
        P: Fn(TypedRow) -> S + 'static,
        S: ProjectionTarget,
    {
        let row = TypedRow::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())),
        );

        // This is where we'd analyze the projection to extract column names
        // For now, we'll use a simpler approach with the ProjectionTarget trait
        let projection_sql = S::required_columns(&row);

        ProjectedQuery {
            base_query: self,
            projection_sql,
            _phantom: PhantomData,
        }
    }
}

/// A query with a projection applied
pub struct ProjectedQuery<T> {
    base_query: TypedQuery,
    projection_sql: Vec<String>,
    _phantom: PhantomData<T>,
}

impl<T> ProjectedQuery<T> {
    /// Generate SQL for the 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(" LIMIT ?");
        }

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

        sql
    }

    /// Simulate collecting results (in real implementation, this would execute the query)
    pub fn collect<C: FromIterator<T>>(self) -> C {
        // This would actually execute the query and map results
        // For demo purposes, we'll return an empty collection
        std::iter::empty().collect()
    }
}

/// Trait for types that can be used as projection targets
pub trait ProjectionTarget {
    /// Get the list of required columns for this projection
    fn required_columns(row: &TypedRow) -> Vec<String>;
}

/// Macro to automatically implement ProjectionTarget
#[macro_export]
macro_rules! projection_target {
    ($struct_name:ident { $($field:ident: $column:ident),* $(,)? }) => {
        impl $crate::dsl::projection::ProjectionTarget for $struct_name {
            fn required_columns(row: &$crate::dsl::projection::TypedRow) -> Vec<String> {
                vec![
                    $(
                        row.$column().qualified_name(),
                    )*
                ]
            }
        }
    };
}

/// Macro for anonymous projections (like C# anonymous objects)
#[macro_export]
macro_rules! select_anonymous {
    ($query:expr; $($column:ident),* $(,)?) => {{
        let row = $crate::dsl::projection::TypedRow::new(
            String::new(), // Would be filled from query context
            None
        );
        let columns = vec![
            $(
                row.$column().qualified_name(),
            )*
        ];
        $crate::dsl::projection::ProjectedQuery {
            base_query: $query,
            projection_sql: columns,
            _phantom: std::marker::PhantomData,
        }
    }};
}