Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * plsample.c
4 : : * Handler for the PL/Sample procedural language
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/test/modules/plsample/plsample.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : :
16 : : #include "postgres.h"
17 : :
18 : : #include "catalog/pg_proc.h"
19 : : #include "catalog/pg_type.h"
20 : : #include "commands/event_trigger.h"
21 : : #include "commands/trigger.h"
22 : : #include "executor/spi.h"
23 : : #include "funcapi.h"
24 : : #include "utils/builtins.h"
25 : : #include "utils/fmgrprotos.h"
26 : : #include "utils/lsyscache.h"
27 : : #include "utils/syscache.h"
28 : :
29 : 1 : PG_MODULE_MAGIC;
30 : :
31 : 2 : PG_FUNCTION_INFO_V1(plsample_call_handler);
32 : :
33 : : static Datum plsample_func_handler(PG_FUNCTION_ARGS);
34 : : static HeapTuple plsample_trigger_handler(PG_FUNCTION_ARGS);
35 : :
36 : : /*
37 : : * Handle function, procedure, and trigger calls.
38 : : */
39 : : Datum
40 : 6 : plsample_call_handler(PG_FUNCTION_ARGS)
41 : : {
42 : 6 : Datum retval = (Datum) 0;
43 : :
44 : : /*
45 : : * Many languages will require cleanup that happens even in the event of
46 : : * an error. That can happen in the PG_FINALLY block. If none is needed,
47 : : * this PG_TRY construct can be omitted.
48 : : */
49 [ + - ]: 6 : PG_TRY();
50 : : {
51 : : /*
52 : : * Determine if called as function or trigger and call appropriate
53 : : * subhandler.
54 : : */
55 [ + + + - ]: 6 : if (CALLED_AS_TRIGGER(fcinfo))
56 : : {
57 : : /*
58 : : * This function has been called as a trigger function, where
59 : : * (TriggerData *) fcinfo->context includes the information of the
60 : : * context.
61 : : */
62 : 4 : retval = PointerGetDatum(plsample_trigger_handler(fcinfo));
63 : : }
64 [ - + - - ]: 2 : else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
65 : : {
66 : : /*
67 : : * This function is called as an event trigger function, where
68 : : * (EventTriggerData *) fcinfo->context includes the information
69 : : * of the context.
70 : : *
71 : : * TODO: provide an example handler.
72 : : */
73 : : }
74 : : else
75 : : {
76 : : /* Regular function handler */
77 : 2 : retval = plsample_func_handler(fcinfo);
78 : : }
79 : : }
80 : 0 : PG_FINALLY();
81 : : {
82 : : }
83 [ - + ]: 6 : PG_END_TRY();
84 : :
85 : 6 : return retval;
86 : : }
87 : :
88 : : /*
89 : : * plsample_func_handler
90 : : *
91 : : * Function called by the call handler for function execution.
92 : : */
93 : : static Datum
94 : 2 : plsample_func_handler(PG_FUNCTION_ARGS)
95 : : {
96 : : HeapTuple pl_tuple;
97 : : Datum ret;
98 : : char *source;
99 : : bool isnull;
100 : : FmgrInfo *arg_out_func;
101 : : Form_pg_type type_struct;
102 : : HeapTuple type_tuple;
103 : : Form_pg_proc pl_struct;
104 : 2 : volatile MemoryContext proc_cxt = NULL;
105 : : Oid *argtypes;
106 : : char **argnames;
107 : : char *argmodes;
108 : : char *proname;
109 : : Form_pg_type pg_type_entry;
110 : : Oid result_typioparam;
111 : : Oid prorettype;
112 : : FmgrInfo result_in_func;
113 : : int numargs;
114 : : int inargno;
115 : :
116 : : /* Fetch the function's pg_proc entry. */
117 : 2 : pl_tuple = SearchSysCache1(PROCOID,
118 : 2 : ObjectIdGetDatum(fcinfo->flinfo->fn_oid));
119 [ - + ]: 2 : if (!HeapTupleIsValid(pl_tuple))
120 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u",
121 : : fcinfo->flinfo->fn_oid);
122 : :
123 : : /*
124 : : * Extract and print the source text of the function. This can be used as
125 : : * a base for the function validation and execution.
126 : : */
127 : 2 : pl_struct = (Form_pg_proc) GETSTRUCT(pl_tuple);
128 : 2 : proname = pstrdup(NameStr(pl_struct->proname));
129 : 2 : ret = SysCacheGetAttr(PROCOID, pl_tuple, Anum_pg_proc_prosrc, &isnull);
130 [ - + ]: 2 : if (isnull)
131 [ # # ]: 0 : elog(ERROR, "could not find source text of function \"%s\"",
132 : : proname);
133 : 2 : source = TextDatumGetCString(ret);
134 [ + - ]: 2 : ereport(NOTICE,
135 : : (errmsg("source text of function \"%s\": %s",
136 : : proname, source)));
137 : :
138 : : /*
139 : : * Allocate a context that will hold all the Postgres data for the
140 : : * procedure.
141 : : */
142 : 2 : proc_cxt = AllocSetContextCreate(TopMemoryContext,
143 : : "PL/Sample function",
144 : : ALLOCSET_SMALL_SIZES);
145 : :
146 : 2 : arg_out_func = palloc0_array(FmgrInfo, fcinfo->nargs);
147 : 2 : numargs = get_func_arg_info(pl_tuple, &argtypes, &argnames, &argmodes);
148 : :
149 : : /*
150 : : * Iterate through all of the function arguments, printing each input
151 : : * value.
152 : : */
153 : 2 : inargno = 0;
154 [ + + ]: 6 : for (int i = 0; i < numargs; i++)
155 : : {
156 : 4 : Oid argtype = argtypes[i];
157 : : char *value;
158 : :
159 [ - + ]: 4 : if (argmodes &&
160 [ # # ]: 0 : (argmodes[i] == PROARGMODE_OUT ||
161 [ # # ]: 0 : argmodes[i] == PROARGMODE_TABLE))
162 : 0 : continue; /* skip OUT arguments */
163 : :
164 : 4 : type_tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
165 [ - + ]: 4 : if (!HeapTupleIsValid(type_tuple))
166 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", argtype);
167 : :
168 : 4 : type_struct = (Form_pg_type) GETSTRUCT(type_tuple);
169 : 4 : fmgr_info_cxt(type_struct->typoutput,
170 : 4 : &(arg_out_func[inargno]), proc_cxt);
171 : 4 : ReleaseSysCache(type_tuple);
172 : :
173 : 4 : value = OutputFunctionCall(&arg_out_func[inargno],
174 : : fcinfo->args[inargno].value);
175 [ + - + - : 4 : ereport(NOTICE,
+ - ]
176 : : (errmsg("argument: %d; name: %s; value: %s",
177 : : inargno,
178 : : (argnames && argnames[i][0]) ? argnames[i] : "(none)",
179 : : value)));
180 : 4 : inargno++;
181 : : }
182 : :
183 : : /* Type of the result */
184 : 2 : prorettype = pl_struct->prorettype;
185 : 2 : ReleaseSysCache(pl_tuple);
186 : :
187 : : /*
188 : : * Get the required information for input conversion of the return value.
189 : : *
190 : : * If the function uses VOID as result, it is better to return NULL.
191 : : * Anyway, let's be honest. This is just a template, so there is not much
192 : : * we can do here. This returns NULL except if the result type is text,
193 : : * where the result is the source text of the function.
194 : : */
195 [ + + ]: 2 : if (prorettype != TEXTOID)
196 : 1 : PG_RETURN_NULL();
197 : :
198 : 1 : type_tuple = SearchSysCache1(TYPEOID,
199 : : ObjectIdGetDatum(prorettype));
200 [ - + ]: 1 : if (!HeapTupleIsValid(type_tuple))
201 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", prorettype);
202 : 1 : pg_type_entry = (Form_pg_type) GETSTRUCT(type_tuple);
203 : 1 : result_typioparam = getTypeIOParam(type_tuple);
204 : :
205 : 1 : fmgr_info_cxt(pg_type_entry->typinput, &result_in_func, proc_cxt);
206 : 1 : ReleaseSysCache(type_tuple);
207 : :
208 : 1 : ret = InputFunctionCall(&result_in_func, source, result_typioparam, -1);
209 : 1 : PG_RETURN_DATUM(ret);
210 : : }
211 : :
212 : : /*
213 : : * plsample_trigger_handler
214 : : *
215 : : * Function called by the call handler for trigger execution.
216 : : */
217 : : static HeapTuple
218 : 4 : plsample_trigger_handler(PG_FUNCTION_ARGS)
219 : : {
220 : 4 : TriggerData *trigdata = (TriggerData *) fcinfo->context;
221 : : char *string;
222 : : volatile HeapTuple rettup;
223 : : HeapTuple pl_tuple;
224 : : Datum ret;
225 : : char *source;
226 : : bool isnull;
227 : : Form_pg_proc pl_struct;
228 : : char *proname;
229 : : int rc PG_USED_FOR_ASSERTS_ONLY;
230 : :
231 : : /* Make sure this is being called from a trigger. */
232 [ + - - + ]: 4 : if (!CALLED_AS_TRIGGER(fcinfo))
233 [ # # ]: 0 : elog(ERROR, "not called by trigger manager");
234 : :
235 : : /* Connect to the SPI manager */
236 : 4 : SPI_connect();
237 : :
238 : 4 : rc = SPI_register_trigger_data(trigdata);
239 : : Assert(rc >= 0);
240 : :
241 : : /* Fetch the function's pg_proc entry. */
242 : 4 : pl_tuple = SearchSysCache1(PROCOID,
243 : 4 : ObjectIdGetDatum(fcinfo->flinfo->fn_oid));
244 [ - + ]: 4 : if (!HeapTupleIsValid(pl_tuple))
245 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u",
246 : : fcinfo->flinfo->fn_oid);
247 : :
248 : : /*
249 : : * Code Retrieval
250 : : *
251 : : * Extract and print the source text of the function. This can be used as
252 : : * a base for the function validation and execution.
253 : : */
254 : 4 : pl_struct = (Form_pg_proc) GETSTRUCT(pl_tuple);
255 : 4 : proname = pstrdup(NameStr(pl_struct->proname));
256 : 4 : ret = SysCacheGetAttr(PROCOID, pl_tuple, Anum_pg_proc_prosrc, &isnull);
257 [ - + ]: 4 : if (isnull)
258 [ # # ]: 0 : elog(ERROR, "could not find source text of function \"%s\"",
259 : : proname);
260 : 4 : source = TextDatumGetCString(ret);
261 [ + - ]: 4 : ereport(NOTICE,
262 : : (errmsg("source text of function \"%s\": %s",
263 : : proname, source)));
264 : :
265 : : /*
266 : : * We're done with the pg_proc tuple, so release it. (Note that the
267 : : * "proname" and "source" strings are now standalone copies.)
268 : : */
269 : 4 : ReleaseSysCache(pl_tuple);
270 : :
271 : : /*
272 : : * Code Augmentation
273 : : *
274 : : * The source text may be augmented here, such as by wrapping it as the
275 : : * body of a function in the target language, prefixing a parameter list
276 : : * with names like TD_name, TD_relid, TD_table_name, TD_table_schema,
277 : : * TD_event, TD_when, TD_level, TD_NEW, TD_OLD, and args, using whatever
278 : : * types in the target language are convenient. The augmented text can be
279 : : * cached in a longer-lived memory context, or, if the target language
280 : : * uses a compilation step, that can be done here, caching the result of
281 : : * the compilation.
282 : : */
283 : :
284 : : /*
285 : : * Code Execution
286 : : *
287 : : * Here the function (the possibly-augmented source text, or the result of
288 : : * compilation if the target language uses such a step) should be
289 : : * executed, after binding values from the TriggerData struct to the
290 : : * appropriate parameters.
291 : : *
292 : : * In this example we just print a lot of info via ereport.
293 : : */
294 : :
295 [ + - ]: 4 : PG_TRY();
296 : : {
297 [ + - ]: 4 : ereport(NOTICE,
298 : : (errmsg("trigger name: %s", trigdata->tg_trigger->tgname)));
299 : 4 : string = SPI_getrelname(trigdata->tg_relation);
300 [ + - ]: 4 : ereport(NOTICE, (errmsg("trigger relation: %s", string)));
301 : :
302 : 4 : string = SPI_getnspname(trigdata->tg_relation);
303 [ + - ]: 4 : ereport(NOTICE, (errmsg("trigger relation schema: %s", string)));
304 : :
305 : : /* Example handling of different trigger aspects. */
306 : :
307 [ + + ]: 4 : if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
308 : : {
309 [ + - ]: 2 : ereport(NOTICE, (errmsg("triggered by INSERT")));
310 : 2 : rettup = trigdata->tg_trigtuple;
311 : : }
312 [ - + ]: 2 : else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
313 : : {
314 [ # # ]: 0 : ereport(NOTICE, (errmsg("triggered by DELETE")));
315 : 0 : rettup = trigdata->tg_trigtuple;
316 : : }
317 [ + - ]: 2 : else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
318 : : {
319 [ + - ]: 2 : ereport(NOTICE, (errmsg("triggered by UPDATE")));
320 : 2 : rettup = trigdata->tg_trigtuple;
321 : : }
322 [ # # ]: 0 : else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
323 : : {
324 [ # # ]: 0 : ereport(NOTICE, (errmsg("triggered by TRUNCATE")));
325 : 0 : rettup = trigdata->tg_trigtuple;
326 : : }
327 : : else
328 [ # # ]: 0 : elog(ERROR, "unrecognized event: %u", trigdata->tg_event);
329 : :
330 [ + + ]: 4 : if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
331 [ + - ]: 2 : ereport(NOTICE, (errmsg("triggered BEFORE")));
332 [ + - ]: 2 : else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
333 [ + - ]: 2 : ereport(NOTICE, (errmsg("triggered AFTER")));
334 [ # # ]: 0 : else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
335 [ # # ]: 0 : ereport(NOTICE, (errmsg("triggered INSTEAD OF")));
336 : : else
337 [ # # ]: 0 : elog(ERROR, "unrecognized when: %u", trigdata->tg_event);
338 : :
339 [ + - ]: 4 : if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
340 [ + - ]: 4 : ereport(NOTICE, (errmsg("triggered per row")));
341 [ # # ]: 0 : else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
342 [ # # ]: 0 : ereport(NOTICE, (errmsg("triggered per statement")));
343 : : else
344 [ # # ]: 0 : elog(ERROR, "unrecognized level: %u", trigdata->tg_event);
345 : :
346 : : /*
347 : : * Iterate through all of the trigger arguments, printing each input
348 : : * value.
349 : : */
350 [ + + ]: 6 : for (int i = 0; i < trigdata->tg_trigger->tgnargs; i++)
351 [ + - ]: 2 : ereport(NOTICE,
352 : : (errmsg("trigger arg[%d]: %s", i,
353 : : trigdata->tg_trigger->tgargs[i])));
354 : : }
355 : 0 : PG_CATCH();
356 : : {
357 : : /* Error cleanup code would go here */
358 : 0 : PG_RE_THROW();
359 : : }
360 [ - + ]: 4 : PG_END_TRY();
361 : :
362 [ - + ]: 4 : if (SPI_finish() != SPI_OK_FINISH)
363 [ # # ]: 0 : elog(ERROR, "SPI_finish() failed");
364 : :
365 : 4 : return rettup;
366 : : }
|