1use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
7pub enum TriggerTiming {
8 Before,
10 After,
12 InsteadOf,
14}
15
16impl TriggerTiming {
17 pub fn to_sql(&self) -> &'static str {
18 match self {
19 TriggerTiming::Before => "BEFORE",
20 TriggerTiming::After => "AFTER",
21 TriggerTiming::InsteadOf => "INSTEAD OF",
22 }
23 }
24}
25
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28pub enum TriggerEvent {
29 Insert,
30 Update,
31 Delete,
32 Truncate,
33}
34
35impl TriggerEvent {
36 pub fn to_sql(&self) -> &'static str {
37 match self {
38 TriggerEvent::Insert => "INSERT",
39 TriggerEvent::Update => "UPDATE",
40 TriggerEvent::Delete => "DELETE",
41 TriggerEvent::Truncate => "TRUNCATE",
42 }
43 }
44}
45
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48pub enum TriggerOrientation {
49 Row,
51 Statement,
53}
54
55impl TriggerOrientation {
56 pub fn to_sql(&self) -> &'static str {
57 match self {
58 TriggerOrientation::Row => "FOR EACH ROW",
59 TriggerOrientation::Statement => "FOR EACH STATEMENT",
60 }
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct Trigger {
67 pub name: String,
68 pub schema: Option<String>,
69 pub table_name: String,
70 pub table_schema: Option<String>,
71 pub timing: TriggerTiming,
72 pub events: Vec<TriggerEvent>,
73 pub orientation: TriggerOrientation,
74 pub function_name: String,
75 pub function_schema: Option<String>,
76 pub condition: Option<String>,
77 pub update_columns: Option<Vec<String>>, pub referencing: Option<TriggerReferencing>,
79}
80
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83pub struct TriggerReferencing {
84 pub old_table: Option<String>,
85 pub new_table: Option<String>,
86}
87
88impl Trigger {
89 pub fn new(
91 name: impl Into<String>,
92 table_name: impl Into<String>,
93 timing: TriggerTiming,
94 events: Vec<TriggerEvent>,
95 function_name: impl Into<String>,
96 ) -> Self {
97 Self {
98 name: name.into(),
99 schema: None,
100 table_name: table_name.into(),
101 table_schema: None,
102 timing,
103 events,
104 orientation: TriggerOrientation::Row,
105 function_name: function_name.into(),
106 function_schema: None,
107 condition: None,
108 update_columns: None,
109 referencing: None,
110 }
111 }
112
113 pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
115 self.schema = Some(schema.into());
116 self
117 }
118
119 pub fn with_table_schema(mut self, schema: impl Into<String>) -> Self {
121 self.table_schema = Some(schema.into());
122 self
123 }
124
125 pub fn with_orientation(mut self, orientation: TriggerOrientation) -> Self {
127 self.orientation = orientation;
128 self
129 }
130
131 pub fn with_function_schema(mut self, schema: impl Into<String>) -> Self {
133 self.function_schema = Some(schema.into());
134 self
135 }
136
137 pub fn with_condition(mut self, condition: impl Into<String>) -> Self {
139 self.condition = Some(condition.into());
140 self
141 }
142
143 pub fn with_update_columns(mut self, columns: Vec<String>) -> Self {
145 self.update_columns = Some(columns);
146 self
147 }
148
149 pub fn with_referencing(mut self, referencing: TriggerReferencing) -> Self {
151 self.referencing = Some(referencing);
152 self
153 }
154
155 pub fn qualified_name(&self) -> String {
157 if let Some(ref schema) = self.schema {
158 format!("\"{}\".\"{}\"", schema, self.name)
159 } else {
160 format!("\"{}\"", self.name)
161 }
162 }
163
164 pub fn qualified_table_name(&self) -> String {
166 if let Some(ref schema) = self.table_schema {
167 format!("\"{}\".\"{}\"", schema, self.table_name)
168 } else {
169 format!("\"{}\"", self.table_name)
170 }
171 }
172
173 pub fn qualified_function_name(&self) -> String {
175 if let Some(ref schema) = self.function_schema {
176 format!("\"{}\".\"{}\"", schema, self.function_name)
177 } else {
178 format!("\"{}\"", self.function_name)
179 }
180 }
181
182 pub fn generate_create_ddl(&self) -> String {
184 let mut ddl = String::with_capacity(512);
185
186 ddl.push_str("CREATE TRIGGER ");
188 ddl.push_str(&format!("\"{}\"", self.name));
189 ddl.push(' ');
190
191 ddl.push_str(self.timing.to_sql());
193 ddl.push(' ');
194
195 let events: Vec<String> = self
197 .events
198 .iter()
199 .map(|e| {
200 if e == &TriggerEvent::Update {
201 if let Some(ref cols) = self.update_columns {
202 format!(
203 "{} OF {}",
204 e.to_sql(),
205 cols.iter()
206 .map(|c| format!("\"{}\"", c))
207 .collect::<Vec<_>>()
208 .join(", ")
209 )
210 } else {
211 e.to_sql().to_string()
212 }
213 } else {
214 e.to_sql().to_string()
215 }
216 })
217 .collect();
218 ddl.push_str(&events.join(" OR "));
219
220 ddl.push_str(" ON ");
222 ddl.push_str(&self.qualified_table_name());
223
224 if let Some(ref referencing) = self.referencing {
226 ddl.push_str(" REFERENCING");
227 if let Some(ref old_table) = referencing.old_table {
228 ddl.push_str(&format!(" OLD TABLE AS \"{}\"", old_table));
229 }
230 if let Some(ref new_table) = referencing.new_table {
231 ddl.push_str(&format!(" NEW TABLE AS \"{}\"", new_table));
232 }
233 }
234
235 ddl.push(' ');
237 ddl.push_str(self.orientation.to_sql());
238
239 if let Some(ref condition) = self.condition {
241 ddl.push_str(" WHEN (");
242 ddl.push_str(condition);
243 ddl.push(')');
244 }
245
246 ddl.push_str(" EXECUTE FUNCTION ");
248 ddl.push_str(&self.qualified_function_name());
249 ddl.push_str("()");
250
251 ddl.push(';');
252 ddl
253 }
254
255 pub fn generate_drop_ddl(&self) -> String {
257 format!(
258 "DROP TRIGGER IF EXISTS \"{}\" ON {};",
259 self.name,
260 self.qualified_table_name()
261 )
262 }
263
264 pub fn generate_disable_ddl(&self) -> String {
266 format!(
267 "ALTER TABLE {} DISABLE TRIGGER \"{}\";",
268 self.qualified_table_name(),
269 self.name
270 )
271 }
272
273 pub fn generate_enable_ddl(&self) -> String {
275 format!(
276 "ALTER TABLE {} ENABLE TRIGGER \"{}\";",
277 self.qualified_table_name(),
278 self.name
279 )
280 }
281
282 pub fn fires_on_event(&self, event: &TriggerEvent) -> bool {
284 self.events.contains(event)
285 }
286
287 pub fn is_row_level(&self) -> bool {
289 matches!(self.orientation, TriggerOrientation::Row)
290 }
291
292 pub fn is_statement_level(&self) -> bool {
294 matches!(self.orientation, TriggerOrientation::Statement)
295 }
296
297 pub fn has_condition(&self) -> bool {
299 self.condition.is_some()
300 }
301
302 pub fn events_as_string(&self) -> String {
304 self.events
305 .iter()
306 .map(|e| e.to_sql())
307 .collect::<Vec<_>>()
308 .join(", ")
309 }
310}
311
312impl TriggerReferencing {
313 pub fn new() -> Self {
315 Self {
316 old_table: None,
317 new_table: None,
318 }
319 }
320
321 pub fn with_old_table(mut self, name: impl Into<String>) -> Self {
323 self.old_table = Some(name.into());
324 self
325 }
326
327 pub fn with_new_table(mut self, name: impl Into<String>) -> Self {
329 self.new_table = Some(name.into());
330 self
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337
338 #[test]
339 fn test_trigger_creation() {
340 let trigger = Trigger::new(
341 "update_modified_time",
342 "users",
343 TriggerTiming::Before,
344 vec![TriggerEvent::Update],
345 "update_modified_time_func",
346 );
347
348 assert_eq!(trigger.name, "update_modified_time");
349 assert_eq!(trigger.table_name, "users");
350 assert_eq!(trigger.timing, TriggerTiming::Before);
351 assert_eq!(trigger.events, vec![TriggerEvent::Update]);
352 assert_eq!(trigger.function_name, "update_modified_time_func");
353 assert_eq!(trigger.orientation, TriggerOrientation::Row);
354 }
355
356 #[test]
357 fn test_trigger_qualified_names() {
358 let trigger = Trigger::new(
359 "test_trigger",
360 "test_table",
361 TriggerTiming::After,
362 vec![TriggerEvent::Insert],
363 "test_function",
364 )
365 .with_schema("public")
366 .with_table_schema("app")
367 .with_function_schema("utils");
368
369 assert_eq!(trigger.qualified_name(), "\"public\".\"test_trigger\"");
370 assert_eq!(trigger.qualified_table_name(), "\"app\".\"test_table\"");
371 assert_eq!(
372 trigger.qualified_function_name(),
373 "\"utils\".\"test_function\""
374 );
375 }
376
377 #[test]
378 fn test_trigger_ddl_generation() {
379 let trigger = Trigger::new(
380 "audit_trigger",
381 "users",
382 TriggerTiming::After,
383 vec![
384 TriggerEvent::Insert,
385 TriggerEvent::Update,
386 TriggerEvent::Delete,
387 ],
388 "audit_function",
389 )
390 .with_condition("NEW.id IS NOT NULL");
391
392 let ddl = trigger.generate_create_ddl();
393
394 assert!(ddl.contains("CREATE TRIGGER \"audit_trigger\""));
395 assert!(ddl.contains("AFTER INSERT OR UPDATE OR DELETE"));
396 assert!(ddl.contains("ON \"users\""));
397 assert!(ddl.contains("FOR EACH ROW"));
398 assert!(ddl.contains("WHEN (NEW.id IS NOT NULL)"));
399 assert!(ddl.contains("EXECUTE FUNCTION \"audit_function\"()"));
400 }
401
402 #[test]
403 fn test_trigger_update_of_columns() {
404 let trigger = Trigger::new(
405 "email_update_trigger",
406 "users",
407 TriggerTiming::Before,
408 vec![TriggerEvent::Update],
409 "validate_email",
410 )
411 .with_update_columns(vec!["email".to_string(), "username".to_string()]);
412
413 let ddl = trigger.generate_create_ddl();
414
415 assert!(ddl.contains("UPDATE OF \"email\", \"username\""));
416 }
417
418 #[test]
419 fn test_trigger_referencing() {
420 let referencing = TriggerReferencing::new()
421 .with_old_table("old_data")
422 .with_new_table("new_data");
423
424 let trigger = Trigger::new(
425 "batch_audit_trigger",
426 "users",
427 TriggerTiming::After,
428 vec![TriggerEvent::Update],
429 "batch_audit_function",
430 )
431 .with_orientation(TriggerOrientation::Statement)
432 .with_referencing(referencing);
433
434 let ddl = trigger.generate_create_ddl();
435
436 assert!(ddl.contains("FOR EACH STATEMENT"));
437 assert!(ddl.contains("REFERENCING OLD TABLE AS \"old_data\" NEW TABLE AS \"new_data\""));
438 }
439
440 #[test]
441 fn test_trigger_drop_ddl() {
442 let trigger = Trigger::new(
443 "test_trigger",
444 "test_table",
445 TriggerTiming::Before,
446 vec![TriggerEvent::Insert],
447 "test_function",
448 );
449
450 let drop_ddl = trigger.generate_drop_ddl();
451 assert_eq!(
452 drop_ddl,
453 "DROP TRIGGER IF EXISTS \"test_trigger\" ON \"test_table\";"
454 );
455 }
456
457 #[test]
458 fn test_trigger_enable_disable() {
459 let trigger = Trigger::new(
460 "test_trigger",
461 "test_table",
462 TriggerTiming::Before,
463 vec![TriggerEvent::Insert],
464 "test_function",
465 );
466
467 let disable_ddl = trigger.generate_disable_ddl();
468 let enable_ddl = trigger.generate_enable_ddl();
469
470 assert_eq!(
471 disable_ddl,
472 "ALTER TABLE \"test_table\" DISABLE TRIGGER \"test_trigger\";"
473 );
474 assert_eq!(
475 enable_ddl,
476 "ALTER TABLE \"test_table\" ENABLE TRIGGER \"test_trigger\";"
477 );
478 }
479
480 #[test]
481 fn test_trigger_utility_methods() {
482 let trigger = Trigger::new(
483 "test_trigger",
484 "test_table",
485 TriggerTiming::Before,
486 vec![TriggerEvent::Insert, TriggerEvent::Update],
487 "test_function",
488 )
489 .with_condition("NEW.active = true")
490 .with_orientation(TriggerOrientation::Statement);
491
492 assert!(trigger.fires_on_event(&TriggerEvent::Insert));
493 assert!(trigger.fires_on_event(&TriggerEvent::Update));
494 assert!(!trigger.fires_on_event(&TriggerEvent::Delete));
495
496 assert!(!trigger.is_row_level());
497 assert!(trigger.is_statement_level());
498 assert!(trigger.has_condition());
499
500 assert_eq!(trigger.events_as_string(), "INSERT, UPDATE");
501 }
502}