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
/*
Portions Copyright 2019-2021 ZomboDB, LLC.
Portions Copyright 2021-2022 Technology Concepts & Design, Inc. <support@tcdi.com>

All rights reserved.

Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/

/*! Support for writing Rust trigger functions

A "no-op" trigger that gets the current [`PgHeapTuple`][crate::PgHeapTuple],
panicking (into a PostgreSQL error) if it doesn't exist:

```rust,no_run
use pgx::prelude::*;

#[pg_trigger]
fn trigger_example<'a>(trigger: &'a PgTrigger<'a>) -> Result<
    Option<PgHeapTuple<'a, impl WhoAllocated>>,
    PgHeapTupleError,
> {
    Ok(Some(trigger.old().expect("No current HeapTuple")))
}
```

Trigger functions only accept one argument, a [`PgTrigger`], and they return a [`Result`][std::result::Result] containing
either a [`PgHeapTuple`][crate::PgHeapTuple] or any error that implements [`impl std::error::Error`][std::error::Error].

# Use from SQL

The `trigger_example` example above would generate something like the following SQL:

```sql
-- pgx-examples/triggers/src/lib.rs:25
-- triggers::trigger_example
CREATE FUNCTION "trigger_example"()
    RETURNS TRIGGER
    LANGUAGE c
    AS 'MODULE_PATHNAME', 'trigger_example_wrapper';
```

Users could then use it like so:

```sql
CREATE TABLE test (
    id serial8 NOT NULL PRIMARY KEY,
    title varchar(50),
    description text,
    payload jsonb
);

CREATE TRIGGER test_trigger
    BEFORE INSERT ON test
    FOR EACH ROW
    EXECUTE PROCEDURE trigger_example();

INSERT INTO test (title, description, payload)
    VALUES ('Fox', 'a description', '{"key": "value"}');
```

This can also be done via the [`extension_sql`][crate::extension_sql] attribute:

```rust,no_run
# use pgx::prelude::*;
#
# #[pg_trigger]
# fn trigger_example<'a>(trigger: &'a PgTrigger<'a>) -> Result<
#    Option<PgHeapTuple<'a, impl WhoAllocated>>,
#    PgHeapTupleError,
# > {
#    Ok(Some(trigger.old().expect("No current HeapTuple")))
# }
#
pgx::extension_sql!(
    r#"
CREATE TABLE test (
    id serial8 NOT NULL PRIMARY KEY,
    title varchar(50),
    description text,
    payload jsonb
);
*
CREATE TRIGGER test_trigger BEFORE INSERT ON test FOR EACH ROW EXECUTE PROCEDURE trigger_example();
INSERT INTO test (title, description, payload) VALUES ('Fox', 'a description', '{"key": "value"}');
"#,
    name = "create_trigger",
    requires = [ trigger_example ]
);
```

# Working with [`WhoAllocated`][crate::WhoAllocated]

Trigger functions can return [`PgHeapTuple`][crate::PgHeapTuple]s which are [`AllocatedByRust`][crate::AllocatedByRust]
or [`AllocatedByPostgres`][crate::AllocatedByPostgres]. In most cases, it can be inferred by the compiler using
[`impl WhoAllocated<pg_sys::HeapTupleData>>`][crate::WhoAllocated].

When it can't, the function definition permits for it to be specified:

```rust,no_run
use pgx::prelude::*;

#[pg_trigger]
fn example_allocated_by_rust<'a>(trigger: &'a PgTrigger<'a>) -> Result<
    Option<PgHeapTuple<'a, AllocatedByRust>>,
    PgHeapTupleError,
> {
    let current = trigger.old().expect("No current HeapTuple");
    Ok(Some(current.into_owned()))
}

#[pg_trigger]
fn example_allocated_by_postgres<'a>(trigger: &'a PgTrigger<'a>) -> Result<
    Option<PgHeapTuple<'a, AllocatedByPostgres>>,
    PgHeapTupleError,
> {
    let current = trigger.old().expect("No current HeapTuple");
    Ok(Some(current))
}
```

# Error Handling

Trigger functions can return any [`impl std::error::Error`][std::error::Error]. Returned errors
become PostgreSQL errors.


```rust,no_run
use pgx::prelude::*;

#[derive(thiserror::Error, Debug)]
enum CustomTriggerError {
    #[error("No current HeapTuple")]
    NoCurrentHeapTuple,
    #[error("pgx::PgHeapTupleError: {0}")]
    PgHeapTuple(PgHeapTupleError),
}

#[pg_trigger]
fn example_custom_error<'a>(trigger: &'a PgTrigger<'a>) -> Result<
    Option<PgHeapTuple<'a, impl WhoAllocated>>,
    CustomTriggerError,
> {
    trigger.old().map(|t| Some(t)).ok_or(CustomTriggerError::NoCurrentHeapTuple)
}
```

# Lifetimes

Triggers are free to use lifetimes to hone their code, the generated wrapper is as generous as possible.

```rust,no_run
use pgx::prelude::*;

#[derive(thiserror::Error, Debug)]
enum CustomTriggerError<'a> {
    #[error("No current HeapTuple")]
    NoCurrentHeapTuple,
    #[error("pgx::PgHeapTupleError: {0}")]
    PgHeapTuple(PgHeapTupleError),
    #[error("A borrowed error variant: {0}")]
    SomeStr(&'a str),
}

#[pg_trigger]
fn example_lifetimes<'a, 'b>(trigger: &'a PgTrigger<'a>) -> Result<
    Option<PgHeapTuple<'a, AllocatedByRust>>,
    CustomTriggerError<'b>,
> {
    return Err(CustomTriggerError::SomeStr("Oopsie"))
}
```

# Escape hatches

Unsafe [`pgx::pg_sys::FunctionCallInfo`][crate::pg_sys::FunctionCallInfo] and
[`pgx::pg_sys::TriggerData`][crate::pg_sys::TriggerData] (include its contained
[`pgx::pg_sys::Trigger`][crate::pg_sys::Trigger]) accessors are available..
```

 */

mod pg_trigger;
mod pg_trigger_error;
mod pg_trigger_level;
mod pg_trigger_option;
mod pg_trigger_when;
mod trigger_tuple;

pub use pg_trigger::PgTrigger;
pub use pg_trigger_error::PgTriggerError;
pub use pg_trigger_level::PgTriggerLevel;
pub use pg_trigger_option::PgTriggerOperation;
pub use pg_trigger_when::PgTriggerWhen;
pub use trigger_tuple::TriggerTuple;

use crate::{is_a, pg_sys};

/// Represents the event that fired a trigger.
///
/// It is a newtype wrapper around a `pg_sys::TriggerData.tg_event` to prevent accidental misuse and
/// provides helper methods for determining how the event was raised.
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct TriggerEvent(u32);

impl TriggerEvent {
    #[inline]
    pub fn fired_by_insert(&self) -> bool {
        trigger_fired_by_insert(self.0)
    }

    #[inline]
    pub fn fired_by_delete(&self) -> bool {
        trigger_fired_by_delete(self.0)
    }

    #[inline]
    pub fn fired_by_update(&self) -> bool {
        trigger_fired_by_update(self.0)
    }

    #[inline]
    pub fn fired_by_truncate(&self) -> bool {
        trigger_fired_by_truncate(self.0)
    }

    #[inline]
    pub fn fired_for_row(&self) -> bool {
        trigger_fired_for_row(self.0)
    }

    #[inline]
    pub fn fired_for_statement(&self) -> bool {
        trigger_fired_for_statement(self.0)
    }

    #[inline]
    pub fn fired_before(&self) -> bool {
        trigger_fired_before(self.0)
    }

    #[inline]
    pub fn fired_after(&self) -> bool {
        trigger_fired_after(self.0)
    }

    #[inline]
    pub fn fired_instead(&self) -> bool {
        trigger_fired_instead(self.0)
    }
}

#[inline]
pub unsafe fn called_as_trigger(fcinfo: pg_sys::FunctionCallInfo) -> bool {
    let fcinfo = fcinfo.as_ref().expect("fcinfo was null");
    !fcinfo.context.is_null() && is_a(fcinfo.context, pg_sys::NodeTag_T_TriggerData)
}

#[inline]
pub fn trigger_fired_by_insert(event: u32) -> bool {
    event & pg_sys::TRIGGER_EVENT_OPMASK == pg_sys::TRIGGER_EVENT_INSERT
}

#[inline]
pub fn trigger_fired_by_delete(event: u32) -> bool {
    event & pg_sys::TRIGGER_EVENT_OPMASK == pg_sys::TRIGGER_EVENT_DELETE
}

#[inline]
pub fn trigger_fired_by_update(event: u32) -> bool {
    event & pg_sys::TRIGGER_EVENT_OPMASK == pg_sys::TRIGGER_EVENT_UPDATE
}

#[inline]
pub fn trigger_fired_by_truncate(event: u32) -> bool {
    event & pg_sys::TRIGGER_EVENT_OPMASK == pg_sys::TRIGGER_EVENT_TRUNCATE
}

#[inline]
pub fn trigger_fired_for_row(event: u32) -> bool {
    event & pg_sys::TRIGGER_EVENT_ROW != 0
}

#[inline]
pub fn trigger_fired_for_statement(event: u32) -> bool {
    !trigger_fired_for_row(event)
}

#[inline]
pub fn trigger_fired_before(event: u32) -> bool {
    event & pg_sys::TRIGGER_EVENT_TIMINGMASK == pg_sys::TRIGGER_EVENT_BEFORE
}

#[inline]
pub fn trigger_fired_after(event: u32) -> bool {
    event & pg_sys::TRIGGER_EVENT_TIMINGMASK == pg_sys::TRIGGER_EVENT_AFTER
}

#[inline]
pub fn trigger_fired_instead(event: u32) -> bool {
    event & pg_sys::TRIGGER_EVENT_TIMINGMASK == pg_sys::TRIGGER_EVENT_INSTEAD
}