ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::GrantBuildError;
use crate::schema::{Grant, GrantTarget, Privilege};

/// Builder for constructing database grants (permissions)
#[derive(Debug, Clone)]
pub struct GrantBuilder {
    privileges: Vec<Privilege>,
    target: Option<GrantTarget>,
    grantee: Option<String>,
    with_grant_option: bool,
    with_hierarchy: bool,
}

impl GrantBuilder {
    /// Create a new grant builder
    pub fn new() -> Self {
        Self {
            privileges: Vec::new(),
            target: None,
            grantee: None,
            with_grant_option: false,
            with_hierarchy: false,
        }
    }

    /// Add a privilege to this grant
    pub fn privilege(mut self, privilege: Privilege) -> Self {
        self.privileges.push(privilege);
        self
    }

    /// Add multiple privileges to this grant
    pub fn privileges(mut self, privileges: Vec<Privilege>) -> Self {
        self.privileges.extend(privileges);
        self
    }

    /// Add privileges (mutable reference version for conditional building)
    pub fn add_privilege(&mut self, privilege: Privilege) {
        self.privileges.push(privilege);
    }

    /// Add multiple privileges (mutable reference version for conditional building)
    pub fn add_privileges(&mut self, privileges: Vec<Privilege>) {
        self.privileges.extend(privileges);
    }

    /// Convenience method to grant SELECT privilege
    pub fn select(mut self) -> Self {
        self.privileges.push(Privilege::Select);
        self
    }

    /// Convenience method to grant INSERT privilege
    pub fn insert(mut self) -> Self {
        self.privileges.push(Privilege::Insert);
        self
    }

    /// Convenience method to grant UPDATE privilege
    pub fn update(mut self) -> Self {
        self.privileges.push(Privilege::Update);
        self
    }

    /// Convenience method to grant DELETE privilege
    pub fn delete(mut self) -> Self {
        self.privileges.push(Privilege::Delete);
        self
    }

    /// Convenience method to grant ALL privileges
    pub fn all(mut self) -> Self {
        self.privileges.push(Privilege::All);
        self
    }

    /// Convenience method to grant USAGE privilege
    pub fn usage(mut self) -> Self {
        self.privileges.push(Privilege::Usage);
        self
    }

    /// Convenience method to grant CREATE privilege
    pub fn create(mut self) -> Self {
        self.privileges.push(Privilege::Create);
        self
    }

    /// Convenience method to grant EXECUTE privilege
    pub fn execute(mut self) -> Self {
        self.privileges.push(Privilege::Execute);
        self
    }

    /// Set the target (what the grant applies to)
    pub fn on(mut self, target: GrantTarget) -> Self {
        self.target = Some(target);
        self
    }

    /// Set the target (mutable reference version for conditional building)
    pub fn set_target(&mut self, target: GrantTarget) {
        self.target = Some(target);
    }

    /// Convenience method to grant on a table
    pub fn on_table(mut self, table_name: impl Into<String>) -> Self {
        self.target = Some(GrantTarget::Table {
            table: table_name.into(),
            schema: None,
        });
        self
    }

    /// Convenience method to grant on a schema
    pub fn on_schema(mut self, schema_name: impl Into<String>) -> Self {
        self.target = Some(GrantTarget::Schema(schema_name.into()));
        self
    }

    /// Convenience method to grant on a function
    pub fn on_function(mut self, function_name: impl Into<String>) -> Self {
        self.target = Some(GrantTarget::Function {
            function: function_name.into(),
            schema: None,
        });
        self
    }

    /// Convenience method to grant on a database
    pub fn on_database(mut self, database_name: impl Into<String>) -> Self {
        self.target = Some(GrantTarget::Database(database_name.into()));
        self
    }

    /// Convenience method to grant on all tables in schema
    pub fn on_all_tables_in_schema(mut self, schema_name: impl Into<String>) -> Self {
        self.target = Some(GrantTarget::AllTablesInSchema(schema_name.into()));
        self
    }

    /// Convenience method to grant on all functions in schema
    pub fn on_all_functions_in_schema(mut self, schema_name: impl Into<String>) -> Self {
        self.target = Some(GrantTarget::AllFunctionsInSchema(schema_name.into()));
        self
    }

    /// Convenience method to grant to a role
    pub fn to_role(mut self, role_name: impl Into<String>) -> Self {
        self.grantee = Some(role_name.into());
        self
    }

    /// Convenience method to grant to a user
    pub fn to_user(mut self, user_name: impl Into<String>) -> Self {
        self.grantee = Some(user_name.into());
        self
    }

    /// Convenience method to grant to PUBLIC
    pub fn to_public(mut self) -> Self {
        self.grantee = Some("PUBLIC".to_string());
        self
    }

    /// Set the grantee (legacy method for backward compatibility)
    pub fn grantee(mut self, grantee: impl Into<String>) -> Self {
        self.grantee = Some(grantee.into());
        self
    }

    /// Set the grantee (mutable reference version for conditional building)
    pub fn set_grantee(&mut self, grantee: impl Into<String>) {
        self.grantee = Some(grantee.into());
    }

    /// Enable WITH GRANT OPTION
    pub fn with_grant_option(mut self, with_grant_option: bool) -> Self {
        self.with_grant_option = with_grant_option;
        self
    }

    /// Set WITH GRANT OPTION (mutable reference version for conditional building)
    pub fn set_with_grant_option(&mut self, with_grant_option: bool) {
        self.with_grant_option = with_grant_option;
    }

    /// Enable WITH HIERARCHY OPTION
    pub fn with_hierarchy(mut self, with_hierarchy: bool) -> Self {
        self.with_hierarchy = with_hierarchy;
        self
    }

    /// Set WITH HIERARCHY OPTION (mutable reference version for conditional building)
    pub fn set_with_hierarchy(&mut self, with_hierarchy: bool) {
        self.with_hierarchy = with_hierarchy;
    }
}

impl SchemaBuilder for GrantBuilder {
    type Output = Grant;
    type Error = GrantBuildError;

    fn build(self) -> Result<Self::Output, Self::Error> {
        if self.privileges.is_empty() {
            return Err(GrantBuildError::NoPrivileges);
        }

        let target = self.target.ok_or(GrantBuildError::NoTarget)?;
        let grantee = self.grantee.ok_or(GrantBuildError::NoGrantee)?;

        // For now, we'll create a grant with the first privilege
        // TODO: Support multiple privileges in a single grant
        let privilege = self.privileges[0].clone();
        let mut grant = Grant::new(privilege, target, grantee);

        if self.with_grant_option {
            grant = grant.with_grant_option(true);
        }

        Ok(grant)
    }
}

impl ValidatableBuilder for GrantBuilder {
    fn is_valid(&self) -> bool {
        !self.privileges.is_empty()
            && self.target.is_some()
            && self.grantee.is_some()
            && !(self.privileges.contains(&Privilege::All) && self.privileges.len() > 1)
    }

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

        if self.privileges.is_empty() {
            errors.push("Grant must specify at least one privilege".to_string());
        }

        if self.target.is_none() {
            errors.push("Grant must specify a target (ON clause)".to_string());
        }

        if self.grantee.is_none() {
            errors.push("Grant must specify a grantee (TO clause)".to_string());
        }

        if self.privileges.contains(&Privilege::All) && self.privileges.len() > 1 {
            errors.push("Cannot specify ALL privilege with other privileges".to_string());
        }

        errors
    }
}

impl ConditionalBuilder for GrantBuilder {
    // The trait provides default implementations for when() and when_else()
    // No additional implementation needed
}

impl InspectableBuilder for GrantBuilder {
    fn debug_info(&self) -> String {
        format!(
            "GrantBuilder {{ privileges: {:?}, target: {:?}, grantee: {:?}, with_grant_option: {}, with_hierarchy: {} }}",
            self.privileges,
            self.target,
            self.grantee,
            self.with_grant_option,
            self.with_hierarchy
        )
    }

    fn summary(&self) -> String {
        let privileges_str = if self.privileges.len() == 1 {
            format!("{:?}", self.privileges[0])
        } else {
            format!("{:?}", self.privileges)
        };

        let target_str = self
            .target
            .as_ref()
            .map(|t| format!("{:?}", t))
            .unwrap_or_else(|| "none".to_string());

        let grantee_str = self
            .grantee
            .as_ref()
            .map(|g| format!("role: {}", g))
            .unwrap_or_else(|| "none".to_string());

        format!(
            "Grant {} on {} to {}",
            privileges_str, target_str, grantee_str
        )
    }
}