ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
//! Information Schema Query Builder
//!
//! Provides a type-safe builder for querying PostgreSQL's information_schema
//! and other system catalogs for introspection and metadata queries.

use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::BuilderValidationError;
use anyhow::Result;

/// Builder for querying information schema tables
#[derive(Debug, Clone)]
pub struct InformationSchemaBuilder {
    /// The information schema table to query
    table: InformationSchemaTable,
    /// Columns to select
    select_columns: Vec<String>,
    /// WHERE conditions
    where_conditions: Vec<WhereCondition>,
    /// ORDER BY clauses
    order_by: Vec<String>,
    /// LIMIT clause
    limit: Option<usize>,
    /// OFFSET clause
    offset: Option<usize>,
}

/// Information schema tables that can be queried
#[derive(Debug, Clone, PartialEq)]
pub enum InformationSchemaTable {
    Schemata,
    Tables,
    Columns,
    Indexes,
    Constraints,
    Functions,
    Procedures,
    Triggers,
    Views,
    Sequences,
    UserDefinedTypes,
    Routines,
}

/// WHERE condition for information schema queries
#[derive(Debug, Clone)]
pub enum WhereCondition {
    Equals(String, String),
    In(String, Vec<String>),
    Like(String, String),
    NotNull(String),
    IsNull(String),
    Custom(String),
}

impl InformationSchemaBuilder {
    /// Create a new information schema builder
    pub fn new() -> Self {
        Self {
            table: InformationSchemaTable::Schemata,
            select_columns: Vec::new(),
            where_conditions: Vec::new(),
            order_by: Vec::new(),
            limit: None,
            offset: None,
        }
    }

    /// Set the information schema table to query
    pub fn table(mut self, table: InformationSchemaTable) -> Self {
        self.table = table;
        self
    }

    /// Add a column to select
    pub fn select_column(mut self, column: &str) -> Self {
        self.select_columns.push(column.to_string());
        self
    }

    /// Add multiple columns to select
    pub fn select_columns(mut self, columns: &[&str]) -> Self {
        self.select_columns
            .extend(columns.iter().map(|s| s.to_string()));
        self
    }

    /// Add a WHERE condition
    pub fn where_condition(mut self, condition: WhereCondition) -> Self {
        self.where_conditions.push(condition);
        self
    }

    /// Add WHERE column = value
    pub fn where_equals(mut self, column: &str, value: &str) -> Self {
        self.where_conditions.push(WhereCondition::Equals(
            column.to_string(),
            value.to_string(),
        ));
        self
    }

    /// Add WHERE column IN (values)
    pub fn where_in(mut self, column: &str, values: &[&str]) -> Self {
        self.where_conditions.push(WhereCondition::In(
            column.to_string(),
            values.iter().map(|s| s.to_string()).collect(),
        ));
        self
    }

    /// Add WHERE column LIKE pattern
    pub fn where_like(mut self, column: &str, pattern: &str) -> Self {
        self.where_conditions.push(WhereCondition::Like(
            column.to_string(),
            pattern.to_string(),
        ));
        self
    }

    /// Add WHERE column IS NOT NULL
    pub fn where_not_null(mut self, column: &str) -> Self {
        self.where_conditions
            .push(WhereCondition::NotNull(column.to_string()));
        self
    }

    /// Add WHERE column IS NULL
    pub fn where_is_null(mut self, column: &str) -> Self {
        self.where_conditions
            .push(WhereCondition::IsNull(column.to_string()));
        self
    }

    /// Add custom WHERE condition
    pub fn where_custom(mut self, condition: &str) -> Self {
        self.where_conditions
            .push(WhereCondition::Custom(condition.to_string()));
        self
    }

    /// Add ORDER BY clause
    pub fn order_by(mut self, column: &str) -> Self {
        self.order_by.push(column.to_string());
        self
    }

    /// Add ORDER BY clause with direction
    pub fn order_by_desc(mut self, column: &str) -> Self {
        self.order_by.push(format!("{} DESC", column));
        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 the SQL 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
        sql.push_str(" FROM information_schema.");
        sql.push_str(&self.table.to_string());

        // Add WHERE clause
        if !self.where_conditions.is_empty() {
            sql.push_str(" WHERE ");
            let conditions: Vec<String> = self
                .where_conditions
                .iter()
                .map(|cond| self.format_condition(cond))
                .collect();
            sql.push_str(&conditions.join(" AND "));
        }

        // 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(&format!(" LIMIT {}", limit));
        }

        // Add OFFSET
        if let Some(offset) = self.offset {
            sql.push_str(&format!(" OFFSET {}", offset));
        }

        sql
    }

    /// Format a WHERE condition
    fn format_condition(&self, condition: &WhereCondition) -> String {
        match condition {
            WhereCondition::Equals(column, value) => {
                format!("{} = '{}'", column, value)
            }
            WhereCondition::In(column, values) => {
                let values_str = values
                    .iter()
                    .map(|v| format!("'{}'", v))
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("{} IN ({})", column, values_str)
            }
            WhereCondition::Like(column, pattern) => {
                format!("{} LIKE '{}'", column, pattern)
            }
            WhereCondition::NotNull(column) => {
                format!("{} IS NOT NULL", column)
            }
            WhereCondition::IsNull(column) => {
                format!("{} IS NULL", column)
            }
            WhereCondition::Custom(condition) => condition.clone(),
        }
    }
}

impl InformationSchemaTable {
    /// Convert to string representation
    pub fn to_string(&self) -> String {
        match self {
            InformationSchemaTable::Schemata => "schemata",
            InformationSchemaTable::Tables => "tables",
            InformationSchemaTable::Columns => "columns",
            InformationSchemaTable::Indexes => "statistics",
            InformationSchemaTable::Constraints => "table_constraints",
            InformationSchemaTable::Functions => "routines",
            InformationSchemaTable::Procedures => "routines",
            InformationSchemaTable::Triggers => "triggers",
            InformationSchemaTable::Views => "views",
            InformationSchemaTable::Sequences => "sequences",
            InformationSchemaTable::UserDefinedTypes => "user_defined_types",
            InformationSchemaTable::Routines => "routines",
        }
        .to_string()
    }
}

// Implement the builder traits
impl SchemaBuilder for InformationSchemaBuilder {
    type Output = String;
    type Error = BuilderValidationError;

    fn build(self) -> Result<Self::Output, Self::Error> {
        if !self.is_valid() {
            let errors = self.validation_errors();
            return Err(BuilderValidationError::Generic(format!(
                "Validation failed: {}",
                errors.join(", ")
            )));
        }

        Ok(self.to_sql())
    }
}

impl ValidatableBuilder for InformationSchemaBuilder {
    fn is_valid(&self) -> bool {
        !self.select_columns.is_empty() || self.table == InformationSchemaTable::Schemata
    }

    fn validation_errors(&self) -> Vec<String> {
        let mut errors = Vec::new();

        if self.select_columns.is_empty() && self.table != InformationSchemaTable::Schemata {
            errors.push("No columns selected".to_string());
        }

        errors
    }
}

impl ConditionalBuilder for InformationSchemaBuilder {
    fn when<F>(mut self, condition: bool, config_fn: F) -> Self
    where
        F: FnOnce(&mut Self),
    {
        if condition {
            config_fn(&mut self);
        }
        self
    }
}

impl InspectableBuilder for InformationSchemaBuilder {
    fn debug_info(&self) -> String {
        format!(
            "InformationSchemaBuilder {{ table: {:?}, columns: {:?}, conditions: {} }}",
            self.table,
            self.select_columns,
            self.where_conditions.len()
        )
    }

    fn summary(&self) -> String {
        format!(
            "Query {} with {} columns and {} conditions",
            self.table.to_string(),
            self.select_columns.len(),
            self.where_conditions.len()
        )
    }
}

/// Convenience function to create a new information schema builder
pub fn information_schema() -> InformationSchemaBuilder {
    InformationSchemaBuilder::new()
}

/// Convenience function to query schemas
pub fn schemas() -> InformationSchemaBuilder {
    InformationSchemaBuilder::new()
        .table(InformationSchemaTable::Schemata)
        .select_column("schema_name")
}

/// Convenience function to query tables
pub fn tables() -> InformationSchemaBuilder {
    InformationSchemaBuilder::new()
        .table(InformationSchemaTable::Tables)
        .select_columns(&["table_schema", "table_name"])
}

/// Convenience function to query columns
pub fn columns() -> InformationSchemaBuilder {
    InformationSchemaBuilder::new()
        .table(InformationSchemaTable::Columns)
        .select_columns(&["table_schema", "table_name", "column_name", "data_type"])
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_schema_query() {
        let query = schemas().where_in("schema_name", &["auth", "app"]).to_sql();

        assert_eq!(
            query,
            "SELECT schema_name FROM information_schema.schemata WHERE schema_name IN ('auth', 'app')"
        );
    }

    #[test]
    fn test_tables_query() {
        let query = tables()
            .where_equals("table_schema", "auth")
            .order_by("table_name")
            .to_sql();

        assert_eq!(
            query,
            "SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema = 'auth' ORDER BY table_name"
        );
    }

    #[test]
    fn test_columns_query() {
        let query = columns()
            .where_equals("table_schema", "auth")
            .where_equals("table_name", "users")
            .to_sql();

        assert_eq!(
            query,
            "SELECT table_schema, table_name, column_name, data_type FROM information_schema.columns WHERE table_schema = 'auth' AND table_name = 'users'"
        );
    }
}