ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! PostgreSQL triggers support for Ignis

use serde::{Deserialize, Serialize};

/// Trigger timing - when the trigger fires
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TriggerTiming {
    /// Fire before the triggering event
    Before,
    /// Fire after the triggering event  
    After,
    /// Fire instead of the triggering event (views only)
    InsteadOf,
}

impl TriggerTiming {
    pub fn to_sql(&self) -> &'static str {
        match self {
            TriggerTiming::Before => "BEFORE",
            TriggerTiming::After => "AFTER",
            TriggerTiming::InsteadOf => "INSTEAD OF",
        }
    }
}

/// Trigger events - what operations trigger the trigger
#[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",
        }
    }
}

/// Trigger orientation - row-level vs statement-level
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TriggerOrientation {
    /// Fire once per affected row
    Row,
    /// Fire once per statement
    Statement,
}

impl TriggerOrientation {
    pub fn to_sql(&self) -> &'static str {
        match self {
            TriggerOrientation::Row => "FOR EACH ROW",
            TriggerOrientation::Statement => "FOR EACH STATEMENT",
        }
    }
}

/// Represents a PostgreSQL trigger
#[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>>, // For UPDATE OF specific columns
    pub referencing: Option<TriggerReferencing>,
}

/// Referencing clause for transition tables (PostgreSQL 10+)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TriggerReferencing {
    pub old_table: Option<String>,
    pub new_table: Option<String>,
}

impl Trigger {
    /// Create a new 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,
        }
    }

    /// Set schema
    pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Set table schema
    pub fn with_table_schema(mut self, schema: impl Into<String>) -> Self {
        self.table_schema = Some(schema.into());
        self
    }

    /// Set trigger orientation
    pub fn with_orientation(mut self, orientation: TriggerOrientation) -> Self {
        self.orientation = orientation;
        self
    }

    /// Set function schema
    pub fn with_function_schema(mut self, schema: impl Into<String>) -> Self {
        self.function_schema = Some(schema.into());
        self
    }

    /// Add a condition (WHEN clause)
    pub fn with_condition(mut self, condition: impl Into<String>) -> Self {
        self.condition = Some(condition.into());
        self
    }

    /// Set specific columns for UPDATE triggers (UPDATE OF columns)
    pub fn with_update_columns(mut self, columns: Vec<String>) -> Self {
        self.update_columns = Some(columns);
        self
    }

    /// Set transition table references
    pub fn with_referencing(mut self, referencing: TriggerReferencing) -> Self {
        self.referencing = Some(referencing);
        self
    }

    /// Get the fully qualified trigger name
    pub fn qualified_name(&self) -> String {
        if let Some(ref schema) = self.schema {
            format!("\"{}\".\"{}\"", schema, self.name)
        } else {
            format!("\"{}\"", self.name)
        }
    }

    /// Get the fully qualified table 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)
        }
    }

    /// Get the fully qualified function 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)
        }
    }

    /// Generate CREATE TRIGGER DDL
    pub fn generate_create_ddl(&self) -> String {
        let mut ddl = String::with_capacity(512);

        // CREATE TRIGGER
        ddl.push_str("CREATE TRIGGER ");
        ddl.push_str(&format!("\"{}\"", self.name));
        ddl.push(' ');

        // TIMING
        ddl.push_str(self.timing.to_sql());
        ddl.push(' ');

        // EVENTS
        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 "));

        // ON table
        ddl.push_str(" ON ");
        ddl.push_str(&self.qualified_table_name());

        // REFERENCING (PostgreSQL 10+)
        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));
            }
        }

        // FOR EACH ROW/STATEMENT
        ddl.push(' ');
        ddl.push_str(self.orientation.to_sql());

        // WHEN condition
        if let Some(ref condition) = self.condition {
            ddl.push_str(" WHEN (");
            ddl.push_str(condition);
            ddl.push(')');
        }

        // EXECUTE FUNCTION
        ddl.push_str(" EXECUTE FUNCTION ");
        ddl.push_str(&self.qualified_function_name());
        ddl.push_str("()");

        ddl.push(';');
        ddl
    }

    /// Generate DROP TRIGGER DDL
    pub fn generate_drop_ddl(&self) -> String {
        format!(
            "DROP TRIGGER IF EXISTS \"{}\" ON {};",
            self.name,
            self.qualified_table_name()
        )
    }

    /// Generate DDL to disable trigger
    pub fn generate_disable_ddl(&self) -> String {
        format!(
            "ALTER TABLE {} DISABLE TRIGGER \"{}\";",
            self.qualified_table_name(),
            self.name
        )
    }

    /// Generate DDL to enable trigger
    pub fn generate_enable_ddl(&self) -> String {
        format!(
            "ALTER TABLE {} ENABLE TRIGGER \"{}\";",
            self.qualified_table_name(),
            self.name
        )
    }

    /// Check if this trigger fires on a specific event
    pub fn fires_on_event(&self, event: &TriggerEvent) -> bool {
        self.events.contains(event)
    }

    /// Check if this trigger is row-level
    pub fn is_row_level(&self) -> bool {
        matches!(self.orientation, TriggerOrientation::Row)
    }

    /// Check if this trigger is statement-level
    pub fn is_statement_level(&self) -> bool {
        matches!(self.orientation, TriggerOrientation::Statement)
    }

    /// Check if this trigger has a condition
    pub fn has_condition(&self) -> bool {
        self.condition.is_some()
    }

    /// Get the events as a comma-separated string
    pub fn events_as_string(&self) -> String {
        self.events
            .iter()
            .map(|e| e.to_sql())
            .collect::<Vec<_>>()
            .join(", ")
    }
}

impl TriggerReferencing {
    /// Create new referencing clause
    pub fn new() -> Self {
        Self {
            old_table: None,
            new_table: None,
        }
    }

    /// Set old table alias
    pub fn with_old_table(mut self, name: impl Into<String>) -> Self {
        self.old_table = Some(name.into());
        self
    }

    /// Set new table alias  
    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");
    }
}