use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TriggerTiming {
Before,
After,
InsteadOf,
}
impl TriggerTiming {
pub fn to_sql(&self) -> &'static str {
match self {
TriggerTiming::Before => "BEFORE",
TriggerTiming::After => "AFTER",
TriggerTiming::InsteadOf => "INSTEAD OF",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TriggerEvent {
Insert,
Update,
Delete,
Truncate,
}
impl TriggerEvent {
pub fn to_sql(&self) -> &'static str {
match self {
TriggerEvent::Insert => "INSERT",
TriggerEvent::Update => "UPDATE",
TriggerEvent::Delete => "DELETE",
TriggerEvent::Truncate => "TRUNCATE",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TriggerOrientation {
Row,
Statement,
}
impl TriggerOrientation {
pub fn to_sql(&self) -> &'static str {
match self {
TriggerOrientation::Row => "FOR EACH ROW",
TriggerOrientation::Statement => "FOR EACH STATEMENT",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Trigger {
pub name: String,
pub schema: Option<String>,
pub table_name: String,
pub table_schema: Option<String>,
pub timing: TriggerTiming,
pub events: Vec<TriggerEvent>,
pub orientation: TriggerOrientation,
pub function_name: String,
pub function_schema: Option<String>,
pub condition: Option<String>,
pub update_columns: Option<Vec<String>>, pub referencing: Option<TriggerReferencing>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TriggerReferencing {
pub old_table: Option<String>,
pub new_table: Option<String>,
}
impl Trigger {
pub fn new(
name: impl Into<String>,
table_name: impl Into<String>,
timing: TriggerTiming,
events: Vec<TriggerEvent>,
function_name: impl Into<String>,
) -> Self {
Self {
name: name.into(),
schema: None,
table_name: table_name.into(),
table_schema: None,
timing,
events,
orientation: TriggerOrientation::Row,
function_name: function_name.into(),
function_schema: None,
condition: None,
update_columns: None,
referencing: None,
}
}
pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn with_table_schema(mut self, schema: impl Into<String>) -> Self {
self.table_schema = Some(schema.into());
self
}
pub fn with_orientation(mut self, orientation: TriggerOrientation) -> Self {
self.orientation = orientation;
self
}
pub fn with_function_schema(mut self, schema: impl Into<String>) -> Self {
self.function_schema = Some(schema.into());
self
}
pub fn with_condition(mut self, condition: impl Into<String>) -> Self {
self.condition = Some(condition.into());
self
}
pub fn with_update_columns(mut self, columns: Vec<String>) -> Self {
self.update_columns = Some(columns);
self
}
pub fn with_referencing(mut self, referencing: TriggerReferencing) -> Self {
self.referencing = Some(referencing);
self
}
pub fn qualified_name(&self) -> String {
if let Some(ref schema) = self.schema {
format!("\"{}\".\"{}\"", schema, self.name)
} else {
format!("\"{}\"", self.name)
}
}
pub fn qualified_table_name(&self) -> String {
if let Some(ref schema) = self.table_schema {
format!("\"{}\".\"{}\"", schema, self.table_name)
} else {
format!("\"{}\"", self.table_name)
}
}
pub fn qualified_function_name(&self) -> String {
if let Some(ref schema) = self.function_schema {
format!("\"{}\".\"{}\"", schema, self.function_name)
} else {
format!("\"{}\"", self.function_name)
}
}
pub fn generate_create_ddl(&self) -> String {
let mut ddl = String::with_capacity(512);
ddl.push_str("CREATE TRIGGER ");
ddl.push_str(&format!("\"{}\"", self.name));
ddl.push(' ');
ddl.push_str(self.timing.to_sql());
ddl.push(' ');
let events: Vec<String> = self
.events
.iter()
.map(|e| {
if e == &TriggerEvent::Update {
if let Some(ref cols) = self.update_columns {
format!(
"{} OF {}",
e.to_sql(),
cols.iter()
.map(|c| format!("\"{}\"", c))
.collect::<Vec<_>>()
.join(", ")
)
} else {
e.to_sql().to_string()
}
} else {
e.to_sql().to_string()
}
})
.collect();
ddl.push_str(&events.join(" OR "));
ddl.push_str(" ON ");
ddl.push_str(&self.qualified_table_name());
if let Some(ref referencing) = self.referencing {
ddl.push_str(" REFERENCING");
if let Some(ref old_table) = referencing.old_table {
ddl.push_str(&format!(" OLD TABLE AS \"{}\"", old_table));
}
if let Some(ref new_table) = referencing.new_table {
ddl.push_str(&format!(" NEW TABLE AS \"{}\"", new_table));
}
}
ddl.push(' ');
ddl.push_str(self.orientation.to_sql());
if let Some(ref condition) = self.condition {
ddl.push_str(" WHEN (");
ddl.push_str(condition);
ddl.push(')');
}
ddl.push_str(" EXECUTE FUNCTION ");
ddl.push_str(&self.qualified_function_name());
ddl.push_str("()");
ddl.push(';');
ddl
}
pub fn generate_drop_ddl(&self) -> String {
format!(
"DROP TRIGGER IF EXISTS \"{}\" ON {};",
self.name,
self.qualified_table_name()
)
}
pub fn generate_disable_ddl(&self) -> String {
format!(
"ALTER TABLE {} DISABLE TRIGGER \"{}\";",
self.qualified_table_name(),
self.name
)
}
pub fn generate_enable_ddl(&self) -> String {
format!(
"ALTER TABLE {} ENABLE TRIGGER \"{}\";",
self.qualified_table_name(),
self.name
)
}
pub fn fires_on_event(&self, event: &TriggerEvent) -> bool {
self.events.contains(event)
}
pub fn is_row_level(&self) -> bool {
matches!(self.orientation, TriggerOrientation::Row)
}
pub fn is_statement_level(&self) -> bool {
matches!(self.orientation, TriggerOrientation::Statement)
}
pub fn has_condition(&self) -> bool {
self.condition.is_some()
}
pub fn events_as_string(&self) -> String {
self.events
.iter()
.map(|e| e.to_sql())
.collect::<Vec<_>>()
.join(", ")
}
}
impl TriggerReferencing {
pub fn new() -> Self {
Self {
old_table: None,
new_table: None,
}
}
pub fn with_old_table(mut self, name: impl Into<String>) -> Self {
self.old_table = Some(name.into());
self
}
pub fn with_new_table(mut self, name: impl Into<String>) -> Self {
self.new_table = Some(name.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_trigger_creation() {
let trigger = Trigger::new(
"update_modified_time",
"users",
TriggerTiming::Before,
vec![TriggerEvent::Update],
"update_modified_time_func",
);
assert_eq!(trigger.name, "update_modified_time");
assert_eq!(trigger.table_name, "users");
assert_eq!(trigger.timing, TriggerTiming::Before);
assert_eq!(trigger.events, vec![TriggerEvent::Update]);
assert_eq!(trigger.function_name, "update_modified_time_func");
assert_eq!(trigger.orientation, TriggerOrientation::Row);
}
#[test]
fn test_trigger_qualified_names() {
let trigger = Trigger::new(
"test_trigger",
"test_table",
TriggerTiming::After,
vec![TriggerEvent::Insert],
"test_function",
)
.with_schema("public")
.with_table_schema("app")
.with_function_schema("utils");
assert_eq!(trigger.qualified_name(), "\"public\".\"test_trigger\"");
assert_eq!(trigger.qualified_table_name(), "\"app\".\"test_table\"");
assert_eq!(
trigger.qualified_function_name(),
"\"utils\".\"test_function\""
);
}
#[test]
fn test_trigger_ddl_generation() {
let trigger = Trigger::new(
"audit_trigger",
"users",
TriggerTiming::After,
vec![
TriggerEvent::Insert,
TriggerEvent::Update,
TriggerEvent::Delete,
],
"audit_function",
)
.with_condition("NEW.id IS NOT NULL");
let ddl = trigger.generate_create_ddl();
assert!(ddl.contains("CREATE TRIGGER \"audit_trigger\""));
assert!(ddl.contains("AFTER INSERT OR UPDATE OR DELETE"));
assert!(ddl.contains("ON \"users\""));
assert!(ddl.contains("FOR EACH ROW"));
assert!(ddl.contains("WHEN (NEW.id IS NOT NULL)"));
assert!(ddl.contains("EXECUTE FUNCTION \"audit_function\"()"));
}
#[test]
fn test_trigger_update_of_columns() {
let trigger = Trigger::new(
"email_update_trigger",
"users",
TriggerTiming::Before,
vec![TriggerEvent::Update],
"validate_email",
)
.with_update_columns(vec!["email".to_string(), "username".to_string()]);
let ddl = trigger.generate_create_ddl();
assert!(ddl.contains("UPDATE OF \"email\", \"username\""));
}
#[test]
fn test_trigger_referencing() {
let referencing = TriggerReferencing::new()
.with_old_table("old_data")
.with_new_table("new_data");
let trigger = Trigger::new(
"batch_audit_trigger",
"users",
TriggerTiming::After,
vec![TriggerEvent::Update],
"batch_audit_function",
)
.with_orientation(TriggerOrientation::Statement)
.with_referencing(referencing);
let ddl = trigger.generate_create_ddl();
assert!(ddl.contains("FOR EACH STATEMENT"));
assert!(ddl.contains("REFERENCING OLD TABLE AS \"old_data\" NEW TABLE AS \"new_data\""));
}
#[test]
fn test_trigger_drop_ddl() {
let trigger = Trigger::new(
"test_trigger",
"test_table",
TriggerTiming::Before,
vec![TriggerEvent::Insert],
"test_function",
);
let drop_ddl = trigger.generate_drop_ddl();
assert_eq!(
drop_ddl,
"DROP TRIGGER IF EXISTS \"test_trigger\" ON \"test_table\";"
);
}
#[test]
fn test_trigger_enable_disable() {
let trigger = Trigger::new(
"test_trigger",
"test_table",
TriggerTiming::Before,
vec![TriggerEvent::Insert],
"test_function",
);
let disable_ddl = trigger.generate_disable_ddl();
let enable_ddl = trigger.generate_enable_ddl();
assert_eq!(
disable_ddl,
"ALTER TABLE \"test_table\" DISABLE TRIGGER \"test_trigger\";"
);
assert_eq!(
enable_ddl,
"ALTER TABLE \"test_table\" ENABLE TRIGGER \"test_trigger\";"
);
}
#[test]
fn test_trigger_utility_methods() {
let trigger = Trigger::new(
"test_trigger",
"test_table",
TriggerTiming::Before,
vec![TriggerEvent::Insert, TriggerEvent::Update],
"test_function",
)
.with_condition("NEW.active = true")
.with_orientation(TriggerOrientation::Statement);
assert!(trigger.fires_on_event(&TriggerEvent::Insert));
assert!(trigger.fires_on_event(&TriggerEvent::Update));
assert!(!trigger.fires_on_event(&TriggerEvent::Delete));
assert!(!trigger.is_row_level());
assert!(trigger.is_statement_level());
assert!(trigger.has_condition());
assert_eq!(trigger.events_as_string(), "INSERT, UPDATE");
}
}