pgmt 0.4.8

PostgreSQL migration tool that keeps your schema files as the source of truth
Documentation
//! View operations for schema migrations

use super::OperationKind;
use super::comments::{CommentOperation, CommentTarget};
use crate::catalog::id::DbObjectId;
use crate::render::quote_ident;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ViewOption {
    SecurityInvoker,
    SecurityBarrier,
}

impl ViewOption {
    pub fn as_str(&self) -> &'static str {
        match self {
            ViewOption::SecurityInvoker => "security_invoker",
            ViewOption::SecurityBarrier => "security_barrier",
        }
    }
}

#[derive(Debug, Clone)]
pub enum ViewOperation {
    Create {
        schema: String,
        name: String,
        definition: String,
        security_invoker: bool,
        security_barrier: bool,
    },
    Drop {
        schema: String,
        name: String,
    },
    Replace {
        schema: String,
        name: String,
        definition: String,
        security_invoker: bool,
        security_barrier: bool,
    },
    SetOption {
        schema: String,
        name: String,
        option: ViewOption,
        enabled: bool,
    },
    Comment(CommentOperation<ViewIdentifier>),
    ColumnComment(CommentOperation<ViewColumnIdentifier>),
}

impl ViewOperation {
    pub fn operation_kind(&self) -> OperationKind {
        match self {
            Self::Create { .. } => OperationKind::Create,
            Self::Drop { .. } => OperationKind::Drop,
            Self::Replace { .. } => OperationKind::Alter,
            Self::SetOption { .. } => OperationKind::Alter,
            Self::Comment(_) => OperationKind::Alter,
            Self::ColumnComment(_) => OperationKind::Alter,
        }
    }
}

#[derive(Debug, Clone)]
pub struct ViewIdentifier {
    pub schema: String,
    pub name: String,
}

impl CommentTarget for ViewIdentifier {
    const OBJECT_TYPE: &'static str = "VIEW";

    fn identifier(&self) -> String {
        format!("{}.{}", quote_ident(&self.schema), quote_ident(&self.name))
    }

    fn db_object_id(&self) -> DbObjectId {
        DbObjectId::View {
            schema: self.schema.clone(),
            name: self.name.clone(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ViewColumnIdentifier {
    pub schema: String,
    pub view: String,
    pub name: String,
}

impl CommentTarget for ViewColumnIdentifier {
    const OBJECT_TYPE: &'static str = "COLUMN";

    fn identifier(&self) -> String {
        format!(
            "{}.{}.{}",
            quote_ident(&self.schema),
            quote_ident(&self.view),
            quote_ident(&self.name)
        )
    }

    fn db_object_id(&self) -> DbObjectId {
        DbObjectId::View {
            schema: self.schema.clone(),
            name: self.view.clone(),
        }
    }
}