pgx/trigger_support/
pg_trigger_option.rs

1use crate::pg_sys;
2use crate::trigger_support::{PgTriggerError, TriggerEvent};
3
4/// The operation for which the trigger was fired
5///
6/// Maps from a `TEXT` of `INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE`.
7///
8/// Can be calculated from a `pgx_pg_sys::TriggerEvent`.
9// Postgres constants: https://cs.github.com/postgres/postgres/blob/36d4efe779bfc7190ea1c1cf8deb0d945b726663/src/include/commands/trigger.h#L92
10// Postgres defines: https://cs.github.com/postgres/postgres/blob/36d4efe779bfc7190ea1c1cf8deb0d945b726663/src/include/commands/trigger.h#L92
11pub enum PgTriggerOperation {
12    /// `INSERT`
13    Insert,
14    /// `UPDATE`
15    Update,
16    /// `DELETE`
17    Delete,
18    /// `TRUNCATE`
19    Truncate,
20}
21
22impl TryFrom<TriggerEvent> for PgTriggerOperation {
23    type Error = PgTriggerError;
24    fn try_from(event: TriggerEvent) -> Result<Self, Self::Error> {
25        match event.0 & pg_sys::TRIGGER_EVENT_OPMASK {
26            pg_sys::TRIGGER_EVENT_INSERT => Ok(Self::Insert),
27            pg_sys::TRIGGER_EVENT_DELETE => Ok(Self::Delete),
28            pg_sys::TRIGGER_EVENT_UPDATE => Ok(Self::Update),
29            pg_sys::TRIGGER_EVENT_TRUNCATE => Ok(Self::Truncate),
30            v => Err(PgTriggerError::InvalidPgTriggerOperation(v)),
31        }
32    }
33}
34
35impl ToString for PgTriggerOperation {
36    fn to_string(&self) -> String {
37        match self {
38            PgTriggerOperation::Insert => "INSERT",
39            PgTriggerOperation::Update => "UPDATE",
40            PgTriggerOperation::Delete => "DELETE",
41            PgTriggerOperation::Truncate => "TRUNCATE",
42        }
43        .to_string()
44    }
45}