]> begriffs open source - ai-pg/blob - full-docs/txt/event-trigger-example.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / event-trigger-example.txt
1
2 38.3. A Complete Event Trigger Example #
3
4    Here is a very simple example of an event trigger function written in
5    C. (Examples of triggers written in procedural languages can be found
6    in the documentation of the procedural languages.)
7
8    The function noddl raises an exception each time it is called. The
9    event trigger definition associated the function with the
10    ddl_command_start event. The effect is that all DDL commands (with the
11    exceptions mentioned in Section 38.1) are prevented from running.
12
13    This is the source code of the trigger function:
14 #include "postgres.h"
15
16 #include "commands/event_trigger.h"
17 #include "fmgr.h"
18
19 PG_MODULE_MAGIC;
20
21 PG_FUNCTION_INFO_V1(noddl);
22
23 Datum
24 noddl(PG_FUNCTION_ARGS)
25 {
26     EventTriggerData *trigdata;
27
28     if (!CALLED_AS_EVENT_TRIGGER(fcinfo))  /* internal error */
29         elog(ERROR, "not fired by event trigger manager");
30
31     trigdata = (EventTriggerData *) fcinfo->context;
32
33     ereport(ERROR,
34             (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
35              errmsg("command \"%s\" denied",
36                     GetCommandTagName(trigdata->tag))));
37
38     PG_RETURN_NULL();
39 }
40
41    After you have compiled the source code (see Section 36.10.5), declare
42    the function and the triggers:
43 CREATE FUNCTION noddl() RETURNS event_trigger
44     AS 'noddl' LANGUAGE C;
45
46 CREATE EVENT TRIGGER noddl ON ddl_command_start
47     EXECUTE FUNCTION noddl();
48
49    Now you can test the operation of the trigger:
50 =# \dy
51                      List of event triggers
52  Name  |       Event       | Owner | Enabled | Function | Tags
53 -------+-------------------+-------+---------+----------+------
54  noddl | ddl_command_start | dim   | enabled | noddl    |
55 (1 row)
56
57 =# CREATE TABLE foo(id serial);
58 ERROR:  command "CREATE TABLE" denied
59
60    In this situation, in order to be able to run some DDL commands when
61    you need to do so, you have to either drop the event trigger or disable
62    it. It can be convenient to disable the trigger for only the duration
63    of a transaction:
64 BEGIN;
65 ALTER EVENT TRIGGER noddl DISABLE;
66 CREATE TABLE foo (id serial);
67 ALTER EVENT TRIGGER noddl ENABLE;
68 COMMIT;
69
70    (Recall that DDL commands on event triggers themselves are not affected
71    by event triggers.)