2 * contrib/spi/insert_username.c
4 * insert user name in response to a trigger
5 * usage: insert_username (column_name)
9 #include "access/htup_details.h"
10 #include "catalog/pg_type.h"
11 #include "commands/trigger.h"
12 #include "executor/spi.h"
13 #include "miscadmin.h"
14 #include "utils/builtins.h"
15 #include "utils/rel.h"
19 PG_FUNCTION_INFO_V1(insert_username
);
22 insert_username(PG_FUNCTION_ARGS
)
24 TriggerData
*trigdata
= (TriggerData
*) fcinfo
->context
;
25 Trigger
*trigger
; /* to get trigger name */
26 int nargs
; /* # of arguments */
27 Datum newval
; /* new value of column */
28 bool newnull
; /* null flag */
29 char **args
; /* arguments */
30 char *relname
; /* triggered relation name */
31 Relation rel
; /* triggered relation */
32 HeapTuple rettuple
= NULL
;
33 TupleDesc tupdesc
; /* tuple description */
36 /* sanity checks from autoinc.c */
37 if (!CALLED_AS_TRIGGER(fcinfo
))
39 elog(ERROR
, "insert_username: not fired by trigger manager");
40 if (!TRIGGER_FIRED_FOR_ROW(trigdata
->tg_event
))
42 elog(ERROR
, "insert_username: must be fired for row");
43 if (!TRIGGER_FIRED_BEFORE(trigdata
->tg_event
))
45 elog(ERROR
, "insert_username: must be fired before event");
47 if (TRIGGER_FIRED_BY_INSERT(trigdata
->tg_event
))
48 rettuple
= trigdata
->tg_trigtuple
;
49 else if (TRIGGER_FIRED_BY_UPDATE(trigdata
->tg_event
))
50 rettuple
= trigdata
->tg_newtuple
;
53 elog(ERROR
, "insert_username: cannot process DELETE events");
55 rel
= trigdata
->tg_relation
;
56 relname
= SPI_getrelname(rel
);
58 trigger
= trigdata
->tg_trigger
;
60 nargs
= trigger
->tgnargs
;
63 elog(ERROR
, "insert_username (%s): one argument was expected", relname
);
65 args
= trigger
->tgargs
;
66 tupdesc
= rel
->rd_att
;
68 attnum
= SPI_fnumber(tupdesc
, args
[0]);
72 (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION
),
73 errmsg("\"%s\" has no attribute \"%s\"", relname
, args
[0])));
75 if (SPI_gettypeid(tupdesc
, attnum
) != TEXTOID
)
77 (errcode(ERRCODE_TRIGGERED_ACTION_EXCEPTION
),
78 errmsg("attribute \"%s\" of \"%s\" must be type TEXT",
81 /* create fields containing name */
82 newval
= CStringGetTextDatum(GetUserNameFromId(GetUserId(), false));
85 /* construct new tuple */
86 rettuple
= heap_modify_tuple_by_cols(rettuple
, tupdesc
,
87 1, &attnum
, &newval
, &newnull
);
91 return PointerGetDatum(rettuple
);