Branch data Line data Source code
1 : : /**********************************************************************
2 : : * pltcl.c - PostgreSQL support for Tcl as
3 : : * procedural language (PL)
4 : : *
5 : : * src/pl/tcl/pltcl.c
6 : : *
7 : : **********************************************************************/
8 : :
9 : : #include "postgres.h"
10 : :
11 : : #include <tcl.h>
12 : :
13 : : #include <unistd.h>
14 : : #include <fcntl.h>
15 : :
16 : : #include "access/htup_details.h"
17 : : #include "access/xact.h"
18 : : #include "catalog/objectaccess.h"
19 : : #include "catalog/pg_proc.h"
20 : : #include "catalog/pg_type.h"
21 : : #include "commands/event_trigger.h"
22 : : #include "commands/trigger.h"
23 : : #include "executor/spi.h"
24 : : #include "fmgr.h"
25 : : #include "funcapi.h"
26 : : #include "mb/pg_wchar.h"
27 : : #include "miscadmin.h"
28 : : #include "parser/parse_func.h"
29 : : #include "parser/parse_type.h"
30 : : #include "pgstat.h"
31 : : #include "utils/acl.h"
32 : : #include "utils/builtins.h"
33 : : #include "utils/guc.h"
34 : : #include "utils/hsearch.h"
35 : : #include "utils/lsyscache.h"
36 : : #include "utils/memutils.h"
37 : : #include "utils/regproc.h"
38 : : #include "utils/rel.h"
39 : : #include "utils/syscache.h"
40 : : #include "utils/tuplestore.h"
41 : : #include "utils/typcache.h"
42 : :
43 : :
44 : 9 : PG_MODULE_MAGIC_EXT(
45 : : .name = "pltcl",
46 : : .version = PG_VERSION
47 : : );
48 : :
49 : : #define HAVE_TCL_VERSION(maj,min) \
50 : : ((TCL_MAJOR_VERSION > maj) || \
51 : : (TCL_MAJOR_VERSION == maj && TCL_MINOR_VERSION >= min))
52 : :
53 : : /* Insist on Tcl >= 8.4 */
54 : : #if !HAVE_TCL_VERSION(8,4)
55 : : #error PostgreSQL only supports Tcl 8.4 or later.
56 : : #endif
57 : :
58 : : /* Hack to deal with Tcl 8.6 const-ification without losing compatibility */
59 : : #ifndef CONST86
60 : : #define CONST86
61 : : #endif
62 : :
63 : : #if !HAVE_TCL_VERSION(8,7)
64 : : typedef int Tcl_Size;
65 : : #endif
66 : :
67 : : /* define our text domain for translations */
68 : : #undef TEXTDOMAIN
69 : : #define TEXTDOMAIN PG_TEXTDOMAIN("pltcl")
70 : :
71 : :
72 : : /*
73 : : * Support for converting between UTF8 (which is what all strings going into
74 : : * or out of Tcl should be) and the database encoding.
75 : : *
76 : : * If you just use utf_u2e() or utf_e2u() directly, they will leak some
77 : : * palloc'd space when doing a conversion. This is not worth worrying about
78 : : * if it only happens, say, once per PL/Tcl function call. If it does seem
79 : : * worth worrying about, use the wrapper macros.
80 : : */
81 : :
82 : : static inline char *
83 : 451 : utf_u2e(const char *src)
84 : : {
85 : 451 : return pg_any_to_server(src, strlen(src), PG_UTF8);
86 : : }
87 : :
88 : : static inline char *
89 : 1358 : utf_e2u(const char *src)
90 : : {
91 : 1358 : return pg_server_to_any(src, strlen(src), PG_UTF8);
92 : : }
93 : :
94 : : #define UTF_BEGIN \
95 : : do { \
96 : : const char *_pltcl_utf_src = NULL; \
97 : : char *_pltcl_utf_dst = NULL
98 : :
99 : : #define UTF_END \
100 : : if (_pltcl_utf_src != (const char *) _pltcl_utf_dst) \
101 : : pfree(_pltcl_utf_dst); \
102 : : } while (0)
103 : :
104 : : #define UTF_U2E(x) \
105 : : (_pltcl_utf_dst = utf_u2e(_pltcl_utf_src = (x)))
106 : :
107 : : #define UTF_E2U(x) \
108 : : (_pltcl_utf_dst = utf_e2u(_pltcl_utf_src = (x)))
109 : :
110 : : /* This variant always makes a pstrdup'd copy */
111 : : static inline char *
112 : 311 : utf_u2e_copy(const char *src)
113 : : {
114 : 311 : char *dst = pg_any_to_server(src, strlen(src), PG_UTF8);
115 : :
116 [ + - ]: 311 : if ((const char *) dst == src)
117 : 311 : dst = pstrdup(dst);
118 : 311 : return dst;
119 : : }
120 : :
121 : :
122 : : /**********************************************************************
123 : : * Information associated with a Tcl interpreter. We have one interpreter
124 : : * that is used for all pltclu (untrusted) functions. For pltcl (trusted)
125 : : * functions, there is a separate interpreter for each effective SQL userid.
126 : : * (This is needed to ensure that an unprivileged user can't inject Tcl code
127 : : * that'll be executed with the privileges of some other SQL user.)
128 : : *
129 : : * The pltcl_interp_desc structs are kept in a Postgres hash table indexed
130 : : * by userid OID, with OID 0 used for the single untrusted interpreter.
131 : : **********************************************************************/
132 : : typedef struct pltcl_interp_desc
133 : : {
134 : : Oid user_id; /* Hash key (must be first!) */
135 : : Tcl_Interp *interp; /* The interpreter */
136 : : Tcl_HashTable query_hash; /* pltcl_query_desc structs */
137 : : } pltcl_interp_desc;
138 : :
139 : :
140 : : /**********************************************************************
141 : : * The information we cache about loaded procedures
142 : : *
143 : : * The pltcl_proc_desc struct itself, as well as all subsidiary data,
144 : : * is stored in the memory context identified by the fn_cxt field.
145 : : * We can reclaim all the data by deleting that context, and should do so
146 : : * when the fn_refcount goes to zero. That will happen if we build a new
147 : : * pltcl_proc_desc following an update of the pg_proc row. If that happens
148 : : * while the old proc is being executed, we mustn't remove the struct until
149 : : * execution finishes. When building a new pltcl_proc_desc, we unlink
150 : : * Tcl's copy of the old procedure definition, similarly relying on Tcl's
151 : : * internal reference counting to prevent that structure from disappearing
152 : : * while it's in use.
153 : : *
154 : : * Note that the data in this struct is shared across all active calls;
155 : : * nothing except the fn_refcount should be changed by a call instance.
156 : : **********************************************************************/
157 : : typedef struct pltcl_proc_desc
158 : : {
159 : : char *user_proname; /* user's name (from format_procedure) */
160 : : char *internal_proname; /* Tcl proc name (NULL if deleted) */
161 : : MemoryContext fn_cxt; /* memory context for this procedure */
162 : : unsigned long fn_refcount; /* number of active references */
163 : : TransactionId fn_xmin; /* xmin of pg_proc row */
164 : : ItemPointerData fn_tid; /* TID of pg_proc row */
165 : : bool fn_readonly; /* is function readonly? */
166 : : bool lanpltrusted; /* is it pltcl (vs. pltclu)? */
167 : : pltcl_interp_desc *interp_desc; /* interpreter to use */
168 : : Oid result_typid; /* OID of fn's result type */
169 : : FmgrInfo result_in_func; /* input function for fn's result type */
170 : : Oid result_typioparam; /* param to pass to same */
171 : : bool fn_retisset; /* true if function returns a set */
172 : : bool fn_retistuple; /* true if function returns composite */
173 : : bool fn_retisdomain; /* true if function returns domain */
174 : : void *domain_info; /* opaque cache for domain checks */
175 : : int nargs; /* number of arguments */
176 : : /* these arrays have nargs entries: */
177 : : FmgrInfo *arg_out_func; /* output fns for arg types */
178 : : bool *arg_is_rowtype; /* is each arg composite? */
179 : : } pltcl_proc_desc;
180 : :
181 : :
182 : : /**********************************************************************
183 : : * The information we cache about prepared and saved plans
184 : : **********************************************************************/
185 : : typedef struct pltcl_query_desc
186 : : {
187 : : char qname[20];
188 : : SPIPlanPtr plan;
189 : : int nargs;
190 : : Oid *argtypes;
191 : : FmgrInfo *arginfuncs;
192 : : Oid *argtypioparams;
193 : : } pltcl_query_desc;
194 : :
195 : :
196 : : /**********************************************************************
197 : : * For speedy lookup, we maintain a hash table mapping from
198 : : * function OID + trigger flag + user OID to pltcl_proc_desc pointers.
199 : : * The reason the pltcl_proc_desc struct isn't directly part of the hash
200 : : * entry is to simplify recovery from errors during compile_pltcl_function.
201 : : *
202 : : * Note: if the same function is called by multiple userIDs within a session,
203 : : * there will be a separate pltcl_proc_desc entry for each userID in the case
204 : : * of pltcl functions, but only one entry for pltclu functions, because we
205 : : * set user_id = 0 for that case.
206 : : **********************************************************************/
207 : : typedef struct pltcl_proc_key
208 : : {
209 : : Oid proc_id; /* Function OID */
210 : :
211 : : /*
212 : : * is_trigger is really a bool, but declare as Oid to ensure this struct
213 : : * contains no padding
214 : : */
215 : : Oid is_trigger; /* is it a trigger function? */
216 : : Oid user_id; /* User calling the function, or 0 */
217 : : } pltcl_proc_key;
218 : :
219 : : typedef struct pltcl_proc_ptr
220 : : {
221 : : pltcl_proc_key proc_key; /* Hash key (must be first!) */
222 : : pltcl_proc_desc *proc_ptr;
223 : : } pltcl_proc_ptr;
224 : :
225 : :
226 : : /**********************************************************************
227 : : * Per-call state
228 : : **********************************************************************/
229 : : typedef struct pltcl_call_state
230 : : {
231 : : /* Call info struct, or NULL in a trigger */
232 : : FunctionCallInfo fcinfo;
233 : :
234 : : /* Trigger data, if we're in a normal (not event) trigger; else NULL */
235 : : TriggerData *trigdata;
236 : :
237 : : /* Function we're executing (NULL if not yet identified) */
238 : : pltcl_proc_desc *prodesc;
239 : :
240 : : /*
241 : : * Information for SRFs and functions returning composite types.
242 : : * ret_tupdesc and attinmeta are set up if either fn_retistuple or
243 : : * fn_retisset, since even a scalar-returning SRF needs a tuplestore.
244 : : */
245 : : TupleDesc ret_tupdesc; /* return rowtype, if retistuple or retisset */
246 : : AttInMetadata *attinmeta; /* metadata for building tuples of that type */
247 : :
248 : : ReturnSetInfo *rsi; /* passed-in ReturnSetInfo, if any */
249 : : Tuplestorestate *tuple_store; /* SRFs accumulate result here */
250 : : MemoryContext tuple_store_cxt; /* context and resowner for tuplestore */
251 : : ResourceOwner tuple_store_owner;
252 : : } pltcl_call_state;
253 : :
254 : :
255 : : /**********************************************************************
256 : : * Global data
257 : : **********************************************************************/
258 : : static char *pltcl_start_proc = NULL;
259 : : static char *pltclu_start_proc = NULL;
260 : : static bool pltcl_pm_init_done = false;
261 : : static Tcl_Interp *pltcl_hold_interp = NULL;
262 : : static HTAB *pltcl_interp_htab = NULL;
263 : : static HTAB *pltcl_proc_htab = NULL;
264 : :
265 : : /* this is saved and restored by pltcl_handler */
266 : : static pltcl_call_state *pltcl_current_call_state = NULL;
267 : :
268 : : /**********************************************************************
269 : : * Lookup table for SQLSTATE condition names
270 : : **********************************************************************/
271 : : typedef struct
272 : : {
273 : : const char *label;
274 : : int sqlerrstate;
275 : : } TclExceptionNameMap;
276 : :
277 : : static const TclExceptionNameMap exception_name_map[] = {
278 : : #include "pltclerrcodes.h"
279 : : {NULL, 0}
280 : : };
281 : :
282 : : /**********************************************************************
283 : : * Forward declarations
284 : : **********************************************************************/
285 : :
286 : : static void pltcl_init_interp(pltcl_interp_desc *interp_desc,
287 : : Oid prolang, bool pltrusted);
288 : : static pltcl_interp_desc *pltcl_fetch_interp(Oid prolang, bool pltrusted);
289 : : static void call_pltcl_start_proc(Oid prolang, bool pltrusted);
290 : : static void start_proc_error_callback(void *arg);
291 : :
292 : : static Datum pltcl_handler(PG_FUNCTION_ARGS, bool pltrusted);
293 : :
294 : : static Datum pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
295 : : bool pltrusted);
296 : : static HeapTuple pltcl_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
297 : : bool pltrusted);
298 : : static void pltcl_event_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
299 : : bool pltrusted);
300 : :
301 : : static void throw_tcl_error(Tcl_Interp *interp, const char *proname);
302 : :
303 : : static pltcl_proc_desc *compile_pltcl_function(Oid fn_oid, Oid tgreloid,
304 : : bool is_event_trigger,
305 : : bool pltrusted);
306 : :
307 : : static int pltcl_elog(ClientData cdata, Tcl_Interp *interp,
308 : : int objc, Tcl_Obj *const objv[]);
309 : : static void pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata);
310 : : static const char *pltcl_get_condition_name(int sqlstate);
311 : : static int pltcl_quote(ClientData cdata, Tcl_Interp *interp,
312 : : int objc, Tcl_Obj *const objv[]);
313 : : static int pltcl_argisnull(ClientData cdata, Tcl_Interp *interp,
314 : : int objc, Tcl_Obj *const objv[]);
315 : : static int pltcl_returnnull(ClientData cdata, Tcl_Interp *interp,
316 : : int objc, Tcl_Obj *const objv[]);
317 : : static int pltcl_returnnext(ClientData cdata, Tcl_Interp *interp,
318 : : int objc, Tcl_Obj *const objv[]);
319 : : static int pltcl_SPI_execute(ClientData cdata, Tcl_Interp *interp,
320 : : int objc, Tcl_Obj *const objv[]);
321 : : static int pltcl_process_SPI_result(Tcl_Interp *interp,
322 : : const char *arrayname,
323 : : Tcl_Obj *loop_body,
324 : : int spi_rc,
325 : : SPITupleTable *tuptable,
326 : : uint64 ntuples);
327 : : static int pltcl_SPI_prepare(ClientData cdata, Tcl_Interp *interp,
328 : : int objc, Tcl_Obj *const objv[]);
329 : : static int pltcl_SPI_execute_plan(ClientData cdata, Tcl_Interp *interp,
330 : : int objc, Tcl_Obj *const objv[]);
331 : : static int pltcl_subtransaction(ClientData cdata, Tcl_Interp *interp,
332 : : int objc, Tcl_Obj *const objv[]);
333 : : static int pltcl_commit(ClientData cdata, Tcl_Interp *interp,
334 : : int objc, Tcl_Obj *const objv[]);
335 : : static int pltcl_rollback(ClientData cdata, Tcl_Interp *interp,
336 : : int objc, Tcl_Obj *const objv[]);
337 : :
338 : : static void pltcl_subtrans_begin(MemoryContext oldcontext,
339 : : ResourceOwner oldowner);
340 : : static void pltcl_subtrans_commit(MemoryContext oldcontext,
341 : : ResourceOwner oldowner);
342 : : static void pltcl_subtrans_abort(Tcl_Interp *interp,
343 : : MemoryContext oldcontext,
344 : : ResourceOwner oldowner);
345 : :
346 : : static void pltcl_set_tuple_values(Tcl_Interp *interp, const char *arrayname,
347 : : uint64 tupno, HeapTuple tuple, TupleDesc tupdesc);
348 : : static Tcl_Obj *pltcl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc, bool include_generated);
349 : : static HeapTuple pltcl_build_tuple_result(Tcl_Interp *interp,
350 : : Tcl_Obj **kvObjv, int kvObjc,
351 : : pltcl_call_state *call_state);
352 : : static void pltcl_init_tuple_store(pltcl_call_state *call_state);
353 : :
354 : :
355 : : /*
356 : : * Hack to override Tcl's builtin Notifier subsystem. This prevents the
357 : : * backend from becoming multithreaded, which breaks all sorts of things.
358 : : * That happens in the default version of Tcl_InitNotifier if the Tcl library
359 : : * has been compiled with multithreading support (i.e. when TCL_THREADS is
360 : : * defined under Unix, and in all cases under Windows).
361 : : * It's okay to disable the notifier because we never enter the Tcl event loop
362 : : * from Postgres, so the notifier capabilities are initialized, but never
363 : : * used. Only InitNotifier and DeleteFileHandler ever seem to get called
364 : : * within Postgres, but we implement all the functions for completeness.
365 : : */
366 : : static ClientData
367 : 9 : pltcl_InitNotifier(void)
368 : : {
369 : : static int fakeThreadKey; /* To give valid address for ClientData */
370 : :
371 : 9 : return (ClientData) &(fakeThreadKey);
372 : : }
373 : :
374 : : static void
375 : 0 : pltcl_FinalizeNotifier(ClientData clientData)
376 : : {
377 : 0 : }
378 : :
379 : : static void
380 : 1 : pltcl_SetTimer(CONST86 Tcl_Time *timePtr)
381 : : {
382 : 1 : }
383 : :
384 : : static void
385 : 0 : pltcl_AlertNotifier(ClientData clientData)
386 : : {
387 : 0 : }
388 : :
389 : : static void
390 : 0 : pltcl_CreateFileHandler(int fd, int mask,
391 : : Tcl_FileProc *proc, ClientData clientData)
392 : : {
393 : 0 : }
394 : :
395 : : static void
396 : 46 : pltcl_DeleteFileHandler(int fd)
397 : : {
398 : 46 : }
399 : :
400 : : static void
401 : 0 : pltcl_ServiceModeHook(int mode)
402 : : {
403 : 0 : }
404 : :
405 : : static int
406 : 689497 : pltcl_WaitForEvent(CONST86 Tcl_Time *timePtr)
407 : : {
408 : 689497 : return 0;
409 : : }
410 : :
411 : :
412 : : /*
413 : : * _PG_init() - library load-time initialization
414 : : *
415 : : * DO NOT make this static nor change its name!
416 : : *
417 : : * The work done here must be safe to do in the postmaster process,
418 : : * in case the pltcl library is preloaded in the postmaster.
419 : : */
420 : : void
421 : 9 : _PG_init(void)
422 : : {
423 : : Tcl_NotifierProcs notifier;
424 : : HASHCTL hash_ctl;
425 : :
426 : : /* Be sure we do initialization only once (should be redundant now) */
427 [ - + ]: 9 : if (pltcl_pm_init_done)
428 : 0 : return;
429 : :
430 : 9 : pg_bindtextdomain(TEXTDOMAIN);
431 : :
432 : : #ifdef WIN32
433 : : /* Required on win32 to prevent error loading init.tcl */
434 : : Tcl_FindExecutable("");
435 : : #endif
436 : :
437 : : /*
438 : : * Override the functions in the Notifier subsystem. See comments above.
439 : : */
440 : 9 : notifier.setTimerProc = pltcl_SetTimer;
441 : 9 : notifier.waitForEventProc = pltcl_WaitForEvent;
442 : 9 : notifier.createFileHandlerProc = pltcl_CreateFileHandler;
443 : 9 : notifier.deleteFileHandlerProc = pltcl_DeleteFileHandler;
444 : 9 : notifier.initNotifierProc = pltcl_InitNotifier;
445 : 9 : notifier.finalizeNotifierProc = pltcl_FinalizeNotifier;
446 : 9 : notifier.alertNotifierProc = pltcl_AlertNotifier;
447 : 9 : notifier.serviceModeHookProc = pltcl_ServiceModeHook;
448 : 9 : Tcl_SetNotifier(¬ifier);
449 : :
450 : : /************************************************************
451 : : * Create the dummy hold interpreter to prevent close of
452 : : * stdout and stderr on DeleteInterp
453 : : ************************************************************/
454 [ - + ]: 9 : if ((pltcl_hold_interp = Tcl_CreateInterp()) == NULL)
455 [ # # ]: 0 : elog(ERROR, "could not create dummy Tcl interpreter");
456 [ - + ]: 9 : if (Tcl_Init(pltcl_hold_interp) == TCL_ERROR)
457 [ # # ]: 0 : elog(ERROR, "could not initialize dummy Tcl interpreter");
458 : :
459 : : /************************************************************
460 : : * Create the hash table for working interpreters
461 : : ************************************************************/
462 : 9 : hash_ctl.keysize = sizeof(Oid);
463 : 9 : hash_ctl.entrysize = sizeof(pltcl_interp_desc);
464 : 9 : pltcl_interp_htab = hash_create("PL/Tcl interpreters",
465 : : 8,
466 : : &hash_ctl,
467 : : HASH_ELEM | HASH_BLOBS);
468 : :
469 : : /************************************************************
470 : : * Create the hash table for function lookup
471 : : ************************************************************/
472 : 9 : hash_ctl.keysize = sizeof(pltcl_proc_key);
473 : 9 : hash_ctl.entrysize = sizeof(pltcl_proc_ptr);
474 : 9 : pltcl_proc_htab = hash_create("PL/Tcl functions",
475 : : 100,
476 : : &hash_ctl,
477 : : HASH_ELEM | HASH_BLOBS);
478 : :
479 : : /************************************************************
480 : : * Define PL/Tcl's custom GUCs
481 : : ************************************************************/
482 : 9 : DefineCustomStringVariable("pltcl.start_proc",
483 : : gettext_noop("PL/Tcl function to call once when pltcl is first used."),
484 : : NULL,
485 : : &pltcl_start_proc,
486 : : NULL,
487 : : PGC_SUSET, 0,
488 : : NULL, NULL, NULL);
489 : 9 : DefineCustomStringVariable("pltclu.start_proc",
490 : : gettext_noop("PL/TclU function to call once when pltclu is first used."),
491 : : NULL,
492 : : &pltclu_start_proc,
493 : : NULL,
494 : : PGC_SUSET, 0,
495 : : NULL, NULL, NULL);
496 : :
497 : 9 : MarkGUCPrefixReserved("pltcl");
498 : 9 : MarkGUCPrefixReserved("pltclu");
499 : :
500 : 9 : pltcl_pm_init_done = true;
501 : : }
502 : :
503 : : /**********************************************************************
504 : : * pltcl_init_interp() - initialize a new Tcl interpreter
505 : : **********************************************************************/
506 : : static void
507 : 11 : pltcl_init_interp(pltcl_interp_desc *interp_desc, Oid prolang, bool pltrusted)
508 : : {
509 : : Tcl_Interp *interp;
510 : : char interpname[32];
511 : :
512 : : /************************************************************
513 : : * Create the Tcl interpreter subsidiary to pltcl_hold_interp.
514 : : * Note: Tcl automatically does Tcl_Init in the untrusted case,
515 : : * and it's not wanted in the trusted case.
516 : : ************************************************************/
517 : 11 : snprintf(interpname, sizeof(interpname), "subsidiary_%u", interp_desc->user_id);
518 [ - + ]: 11 : if ((interp = Tcl_CreateSlave(pltcl_hold_interp, interpname,
519 : : pltrusted ? 1 : 0)) == NULL)
520 [ # # ]: 0 : elog(ERROR, "could not create subsidiary Tcl interpreter");
521 : :
522 : : /************************************************************
523 : : * Initialize the query hash table associated with interpreter
524 : : ************************************************************/
525 : 11 : Tcl_InitHashTable(&interp_desc->query_hash, TCL_STRING_KEYS);
526 : :
527 : : /************************************************************
528 : : * Install the commands for SPI support in the interpreter
529 : : ************************************************************/
530 : 11 : Tcl_CreateObjCommand(interp, "elog",
531 : : pltcl_elog, NULL, NULL);
532 : 11 : Tcl_CreateObjCommand(interp, "quote",
533 : : pltcl_quote, NULL, NULL);
534 : 11 : Tcl_CreateObjCommand(interp, "argisnull",
535 : : pltcl_argisnull, NULL, NULL);
536 : 11 : Tcl_CreateObjCommand(interp, "return_null",
537 : : pltcl_returnnull, NULL, NULL);
538 : 11 : Tcl_CreateObjCommand(interp, "return_next",
539 : : pltcl_returnnext, NULL, NULL);
540 : 11 : Tcl_CreateObjCommand(interp, "spi_exec",
541 : : pltcl_SPI_execute, NULL, NULL);
542 : 11 : Tcl_CreateObjCommand(interp, "spi_prepare",
543 : : pltcl_SPI_prepare, NULL, NULL);
544 : 11 : Tcl_CreateObjCommand(interp, "spi_execp",
545 : : pltcl_SPI_execute_plan, NULL, NULL);
546 : 11 : Tcl_CreateObjCommand(interp, "subtransaction",
547 : : pltcl_subtransaction, NULL, NULL);
548 : 11 : Tcl_CreateObjCommand(interp, "commit",
549 : : pltcl_commit, NULL, NULL);
550 : 11 : Tcl_CreateObjCommand(interp, "rollback",
551 : : pltcl_rollback, NULL, NULL);
552 : :
553 : : /************************************************************
554 : : * Call the appropriate start_proc, if there is one.
555 : : *
556 : : * We must set interp_desc->interp before the call, else the start_proc
557 : : * won't find the interpreter it's supposed to use. But, if the
558 : : * start_proc fails, we want to abandon use of the interpreter.
559 : : ************************************************************/
560 [ + + ]: 11 : PG_TRY();
561 : : {
562 : 11 : interp_desc->interp = interp;
563 : 11 : call_pltcl_start_proc(prolang, pltrusted);
564 : : }
565 : 3 : PG_CATCH();
566 : : {
567 : 3 : interp_desc->interp = NULL;
568 : 3 : Tcl_DeleteInterp(interp);
569 : 3 : PG_RE_THROW();
570 : : }
571 [ - + ]: 8 : PG_END_TRY();
572 : 8 : }
573 : :
574 : : /**********************************************************************
575 : : * pltcl_fetch_interp() - fetch the Tcl interpreter to use for a function
576 : : *
577 : : * This also takes care of any on-first-use initialization required.
578 : : **********************************************************************/
579 : : static pltcl_interp_desc *
580 : 65 : pltcl_fetch_interp(Oid prolang, bool pltrusted)
581 : : {
582 : : Oid user_id;
583 : : pltcl_interp_desc *interp_desc;
584 : : bool found;
585 : :
586 : : /* Find or create the interpreter hashtable entry for this userid */
587 [ + - ]: 65 : if (pltrusted)
588 : 65 : user_id = GetUserId();
589 : : else
590 : 0 : user_id = InvalidOid;
591 : :
592 : 65 : interp_desc = hash_search(pltcl_interp_htab, &user_id,
593 : : HASH_ENTER,
594 : : &found);
595 [ + + ]: 65 : if (!found)
596 : 8 : interp_desc->interp = NULL;
597 : :
598 : : /* If we haven't yet successfully made an interpreter, try to do that */
599 [ + + ]: 65 : if (!interp_desc->interp)
600 : 11 : pltcl_init_interp(interp_desc, prolang, pltrusted);
601 : :
602 : 62 : return interp_desc;
603 : : }
604 : :
605 : :
606 : : /**********************************************************************
607 : : * call_pltcl_start_proc() - Call user-defined initialization proc, if any
608 : : **********************************************************************/
609 : : static void
610 : 11 : call_pltcl_start_proc(Oid prolang, bool pltrusted)
611 : : {
612 : 11 : LOCAL_FCINFO(fcinfo, 0);
613 : : char *start_proc;
614 : : const char *gucname;
615 : : ErrorContextCallback errcallback;
616 : : List *namelist;
617 : : Oid procOid;
618 : : HeapTuple procTup;
619 : : Form_pg_proc procStruct;
620 : : AclResult aclresult;
621 : : FmgrInfo finfo;
622 : : PgStat_FunctionCallUsage fcusage;
623 : :
624 : : /* select appropriate GUC */
625 [ + - ]: 11 : start_proc = pltrusted ? pltcl_start_proc : pltclu_start_proc;
626 [ + - ]: 11 : gucname = pltrusted ? "pltcl.start_proc" : "pltclu.start_proc";
627 : :
628 : : /* Nothing to do if it's empty or unset */
629 [ + + - + ]: 11 : if (start_proc == NULL || start_proc[0] == '\0')
630 : 7 : return;
631 : :
632 : : /* Set up errcontext callback to make errors more helpful */
633 : 4 : errcallback.callback = start_proc_error_callback;
634 : 4 : errcallback.arg = unconstify(char *, gucname);
635 : 4 : errcallback.previous = error_context_stack;
636 : 4 : error_context_stack = &errcallback;
637 : :
638 : : /* Parse possibly-qualified identifier and look up the function */
639 : 4 : namelist = stringToQualifiedNameList(start_proc, NULL);
640 : 4 : procOid = LookupFuncName(namelist, 0, NULL, false);
641 : :
642 : : /* Current user must have permission to call function */
643 : 2 : aclresult = object_aclcheck(ProcedureRelationId, procOid, GetUserId(), ACL_EXECUTE);
644 [ - + ]: 2 : if (aclresult != ACLCHECK_OK)
645 : 0 : aclcheck_error(aclresult, OBJECT_FUNCTION, start_proc);
646 : :
647 : : /* Get the function's pg_proc entry */
648 : 2 : procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(procOid));
649 [ - + ]: 2 : if (!HeapTupleIsValid(procTup))
650 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", procOid);
651 : 2 : procStruct = (Form_pg_proc) GETSTRUCT(procTup);
652 : :
653 : : /* It must be same language as the function we're currently calling */
654 [ - + ]: 2 : if (procStruct->prolang != prolang)
655 [ # # ]: 0 : ereport(ERROR,
656 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
657 : : errmsg("function \"%s\" is in the wrong language",
658 : : start_proc)));
659 : :
660 : : /*
661 : : * It must not be SECURITY DEFINER, either. This together with the
662 : : * language match check ensures that the function will execute in the same
663 : : * Tcl interpreter we just finished initializing.
664 : : */
665 [ + + ]: 2 : if (procStruct->prosecdef)
666 [ + - ]: 1 : ereport(ERROR,
667 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
668 : : errmsg("function \"%s\" must not be SECURITY DEFINER",
669 : : start_proc)));
670 : :
671 : : /* A-OK */
672 : 1 : ReleaseSysCache(procTup);
673 : :
674 : : /*
675 : : * Call the function using the normal SQL function call mechanism. We
676 : : * could perhaps cheat and jump directly to pltcl_handler(), but it seems
677 : : * better to do it this way so that the call is exposed to, eg, call
678 : : * statistics collection.
679 : : */
680 [ - + ]: 1 : InvokeFunctionExecuteHook(procOid);
681 : 1 : fmgr_info(procOid, &finfo);
682 : 1 : InitFunctionCallInfoData(*fcinfo, &finfo,
683 : : 0,
684 : : InvalidOid, NULL, NULL);
685 : 1 : pgstat_init_function_usage(fcinfo, &fcusage);
686 : 1 : (void) FunctionCallInvoke(fcinfo);
687 : 1 : pgstat_end_function_usage(&fcusage, true);
688 : :
689 : : /* Pop the error context stack */
690 : 1 : error_context_stack = errcallback.previous;
691 : : }
692 : :
693 : : /*
694 : : * Error context callback for errors occurring during start_proc processing.
695 : : */
696 : : static void
697 : 4 : start_proc_error_callback(void *arg)
698 : : {
699 : 4 : const char *gucname = (const char *) arg;
700 : :
701 : : /* translator: %s is "pltcl.start_proc" or "pltclu.start_proc" */
702 : 4 : errcontext("processing %s parameter", gucname);
703 : 4 : }
704 : :
705 : :
706 : : /**********************************************************************
707 : : * pltcl_call_handler - This is the only visible function
708 : : * of the PL interpreter. The PostgreSQL
709 : : * function manager and trigger manager
710 : : * call this function for execution of
711 : : * PL/Tcl procedures.
712 : : **********************************************************************/
713 : 9 : PG_FUNCTION_INFO_V1(pltcl_call_handler);
714 : :
715 : : /* keep non-static */
716 : : Datum
717 : 223 : pltcl_call_handler(PG_FUNCTION_ARGS)
718 : : {
719 : 223 : return pltcl_handler(fcinfo, true);
720 : : }
721 : :
722 : : /*
723 : : * Alternative handler for unsafe functions
724 : : */
725 : 0 : PG_FUNCTION_INFO_V1(pltclu_call_handler);
726 : :
727 : : /* keep non-static */
728 : : Datum
729 : 0 : pltclu_call_handler(PG_FUNCTION_ARGS)
730 : : {
731 : 0 : return pltcl_handler(fcinfo, false);
732 : : }
733 : :
734 : :
735 : : /**********************************************************************
736 : : * pltcl_handler() - Handler for function and trigger calls, for
737 : : * both trusted and untrusted interpreters.
738 : : **********************************************************************/
739 : : static Datum
740 : 223 : pltcl_handler(PG_FUNCTION_ARGS, bool pltrusted)
741 : : {
742 : 223 : Datum retval = (Datum) 0;
743 : : pltcl_call_state current_call_state;
744 : : pltcl_call_state *save_call_state;
745 : :
746 : : /*
747 : : * Initialize current_call_state to nulls/zeroes; in particular, set its
748 : : * prodesc pointer to null. Anything that sets it non-null should
749 : : * increase the prodesc's fn_refcount at the same time. We'll decrease
750 : : * the refcount, and then delete the prodesc if it's no longer referenced,
751 : : * on the way out of this function. This ensures that prodescs live as
752 : : * long as needed even if somebody replaces the originating pg_proc row
753 : : * while they're executing.
754 : : */
755 : 223 : memset(¤t_call_state, 0, sizeof(current_call_state));
756 : :
757 : : /*
758 : : * Ensure that static pointer is saved/restored properly
759 : : */
760 : 223 : save_call_state = pltcl_current_call_state;
761 : 223 : pltcl_current_call_state = ¤t_call_state;
762 : :
763 [ + + ]: 223 : PG_TRY();
764 : : {
765 : : /*
766 : : * Determine if called as function or trigger and call appropriate
767 : : * subhandler
768 : : */
769 [ + + + + ]: 223 : if (CALLED_AS_TRIGGER(fcinfo))
770 : : {
771 : : /* invoke the trigger handler */
772 : 58 : retval = PointerGetDatum(pltcl_trigger_handler(fcinfo,
773 : : ¤t_call_state,
774 : : pltrusted));
775 : : }
776 [ + + + + ]: 165 : else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
777 : : {
778 : : /* invoke the event trigger handler */
779 : 10 : pltcl_event_trigger_handler(fcinfo, ¤t_call_state, pltrusted);
780 : 10 : retval = (Datum) 0;
781 : : }
782 : : else
783 : : {
784 : : /* invoke the regular function handler */
785 : 155 : current_call_state.fcinfo = fcinfo;
786 : 155 : retval = pltcl_func_handler(fcinfo, ¤t_call_state, pltrusted);
787 : : }
788 : : }
789 : 55 : PG_FINALLY();
790 : : {
791 : : /* Restore static pointer, then clean up the prodesc refcount if any */
792 : : /*
793 : : * (We're being paranoid in case an error is thrown in context
794 : : * deletion)
795 : : */
796 : 223 : pltcl_current_call_state = save_call_state;
797 [ + + ]: 223 : if (current_call_state.prodesc != NULL)
798 : : {
799 : : Assert(current_call_state.prodesc->fn_refcount > 0);
800 [ + + ]: 220 : if (--current_call_state.prodesc->fn_refcount == 0)
801 : 1 : MemoryContextDelete(current_call_state.prodesc->fn_cxt);
802 : : }
803 : : }
804 [ + + ]: 223 : PG_END_TRY();
805 : :
806 : 168 : return retval;
807 : : }
808 : :
809 : :
810 : : /**********************************************************************
811 : : * pltcl_func_handler() - Handler for regular function calls
812 : : **********************************************************************/
813 : : static Datum
814 : 155 : pltcl_func_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
815 : : bool pltrusted)
816 : : {
817 : : bool nonatomic;
818 : : pltcl_proc_desc *prodesc;
819 : : Tcl_Interp *volatile interp;
820 : : Tcl_Obj *tcl_cmd;
821 : : int i;
822 : : int tcl_rc;
823 : : Datum retval;
824 : :
825 : 346 : nonatomic = fcinfo->context &&
826 [ + + + + ]: 168 : IsA(fcinfo->context, CallContext) &&
827 [ + + ]: 13 : !castNode(CallContext, fcinfo->context)->atomic;
828 : :
829 : : /* Connect to SPI manager */
830 : 155 : SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0);
831 : :
832 : : /* Find or compile the function */
833 : 155 : prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid, InvalidOid,
834 : : false, pltrusted);
835 : :
836 : 152 : call_state->prodesc = prodesc;
837 : 152 : prodesc->fn_refcount++;
838 : :
839 : 152 : interp = prodesc->interp_desc->interp;
840 : :
841 : : /*
842 : : * If we're a SRF, check caller can handle materialize mode, and save
843 : : * relevant info into call_state. We must ensure that the returned
844 : : * tuplestore is owned by the caller's context, even if we first create it
845 : : * inside a subtransaction.
846 : : */
847 [ + + ]: 152 : if (prodesc->fn_retisset)
848 : : {
849 : 5 : ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
850 : :
851 [ + - - + ]: 5 : if (!rsi || !IsA(rsi, ReturnSetInfo))
852 [ # # ]: 0 : ereport(ERROR,
853 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
854 : : errmsg("set-valued function called in context that cannot accept a set")));
855 : :
856 [ - + ]: 5 : if (!(rsi->allowedModes & SFRM_Materialize))
857 [ # # ]: 0 : ereport(ERROR,
858 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
859 : : errmsg("materialize mode required, but it is not allowed in this context")));
860 : :
861 : 5 : call_state->rsi = rsi;
862 : 5 : call_state->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
863 : 5 : call_state->tuple_store_owner = CurrentResourceOwner;
864 : : }
865 : :
866 : : /************************************************************
867 : : * Create the tcl command to call the internal
868 : : * proc in the Tcl interpreter
869 : : ************************************************************/
870 : 152 : tcl_cmd = Tcl_NewObj();
871 : 152 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
872 : 152 : Tcl_NewStringObj(prodesc->internal_proname, -1));
873 : :
874 : : /* We hold a refcount on tcl_cmd just to be sure it stays around */
875 : 152 : Tcl_IncrRefCount(tcl_cmd);
876 : :
877 : : /************************************************************
878 : : * Add all call arguments to the command
879 : : ************************************************************/
880 [ + - ]: 152 : PG_TRY();
881 : : {
882 [ + + ]: 350 : for (i = 0; i < prodesc->nargs; i++)
883 : : {
884 [ + + ]: 198 : if (prodesc->arg_is_rowtype[i])
885 : : {
886 : : /**************************************************
887 : : * For tuple values, add a list for 'array set ...'
888 : : **************************************************/
889 [ - + ]: 7 : if (fcinfo->args[i].isnull)
890 : 0 : Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
891 : : else
892 : : {
893 : : HeapTupleHeader td;
894 : : Oid tupType;
895 : : int32 tupTypmod;
896 : : TupleDesc tupdesc;
897 : : HeapTupleData tmptup;
898 : : Tcl_Obj *list_tmp;
899 : :
900 : 7 : td = DatumGetHeapTupleHeader(fcinfo->args[i].value);
901 : : /* Extract rowtype info and find a tupdesc */
902 : 7 : tupType = HeapTupleHeaderGetTypeId(td);
903 : 7 : tupTypmod = HeapTupleHeaderGetTypMod(td);
904 : 7 : tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
905 : : /* Build a temporary HeapTuple control structure */
906 : 7 : tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
907 : 7 : tmptup.t_data = td;
908 : :
909 : 7 : list_tmp = pltcl_build_tuple_argument(&tmptup, tupdesc, true);
910 : 7 : Tcl_ListObjAppendElement(NULL, tcl_cmd, list_tmp);
911 : :
912 [ + - ]: 7 : ReleaseTupleDesc(tupdesc);
913 : : }
914 : : }
915 : : else
916 : : {
917 : : /**************************************************
918 : : * Single values are added as string element
919 : : * of their external representation
920 : : **************************************************/
921 [ + + ]: 191 : if (fcinfo->args[i].isnull)
922 : 2 : Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
923 : : else
924 : : {
925 : : char *tmp;
926 : :
927 : 189 : tmp = OutputFunctionCall(&prodesc->arg_out_func[i],
928 : : fcinfo->args[i].value);
929 : 189 : UTF_BEGIN;
930 : 189 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
931 : 189 : Tcl_NewStringObj(UTF_E2U(tmp), -1));
932 [ - + ]: 189 : UTF_END;
933 : 189 : pfree(tmp);
934 : : }
935 : : }
936 : : }
937 : : }
938 : 0 : PG_CATCH();
939 : : {
940 : : /* Release refcount to free tcl_cmd */
941 [ # # ]: 0 : Tcl_DecrRefCount(tcl_cmd);
942 : 0 : PG_RE_THROW();
943 : : }
944 [ - + ]: 152 : PG_END_TRY();
945 : :
946 : : /************************************************************
947 : : * Call the Tcl function
948 : : *
949 : : * We assume no PG error can be thrown directly from this call.
950 : : ************************************************************/
951 : 152 : tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
952 : :
953 : : /* Release refcount to free tcl_cmd (and all subsidiary objects) */
954 [ + - ]: 152 : Tcl_DecrRefCount(tcl_cmd);
955 : :
956 : : /************************************************************
957 : : * Check for errors reported by Tcl.
958 : : ************************************************************/
959 [ + + ]: 152 : if (tcl_rc != TCL_OK)
960 : 38 : throw_tcl_error(interp, prodesc->user_proname);
961 : :
962 : : /************************************************************
963 : : * Disconnect from SPI manager and then create the return
964 : : * value datum (if the input function does a palloc for it
965 : : * this must not be allocated in the SPI memory context
966 : : * because SPI_finish would free it). But don't try to call
967 : : * the result_in_func if we've been told to return a NULL;
968 : : * the Tcl result may not be a valid value of the result type
969 : : * in that case.
970 : : ************************************************************/
971 [ - + ]: 114 : if (SPI_finish() != SPI_OK_FINISH)
972 [ # # ]: 0 : elog(ERROR, "SPI_finish() failed");
973 : :
974 [ + + ]: 114 : if (prodesc->fn_retisset)
975 : : {
976 : 3 : ReturnSetInfo *rsi = call_state->rsi;
977 : :
978 : : /* We already checked this is OK */
979 : 3 : rsi->returnMode = SFRM_Materialize;
980 : :
981 : : /* If we produced any tuples, send back the result */
982 [ + - ]: 3 : if (call_state->tuple_store)
983 : : {
984 : 3 : rsi->setResult = call_state->tuple_store;
985 [ + - ]: 3 : if (call_state->ret_tupdesc)
986 : : {
987 : : MemoryContext oldcxt;
988 : :
989 : 3 : oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
990 : 3 : rsi->setDesc = CreateTupleDescCopy(call_state->ret_tupdesc);
991 : 3 : MemoryContextSwitchTo(oldcxt);
992 : : }
993 : : }
994 : 3 : retval = (Datum) 0;
995 : 3 : fcinfo->isnull = true;
996 : : }
997 [ + + ]: 111 : else if (fcinfo->isnull)
998 : : {
999 : 1 : retval = InputFunctionCall(&prodesc->result_in_func,
1000 : : NULL,
1001 : : prodesc->result_typioparam,
1002 : : -1);
1003 : : }
1004 [ + + ]: 110 : else if (prodesc->fn_retistuple)
1005 : : {
1006 : : TupleDesc td;
1007 : : HeapTuple tup;
1008 : : Tcl_Obj *resultObj;
1009 : : Tcl_Obj **resultObjv;
1010 : : Tcl_Size resultObjc;
1011 : :
1012 : : /*
1013 : : * Set up data about result type. XXX it's tempting to consider
1014 : : * caching this in the prodesc, in the common case where the rowtype
1015 : : * is determined by the function not the calling query. But we'd have
1016 : : * to be able to deal with ADD/DROP/ALTER COLUMN events when the
1017 : : * result type is a named composite type, so it's not exactly trivial.
1018 : : * Maybe worth improving someday.
1019 : : */
1020 [ + + + - ]: 16 : switch (get_call_result_type(fcinfo, NULL, &td))
1021 : : {
1022 : 12 : case TYPEFUNC_COMPOSITE:
1023 : : /* success */
1024 : 12 : break;
1025 : 3 : case TYPEFUNC_COMPOSITE_DOMAIN:
1026 : : Assert(prodesc->fn_retisdomain);
1027 : 3 : break;
1028 : 1 : case TYPEFUNC_RECORD:
1029 : : /* failed to determine actual type of RECORD */
1030 [ + - ]: 1 : ereport(ERROR,
1031 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1032 : : errmsg("function returning record called in context "
1033 : : "that cannot accept type record")));
1034 : : break;
1035 : 0 : default:
1036 : : /* result type isn't composite? */
1037 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
1038 : : break;
1039 : : }
1040 : :
1041 : : Assert(!call_state->ret_tupdesc);
1042 : : Assert(!call_state->attinmeta);
1043 : 15 : call_state->ret_tupdesc = td;
1044 : 15 : call_state->attinmeta = TupleDescGetAttInMetadata(td);
1045 : :
1046 : : /* Convert function result to tuple */
1047 : 15 : resultObj = Tcl_GetObjResult(interp);
1048 [ + + ]: 15 : if (Tcl_ListObjGetElements(interp, resultObj, &resultObjc, &resultObjv) == TCL_ERROR)
1049 [ + - ]: 1 : ereport(ERROR,
1050 : : (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1051 : : errmsg("could not parse function return value: %s",
1052 : : utf_u2e(Tcl_GetStringResult(interp)))));
1053 : :
1054 : 14 : tup = pltcl_build_tuple_result(interp, resultObjv, resultObjc,
1055 : : call_state);
1056 : 10 : retval = HeapTupleGetDatum(tup);
1057 : : }
1058 : : else
1059 : : {
1060 : : /*
1061 : : * Notice that we forcibly copy the result of Tcl_GetStringResult, so
1062 : : * that the result_in_func is applied to data that doesn't belong to
1063 : : * the Tcl interpreter. This avoids use-after-free problems if the
1064 : : * result_in_func calls another pltcl function. No need to worry
1065 : : * about leaking the string, since this happens just once per pltcl
1066 : : * function call.
1067 : : */
1068 : 94 : retval = InputFunctionCall(&prodesc->result_in_func,
1069 : 94 : utf_u2e_copy(Tcl_GetStringResult(interp)),
1070 : : prodesc->result_typioparam,
1071 : : -1);
1072 : : }
1073 : :
1074 : 108 : return retval;
1075 : : }
1076 : :
1077 : :
1078 : : /**********************************************************************
1079 : : * pltcl_trigger_handler() - Handler for trigger calls
1080 : : **********************************************************************/
1081 : : static HeapTuple
1082 : 58 : pltcl_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
1083 : : bool pltrusted)
1084 : : {
1085 : : pltcl_proc_desc *prodesc;
1086 : : Tcl_Interp *volatile interp;
1087 : 58 : TriggerData *trigdata = (TriggerData *) fcinfo->context;
1088 : : char *stroid;
1089 : : TupleDesc tupdesc;
1090 : : volatile HeapTuple rettup;
1091 : : Tcl_Obj *tcl_cmd;
1092 : : Tcl_Obj *tcl_trigtup;
1093 : : int tcl_rc;
1094 : : int i;
1095 : : const char *result;
1096 : : Tcl_Size result_Objc;
1097 : : Tcl_Obj **result_Objv;
1098 : : int rc PG_USED_FOR_ASSERTS_ONLY;
1099 : :
1100 : 58 : call_state->trigdata = trigdata;
1101 : :
1102 : : /* Connect to SPI manager */
1103 : 58 : SPI_connect();
1104 : :
1105 : : /* Make transition tables visible to this SPI connection */
1106 : 58 : rc = SPI_register_trigger_data(trigdata);
1107 : : Assert(rc >= 0);
1108 : :
1109 : : /* Find or compile the function */
1110 : 116 : prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
1111 : 58 : RelationGetRelid(trigdata->tg_relation),
1112 : : false, /* not an event trigger */
1113 : : pltrusted);
1114 : :
1115 : 58 : call_state->prodesc = prodesc;
1116 : 58 : prodesc->fn_refcount++;
1117 : :
1118 : 58 : interp = prodesc->interp_desc->interp;
1119 : :
1120 : 58 : tupdesc = RelationGetDescr(trigdata->tg_relation);
1121 : :
1122 : : /************************************************************
1123 : : * Create the tcl command to call the internal
1124 : : * proc in the interpreter
1125 : : ************************************************************/
1126 : 58 : tcl_cmd = Tcl_NewObj();
1127 : 58 : Tcl_IncrRefCount(tcl_cmd);
1128 : :
1129 [ + - ]: 58 : PG_TRY();
1130 : : {
1131 : : /* The procedure name (note this is all ASCII, so no utf_e2u) */
1132 : 58 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1133 : 58 : Tcl_NewStringObj(prodesc->internal_proname, -1));
1134 : :
1135 : : /* The trigger name for argument TG_name */
1136 : 58 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1137 : 58 : Tcl_NewStringObj(utf_e2u(trigdata->tg_trigger->tgname), -1));
1138 : :
1139 : : /* The oid of the trigger relation for argument TG_relid */
1140 : : /* Consider not converting to a string for more performance? */
1141 : 58 : stroid = DatumGetCString(DirectFunctionCall1(oidout,
1142 : : ObjectIdGetDatum(trigdata->tg_relation->rd_id)));
1143 : 58 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1144 : : Tcl_NewStringObj(stroid, -1));
1145 : 58 : pfree(stroid);
1146 : :
1147 : : /* The name of the table the trigger is acting on: TG_table_name */
1148 : 58 : stroid = SPI_getrelname(trigdata->tg_relation);
1149 : 58 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1150 : 58 : Tcl_NewStringObj(utf_e2u(stroid), -1));
1151 : 58 : pfree(stroid);
1152 : :
1153 : : /* The schema of the table the trigger is acting on: TG_table_schema */
1154 : 58 : stroid = SPI_getnspname(trigdata->tg_relation);
1155 : 58 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1156 : 58 : Tcl_NewStringObj(utf_e2u(stroid), -1));
1157 : 58 : pfree(stroid);
1158 : :
1159 : : /* A list of attribute names for argument TG_relatts */
1160 : 58 : tcl_trigtup = Tcl_NewObj();
1161 : 58 : Tcl_ListObjAppendElement(NULL, tcl_trigtup, Tcl_NewObj());
1162 [ + + ]: 265 : for (i = 0; i < tupdesc->natts; i++)
1163 : : {
1164 : 207 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1165 : :
1166 [ + + ]: 207 : if (att->attisdropped)
1167 : 13 : Tcl_ListObjAppendElement(NULL, tcl_trigtup, Tcl_NewObj());
1168 : : else
1169 : 194 : Tcl_ListObjAppendElement(NULL, tcl_trigtup,
1170 : 194 : Tcl_NewStringObj(utf_e2u(NameStr(att->attname)), -1));
1171 : : }
1172 : 58 : Tcl_ListObjAppendElement(NULL, tcl_cmd, tcl_trigtup);
1173 : :
1174 : : /* The when part of the event for TG_when */
1175 [ + + ]: 58 : if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
1176 : 47 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1177 : : Tcl_NewStringObj("BEFORE", -1));
1178 [ + + ]: 11 : else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
1179 : 8 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1180 : : Tcl_NewStringObj("AFTER", -1));
1181 [ + - ]: 3 : else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
1182 : 3 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1183 : : Tcl_NewStringObj("INSTEAD OF", -1));
1184 : : else
1185 [ # # ]: 0 : elog(ERROR, "unrecognized WHEN tg_event: %u", trigdata->tg_event);
1186 : :
1187 : : /* The level part of the event for TG_level */
1188 [ + + ]: 58 : if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
1189 : : {
1190 : 50 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1191 : : Tcl_NewStringObj("ROW", -1));
1192 : :
1193 : : /*
1194 : : * Now the command part of the event for TG_op and data for NEW
1195 : : * and OLD
1196 : : *
1197 : : * Note: In BEFORE trigger, stored generated columns are not
1198 : : * computed yet, so don't make them accessible in NEW row.
1199 : : */
1200 [ + + ]: 50 : if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1201 : : {
1202 : 30 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1203 : : Tcl_NewStringObj("INSERT", -1));
1204 : :
1205 : 30 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1206 : : pltcl_build_tuple_argument(trigdata->tg_trigtuple,
1207 : : tupdesc,
1208 : 30 : !TRIGGER_FIRED_BEFORE(trigdata->tg_event)));
1209 : 30 : Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
1210 : :
1211 : 30 : rettup = trigdata->tg_trigtuple;
1212 : : }
1213 [ + + ]: 20 : else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1214 : : {
1215 : 8 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1216 : : Tcl_NewStringObj("DELETE", -1));
1217 : :
1218 : 8 : Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
1219 : 8 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1220 : : pltcl_build_tuple_argument(trigdata->tg_trigtuple,
1221 : : tupdesc,
1222 : : true));
1223 : :
1224 : 8 : rettup = trigdata->tg_trigtuple;
1225 : : }
1226 [ + - ]: 12 : else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1227 : : {
1228 : 12 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1229 : : Tcl_NewStringObj("UPDATE", -1));
1230 : :
1231 : 12 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1232 : : pltcl_build_tuple_argument(trigdata->tg_newtuple,
1233 : : tupdesc,
1234 : 12 : !TRIGGER_FIRED_BEFORE(trigdata->tg_event)));
1235 : 12 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1236 : : pltcl_build_tuple_argument(trigdata->tg_trigtuple,
1237 : : tupdesc,
1238 : : true));
1239 : :
1240 : 12 : rettup = trigdata->tg_newtuple;
1241 : : }
1242 : : else
1243 [ # # ]: 0 : elog(ERROR, "unrecognized OP tg_event: %u", trigdata->tg_event);
1244 : : }
1245 [ + - ]: 8 : else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
1246 : : {
1247 : 8 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1248 : : Tcl_NewStringObj("STATEMENT", -1));
1249 : :
1250 [ + + ]: 8 : if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
1251 : 3 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1252 : : Tcl_NewStringObj("INSERT", -1));
1253 [ + + ]: 5 : else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
1254 : 1 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1255 : : Tcl_NewStringObj("DELETE", -1));
1256 [ + + ]: 4 : else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
1257 : 3 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1258 : : Tcl_NewStringObj("UPDATE", -1));
1259 [ + - ]: 1 : else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
1260 : 1 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1261 : : Tcl_NewStringObj("TRUNCATE", -1));
1262 : : else
1263 [ # # ]: 0 : elog(ERROR, "unrecognized OP tg_event: %u", trigdata->tg_event);
1264 : :
1265 : 8 : Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
1266 : 8 : Tcl_ListObjAppendElement(NULL, tcl_cmd, Tcl_NewObj());
1267 : :
1268 : 8 : rettup = (HeapTuple) NULL;
1269 : : }
1270 : : else
1271 [ # # ]: 0 : elog(ERROR, "unrecognized LEVEL tg_event: %u", trigdata->tg_event);
1272 : :
1273 : : /* Finally append the arguments from CREATE TRIGGER */
1274 [ + + ]: 135 : for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
1275 : 77 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1276 : 77 : Tcl_NewStringObj(utf_e2u(trigdata->tg_trigger->tgargs[i]), -1));
1277 : : }
1278 : 0 : PG_CATCH();
1279 : : {
1280 [ # # ]: 0 : Tcl_DecrRefCount(tcl_cmd);
1281 : 0 : PG_RE_THROW();
1282 : : }
1283 [ - + ]: 58 : PG_END_TRY();
1284 : :
1285 : : /************************************************************
1286 : : * Call the Tcl function
1287 : : *
1288 : : * We assume no PG error can be thrown directly from this call.
1289 : : ************************************************************/
1290 : 58 : tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
1291 : :
1292 : : /* Release refcount to free tcl_cmd (and all subsidiary objects) */
1293 [ + - ]: 58 : Tcl_DecrRefCount(tcl_cmd);
1294 : :
1295 : : /************************************************************
1296 : : * Check for errors reported by Tcl.
1297 : : ************************************************************/
1298 [ + + ]: 58 : if (tcl_rc != TCL_OK)
1299 : 7 : throw_tcl_error(interp, prodesc->user_proname);
1300 : :
1301 : : /************************************************************
1302 : : * Exit SPI environment.
1303 : : ************************************************************/
1304 [ - + ]: 51 : if (SPI_finish() != SPI_OK_FINISH)
1305 [ # # ]: 0 : elog(ERROR, "SPI_finish() failed");
1306 : :
1307 : : /************************************************************
1308 : : * The return value from the procedure might be one of
1309 : : * the magic strings OK or SKIP, or a list from array get.
1310 : : * We can check for OK or SKIP without worrying about encoding.
1311 : : ************************************************************/
1312 : 51 : result = Tcl_GetStringResult(interp);
1313 : :
1314 [ + + ]: 51 : if (strcmp(result, "OK") == 0)
1315 : 40 : return rettup;
1316 [ + + ]: 11 : if (strcmp(result, "SKIP") == 0)
1317 : 1 : return (HeapTuple) NULL;
1318 : :
1319 : : /************************************************************
1320 : : * Otherwise, the return value should be a column name/value list
1321 : : * specifying the modified tuple to return.
1322 : : ************************************************************/
1323 [ - + ]: 10 : if (Tcl_ListObjGetElements(interp, Tcl_GetObjResult(interp),
1324 : : &result_Objc, &result_Objv) != TCL_OK)
1325 [ # # ]: 0 : ereport(ERROR,
1326 : : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1327 : : errmsg("could not parse trigger return value: %s",
1328 : : utf_u2e(Tcl_GetStringResult(interp)))));
1329 : :
1330 : : /* Convert function result to tuple */
1331 : 10 : rettup = pltcl_build_tuple_result(interp, result_Objv, result_Objc,
1332 : : call_state);
1333 : :
1334 : 9 : return rettup;
1335 : : }
1336 : :
1337 : : /**********************************************************************
1338 : : * pltcl_event_trigger_handler() - Handler for event trigger calls
1339 : : **********************************************************************/
1340 : : static void
1341 : 10 : pltcl_event_trigger_handler(PG_FUNCTION_ARGS, pltcl_call_state *call_state,
1342 : : bool pltrusted)
1343 : : {
1344 : : pltcl_proc_desc *prodesc;
1345 : : Tcl_Interp *volatile interp;
1346 : 10 : EventTriggerData *tdata = (EventTriggerData *) fcinfo->context;
1347 : : Tcl_Obj *tcl_cmd;
1348 : : int tcl_rc;
1349 : :
1350 : : /* Connect to SPI manager */
1351 : 10 : SPI_connect();
1352 : :
1353 : : /* Find or compile the function */
1354 : 10 : prodesc = compile_pltcl_function(fcinfo->flinfo->fn_oid,
1355 : : InvalidOid, true, pltrusted);
1356 : :
1357 : 10 : call_state->prodesc = prodesc;
1358 : 10 : prodesc->fn_refcount++;
1359 : :
1360 : 10 : interp = prodesc->interp_desc->interp;
1361 : :
1362 : : /* Create the tcl command and call the internal proc */
1363 : 10 : tcl_cmd = Tcl_NewObj();
1364 : 10 : Tcl_IncrRefCount(tcl_cmd);
1365 : 10 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1366 : 10 : Tcl_NewStringObj(prodesc->internal_proname, -1));
1367 : 10 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1368 : 10 : Tcl_NewStringObj(utf_e2u(tdata->event), -1));
1369 : 10 : Tcl_ListObjAppendElement(NULL, tcl_cmd,
1370 : 10 : Tcl_NewStringObj(utf_e2u(GetCommandTagName(tdata->tag)),
1371 : : -1));
1372 : :
1373 : 10 : tcl_rc = Tcl_EvalObjEx(interp, tcl_cmd, (TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL));
1374 : :
1375 : : /* Release refcount to free tcl_cmd (and all subsidiary objects) */
1376 [ + - ]: 10 : Tcl_DecrRefCount(tcl_cmd);
1377 : :
1378 : : /* Check for errors reported by Tcl. */
1379 [ - + ]: 10 : if (tcl_rc != TCL_OK)
1380 : 0 : throw_tcl_error(interp, prodesc->user_proname);
1381 : :
1382 [ - + ]: 10 : if (SPI_finish() != SPI_OK_FINISH)
1383 [ # # ]: 0 : elog(ERROR, "SPI_finish() failed");
1384 : 10 : }
1385 : :
1386 : :
1387 : : /**********************************************************************
1388 : : * throw_tcl_error - ereport an error returned from the Tcl interpreter
1389 : : *
1390 : : * Caution: use this only to report errors returned by Tcl_EvalObjEx() or
1391 : : * other variants of Tcl_Eval(). Other functions may not fill "errorInfo",
1392 : : * so it could be unset or even contain details from some previous error.
1393 : : **********************************************************************/
1394 : : static void
1395 : 45 : throw_tcl_error(Tcl_Interp *interp, const char *proname)
1396 : : {
1397 : : /*
1398 : : * Caution is needed here because Tcl_GetVar could overwrite the
1399 : : * interpreter result (even though it's not really supposed to), and we
1400 : : * can't control the order of evaluation of ereport arguments. Hence, make
1401 : : * real sure we have our own copy of the result string before invoking
1402 : : * Tcl_GetVar.
1403 : : */
1404 : : char *emsg;
1405 : : char *econtext;
1406 : : int emsglen;
1407 : :
1408 : 45 : emsg = utf_u2e_copy(Tcl_GetStringResult(interp));
1409 : 45 : econtext = utf_u2e(Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY));
1410 : :
1411 : : /*
1412 : : * Typically, the first line of errorInfo matches the primary error
1413 : : * message (the interpreter result); don't print that twice if so.
1414 : : */
1415 : 45 : emsglen = strlen(emsg);
1416 [ + - ]: 45 : if (strncmp(emsg, econtext, emsglen) == 0 &&
1417 [ + - ]: 45 : econtext[emsglen] == '\n')
1418 : 45 : econtext += emsglen + 1;
1419 : :
1420 : : /* Tcl likes to prefix the next line with some spaces, too */
1421 [ + + ]: 225 : while (*econtext == ' ')
1422 : 180 : econtext++;
1423 : :
1424 : : /* Note: proname will already contain quoting if any is needed */
1425 [ + - ]: 45 : ereport(ERROR,
1426 : : (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1427 : : errmsg("%s", emsg),
1428 : : errcontext("%s\nin PL/Tcl function %s",
1429 : : econtext, proname)));
1430 : : }
1431 : :
1432 : :
1433 : : /**********************************************************************
1434 : : * compile_pltcl_function - compile (or hopefully just look up) function
1435 : : *
1436 : : * tgreloid is the OID of the relation when compiling a trigger, or zero
1437 : : * (InvalidOid) when compiling a plain function.
1438 : : **********************************************************************/
1439 : : static pltcl_proc_desc *
1440 : 223 : compile_pltcl_function(Oid fn_oid, Oid tgreloid,
1441 : : bool is_event_trigger, bool pltrusted)
1442 : : {
1443 : : HeapTuple procTup;
1444 : : Form_pg_proc procStruct;
1445 : : pltcl_proc_key proc_key;
1446 : : pltcl_proc_ptr *proc_ptr;
1447 : : bool found;
1448 : : pltcl_proc_desc *prodesc;
1449 : : pltcl_proc_desc *old_prodesc;
1450 : 223 : volatile MemoryContext proc_cxt = NULL;
1451 : : Tcl_DString proc_internal_def;
1452 : : Tcl_DString proc_internal_name;
1453 : : Tcl_DString proc_internal_body;
1454 : : Tcl_DString proc_internal_args;
1455 : :
1456 : : /* We'll need the pg_proc tuple in any case... */
1457 : 223 : procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
1458 [ - + ]: 223 : if (!HeapTupleIsValid(procTup))
1459 [ # # ]: 0 : elog(ERROR, "cache lookup failed for function %u", fn_oid);
1460 : 223 : procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1461 : :
1462 : : /*
1463 : : * Look up function in pltcl_proc_htab; if it's not there, create an entry
1464 : : * and set the entry's proc_ptr to NULL.
1465 : : */
1466 : 223 : proc_key.proc_id = fn_oid;
1467 : 223 : proc_key.is_trigger = OidIsValid(tgreloid);
1468 [ + - ]: 223 : proc_key.user_id = pltrusted ? GetUserId() : InvalidOid;
1469 : :
1470 : 223 : proc_ptr = hash_search(pltcl_proc_htab, &proc_key,
1471 : : HASH_ENTER,
1472 : : &found);
1473 [ + + ]: 223 : if (!found)
1474 : 60 : proc_ptr->proc_ptr = NULL;
1475 : :
1476 : 223 : prodesc = proc_ptr->proc_ptr;
1477 : :
1478 : : /************************************************************
1479 : : * If it's present, must check whether it's still up to date.
1480 : : * This is needed because CREATE OR REPLACE FUNCTION can modify the
1481 : : * function's pg_proc entry without changing its OID.
1482 : : ************************************************************/
1483 [ + + ]: 223 : if (prodesc != NULL &&
1484 [ + - ]: 160 : prodesc->internal_proname != NULL &&
1485 [ + + ]: 160 : prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
1486 [ + - ]: 158 : ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self))
1487 : : {
1488 : : /* It's still up-to-date, so we can use it */
1489 : 158 : ReleaseSysCache(procTup);
1490 : 158 : return prodesc;
1491 : : }
1492 : :
1493 : : /************************************************************
1494 : : * If we haven't found it in the hashtable, we analyze
1495 : : * the functions arguments and returntype and store
1496 : : * the in-/out-functions in the prodesc block and create
1497 : : * a new hashtable entry for it.
1498 : : *
1499 : : * Then we load the procedure into the Tcl interpreter.
1500 : : ************************************************************/
1501 : 65 : Tcl_DStringInit(&proc_internal_def);
1502 : 65 : Tcl_DStringInit(&proc_internal_name);
1503 : 65 : Tcl_DStringInit(&proc_internal_body);
1504 : 65 : Tcl_DStringInit(&proc_internal_args);
1505 [ + + ]: 65 : PG_TRY();
1506 : : {
1507 : 65 : bool is_trigger = OidIsValid(tgreloid);
1508 : : Tcl_CmdInfo cmdinfo;
1509 : : const char *user_proname;
1510 : : const char *internal_proname;
1511 : : bool need_underscore;
1512 : : HeapTuple typeTup;
1513 : : Form_pg_type typeStruct;
1514 : : Datum prosrcdatum;
1515 : : char *proc_source;
1516 : : char buf[64];
1517 : : pltcl_interp_desc *interp_desc;
1518 : : Tcl_Interp *interp;
1519 : : int i;
1520 : : int tcl_rc;
1521 : : MemoryContext oldcontext;
1522 : :
1523 : : /************************************************************
1524 : : * Identify the interpreter to use for the function
1525 : : ************************************************************/
1526 : 65 : interp_desc = pltcl_fetch_interp(procStruct->prolang, pltrusted);
1527 : 62 : interp = interp_desc->interp;
1528 : :
1529 : : /************************************************************
1530 : : * If redefining the function, try to remove the old internal
1531 : : * procedure from Tcl's namespace. The point of this is partly to
1532 : : * allow re-use of the same internal proc name, and partly to avoid
1533 : : * leaking the Tcl procedure object if we end up not choosing the same
1534 : : * name. We assume that Tcl is smart enough to not physically delete
1535 : : * the procedure object if it's currently being executed.
1536 : : ************************************************************/
1537 [ + + ]: 62 : if (prodesc != NULL &&
1538 [ + - ]: 2 : prodesc->internal_proname != NULL)
1539 : : {
1540 : : /* We simply ignore any error */
1541 : 2 : (void) Tcl_DeleteCommand(interp, prodesc->internal_proname);
1542 : : /* Don't do this more than once */
1543 : 2 : prodesc->internal_proname = NULL;
1544 : : }
1545 : :
1546 : : /************************************************************
1547 : : * Build the proc name we'll use in error messages.
1548 : : ************************************************************/
1549 : 62 : user_proname = format_procedure(fn_oid);
1550 : :
1551 : : /************************************************************
1552 : : * Build the internal proc name from the user_proname and/or OID.
1553 : : * The internal name must be all-ASCII since we don't want to deal
1554 : : * with encoding conversions. We don't want to worry about Tcl
1555 : : * quoting rules either, so use only the characters of the function
1556 : : * name that are ASCII alphanumerics, plus underscores to separate
1557 : : * function name and arguments. If what we end up with isn't
1558 : : * unique (that is, it matches some existing Tcl command name),
1559 : : * append the function OID (perhaps repeatedly) so that it is unique.
1560 : : ************************************************************/
1561 : :
1562 : : /* For historical reasons, use a function-type-specific prefix */
1563 [ + + ]: 62 : if (is_event_trigger)
1564 : 1 : Tcl_DStringAppend(&proc_internal_name,
1565 : : "__PLTcl_evttrigger_", -1);
1566 [ + + ]: 61 : else if (is_trigger)
1567 : 8 : Tcl_DStringAppend(&proc_internal_name,
1568 : : "__PLTcl_trigger_", -1);
1569 : : else
1570 : 53 : Tcl_DStringAppend(&proc_internal_name,
1571 : : "__PLTcl_proc_", -1);
1572 : : /* Now add what we can from the user_proname */
1573 : 62 : need_underscore = false;
1574 [ + + ]: 1415 : for (const char *ptr = user_proname; *ptr; ptr++)
1575 : : {
1576 : 1353 : if (strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1577 : : "abcdefghijklmnopqrstuvwxyz"
1578 [ + + ]: 1353 : "0123456789_", *ptr) != NULL)
1579 : : {
1580 : : /* Done this way to avoid adding a trailing underscore */
1581 [ + + ]: 1211 : if (need_underscore)
1582 : : {
1583 : 48 : Tcl_DStringAppend(&proc_internal_name, "_", 1);
1584 : 48 : need_underscore = false;
1585 : : }
1586 : 1211 : Tcl_DStringAppend(&proc_internal_name, ptr, 1);
1587 : : }
1588 [ + + ]: 142 : else if (strchr("(, ", *ptr) != NULL)
1589 : 76 : need_underscore = true;
1590 : : }
1591 : : /* If this name already exists, append fn_oid; repeat as needed */
1592 [ + + ]: 125 : while (Tcl_GetCommandInfo(interp,
1593 : 63 : Tcl_DStringValue(&proc_internal_name),
1594 : : &cmdinfo))
1595 : : {
1596 : 1 : snprintf(buf, sizeof(buf), "_%u", fn_oid);
1597 : 1 : Tcl_DStringAppend(&proc_internal_name, buf, -1);
1598 : : }
1599 : 62 : internal_proname = Tcl_DStringValue(&proc_internal_name);
1600 : :
1601 : : /************************************************************
1602 : : * Allocate a context that will hold all PG data for the procedure.
1603 : : ************************************************************/
1604 : 62 : proc_cxt = AllocSetContextCreate(TopMemoryContext,
1605 : : "PL/Tcl function",
1606 : : ALLOCSET_SMALL_SIZES);
1607 : :
1608 : : /************************************************************
1609 : : * Allocate and fill a new procedure description block.
1610 : : * struct prodesc and subsidiary data must all live in proc_cxt.
1611 : : ************************************************************/
1612 : 62 : oldcontext = MemoryContextSwitchTo(proc_cxt);
1613 : 62 : prodesc = palloc0_object(pltcl_proc_desc);
1614 : 62 : prodesc->user_proname = pstrdup(user_proname);
1615 : 62 : MemoryContextSetIdentifier(proc_cxt, prodesc->user_proname);
1616 : 62 : prodesc->internal_proname = pstrdup(internal_proname);
1617 : 62 : prodesc->fn_cxt = proc_cxt;
1618 : 62 : prodesc->fn_refcount = 0;
1619 : 62 : prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
1620 : 62 : prodesc->fn_tid = procTup->t_self;
1621 : 62 : prodesc->nargs = procStruct->pronargs;
1622 : 62 : prodesc->arg_out_func = palloc0_array(FmgrInfo, prodesc->nargs);
1623 : 62 : prodesc->arg_is_rowtype = palloc0_array(bool, prodesc->nargs);
1624 : 62 : MemoryContextSwitchTo(oldcontext);
1625 : :
1626 : : /* Remember if function is STABLE/IMMUTABLE */
1627 : 62 : prodesc->fn_readonly =
1628 : 62 : (procStruct->provolatile != PROVOLATILE_VOLATILE);
1629 : : /* And whether it is trusted */
1630 : 62 : prodesc->lanpltrusted = pltrusted;
1631 : : /* Save the associated interpreter, too */
1632 : 62 : prodesc->interp_desc = interp_desc;
1633 : :
1634 : : /************************************************************
1635 : : * Get the required information for input conversion of the
1636 : : * return value.
1637 : : ************************************************************/
1638 [ + + + + ]: 62 : if (!is_trigger && !is_event_trigger)
1639 : : {
1640 : 53 : Oid rettype = procStruct->prorettype;
1641 : :
1642 : 53 : typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
1643 [ - + ]: 53 : if (!HeapTupleIsValid(typeTup))
1644 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", rettype);
1645 : 53 : typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1646 : :
1647 : : /* Disallow pseudotype result, except VOID and RECORD */
1648 [ + + ]: 53 : if (typeStruct->typtype == TYPTYPE_PSEUDO)
1649 : : {
1650 [ + + - + ]: 24 : if (rettype == VOIDOID ||
1651 : : rettype == RECORDOID)
1652 : : /* okay */ ;
1653 [ # # # # ]: 0 : else if (rettype == TRIGGEROID ||
1654 : : rettype == EVENT_TRIGGEROID)
1655 [ # # ]: 0 : ereport(ERROR,
1656 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1657 : : errmsg("trigger functions can only be called as triggers")));
1658 : : else
1659 [ # # ]: 0 : ereport(ERROR,
1660 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1661 : : errmsg("PL/Tcl functions cannot return type %s",
1662 : : format_type_be(rettype))));
1663 : : }
1664 : :
1665 : 53 : prodesc->result_typid = rettype;
1666 : 53 : fmgr_info_cxt(typeStruct->typinput,
1667 : : &(prodesc->result_in_func),
1668 : : proc_cxt);
1669 : 53 : prodesc->result_typioparam = getTypeIOParam(typeTup);
1670 : :
1671 : 53 : prodesc->fn_retisset = procStruct->proretset;
1672 : 53 : prodesc->fn_retistuple = type_is_rowtype(rettype);
1673 : 53 : prodesc->fn_retisdomain = (typeStruct->typtype == TYPTYPE_DOMAIN);
1674 : 53 : prodesc->domain_info = NULL;
1675 : :
1676 : 53 : ReleaseSysCache(typeTup);
1677 : : }
1678 : :
1679 : : /************************************************************
1680 : : * Get the required information for output conversion
1681 : : * of all procedure arguments, and set up argument naming info.
1682 : : ************************************************************/
1683 [ + + + + ]: 62 : if (!is_trigger && !is_event_trigger)
1684 : : {
1685 [ + + ]: 101 : for (i = 0; i < prodesc->nargs; i++)
1686 : : {
1687 : 48 : Oid argtype = procStruct->proargtypes.values[i];
1688 : :
1689 : 48 : typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
1690 [ - + ]: 48 : if (!HeapTupleIsValid(typeTup))
1691 [ # # ]: 0 : elog(ERROR, "cache lookup failed for type %u", argtype);
1692 : 48 : typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
1693 : :
1694 : : /* Disallow pseudotype argument, except RECORD */
1695 [ + + - + ]: 48 : if (typeStruct->typtype == TYPTYPE_PSEUDO &&
1696 : : argtype != RECORDOID)
1697 [ # # ]: 0 : ereport(ERROR,
1698 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1699 : : errmsg("PL/Tcl functions cannot accept type %s",
1700 : : format_type_be(argtype))));
1701 : :
1702 [ + + ]: 48 : if (type_is_rowtype(argtype))
1703 : : {
1704 : 4 : prodesc->arg_is_rowtype[i] = true;
1705 : 4 : snprintf(buf, sizeof(buf), "__PLTcl_Tup_%d", i + 1);
1706 : : }
1707 : : else
1708 : : {
1709 : 44 : prodesc->arg_is_rowtype[i] = false;
1710 : 44 : fmgr_info_cxt(typeStruct->typoutput,
1711 : 44 : &(prodesc->arg_out_func[i]),
1712 : : proc_cxt);
1713 : 44 : snprintf(buf, sizeof(buf), "%d", i + 1);
1714 : : }
1715 : :
1716 [ + + ]: 48 : if (i > 0)
1717 : 14 : Tcl_DStringAppend(&proc_internal_args, " ", -1);
1718 : 48 : Tcl_DStringAppend(&proc_internal_args, buf, -1);
1719 : :
1720 : 48 : ReleaseSysCache(typeTup);
1721 : : }
1722 : : }
1723 [ + + ]: 9 : else if (is_trigger)
1724 : : {
1725 : : /* trigger procedure has fixed args */
1726 : 8 : Tcl_DStringAppend(&proc_internal_args,
1727 : : "TG_name TG_relid TG_table_name TG_table_schema TG_relatts TG_when TG_level TG_op __PLTcl_Tup_NEW __PLTcl_Tup_OLD args",
1728 : : -1);
1729 : : }
1730 [ + - ]: 1 : else if (is_event_trigger)
1731 : : {
1732 : : /* event trigger procedure has fixed args */
1733 : 1 : Tcl_DStringAppend(&proc_internal_args, "TG_event TG_tag", -1);
1734 : : }
1735 : :
1736 : : /************************************************************
1737 : : * Create the tcl command to define the internal
1738 : : * procedure
1739 : : *
1740 : : * Leave this code as DString - performance is not critical here,
1741 : : * and we don't want to duplicate the knowledge of the Tcl quoting
1742 : : * rules that's embedded in Tcl_DStringAppendElement.
1743 : : ************************************************************/
1744 : 62 : Tcl_DStringAppendElement(&proc_internal_def, "proc");
1745 : 62 : Tcl_DStringAppendElement(&proc_internal_def, internal_proname);
1746 : 62 : Tcl_DStringAppendElement(&proc_internal_def,
1747 : 62 : Tcl_DStringValue(&proc_internal_args));
1748 : :
1749 : : /************************************************************
1750 : : * prefix procedure body with
1751 : : * upvar #0 <internal_proname> GD
1752 : : * and with appropriate setting of arguments
1753 : : ************************************************************/
1754 : 62 : Tcl_DStringAppend(&proc_internal_body, "upvar #0 ", -1);
1755 : 62 : Tcl_DStringAppend(&proc_internal_body, internal_proname, -1);
1756 : 62 : Tcl_DStringAppend(&proc_internal_body, " GD\n", -1);
1757 [ + + ]: 62 : if (is_trigger)
1758 : : {
1759 : 8 : Tcl_DStringAppend(&proc_internal_body,
1760 : : "array set NEW $__PLTcl_Tup_NEW\n", -1);
1761 : 8 : Tcl_DStringAppend(&proc_internal_body,
1762 : : "array set OLD $__PLTcl_Tup_OLD\n", -1);
1763 : 8 : Tcl_DStringAppend(&proc_internal_body,
1764 : : "set i 0\n"
1765 : : "set v 0\n"
1766 : : "foreach v $args {\n"
1767 : : " incr i\n"
1768 : : " set $i $v\n"
1769 : : "}\n"
1770 : : "unset i v\n\n", -1);
1771 : : }
1772 [ + + ]: 54 : else if (is_event_trigger)
1773 : : {
1774 : : /* no argument support for event triggers */
1775 : : }
1776 : : else
1777 : : {
1778 [ + + ]: 101 : for (i = 0; i < prodesc->nargs; i++)
1779 : : {
1780 [ + + ]: 48 : if (prodesc->arg_is_rowtype[i])
1781 : : {
1782 : 4 : snprintf(buf, sizeof(buf),
1783 : : "array set %d $__PLTcl_Tup_%d\n",
1784 : : i + 1, i + 1);
1785 : 4 : Tcl_DStringAppend(&proc_internal_body, buf, -1);
1786 : : }
1787 : : }
1788 : : }
1789 : :
1790 : : /************************************************************
1791 : : * Add user's function definition to proc body
1792 : : ************************************************************/
1793 : 62 : prosrcdatum = SysCacheGetAttrNotNull(PROCOID, procTup,
1794 : : Anum_pg_proc_prosrc);
1795 : 62 : proc_source = TextDatumGetCString(prosrcdatum);
1796 : 62 : UTF_BEGIN;
1797 : 62 : Tcl_DStringAppend(&proc_internal_body, UTF_E2U(proc_source), -1);
1798 [ - + ]: 62 : UTF_END;
1799 : 62 : pfree(proc_source);
1800 : 62 : Tcl_DStringAppendElement(&proc_internal_def,
1801 : 62 : Tcl_DStringValue(&proc_internal_body));
1802 : :
1803 : : /************************************************************
1804 : : * Create the procedure in the interpreter
1805 : : ************************************************************/
1806 : 124 : tcl_rc = Tcl_EvalEx(interp,
1807 : 62 : Tcl_DStringValue(&proc_internal_def),
1808 : : Tcl_DStringLength(&proc_internal_def),
1809 : : TCL_EVAL_GLOBAL);
1810 [ - + ]: 62 : if (tcl_rc != TCL_OK)
1811 [ # # ]: 0 : ereport(ERROR,
1812 : : (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1813 : : errmsg("could not create internal procedure \"%s\": %s",
1814 : : internal_proname,
1815 : : utf_u2e(Tcl_GetStringResult(interp)))));
1816 : : }
1817 : 3 : PG_CATCH();
1818 : : {
1819 : : /*
1820 : : * If we failed anywhere above, clean up whatever got allocated. It
1821 : : * should all be in the proc_cxt, except for the DStrings.
1822 : : */
1823 [ - + ]: 3 : if (proc_cxt)
1824 : 0 : MemoryContextDelete(proc_cxt);
1825 : 3 : Tcl_DStringFree(&proc_internal_def);
1826 : 3 : Tcl_DStringFree(&proc_internal_name);
1827 : 3 : Tcl_DStringFree(&proc_internal_body);
1828 : 3 : Tcl_DStringFree(&proc_internal_args);
1829 : 3 : PG_RE_THROW();
1830 : : }
1831 [ - + ]: 62 : PG_END_TRY();
1832 : :
1833 : : /*
1834 : : * Install the new proc description block in the hashtable, incrementing
1835 : : * its refcount (the hashtable link counts as a reference). Then, if
1836 : : * there was a previous definition of the function, decrement that one's
1837 : : * refcount, and delete it if no longer referenced. The order of
1838 : : * operations here is important: if something goes wrong during the
1839 : : * MemoryContextDelete, leaking some memory for the old definition is OK,
1840 : : * but we don't want to corrupt the live hashtable entry. (Likewise,
1841 : : * freeing the DStrings is pretty low priority if that happens.)
1842 : : */
1843 : 62 : old_prodesc = proc_ptr->proc_ptr;
1844 : :
1845 : 62 : proc_ptr->proc_ptr = prodesc;
1846 : 62 : prodesc->fn_refcount++;
1847 : :
1848 [ + + ]: 62 : if (old_prodesc != NULL)
1849 : : {
1850 : : Assert(old_prodesc->fn_refcount > 0);
1851 [ + + ]: 2 : if (--old_prodesc->fn_refcount == 0)
1852 : 1 : MemoryContextDelete(old_prodesc->fn_cxt);
1853 : : }
1854 : :
1855 : 62 : Tcl_DStringFree(&proc_internal_def);
1856 : 62 : Tcl_DStringFree(&proc_internal_name);
1857 : 62 : Tcl_DStringFree(&proc_internal_body);
1858 : 62 : Tcl_DStringFree(&proc_internal_args);
1859 : :
1860 : 62 : ReleaseSysCache(procTup);
1861 : :
1862 : 62 : return prodesc;
1863 : : }
1864 : :
1865 : :
1866 : : /**********************************************************************
1867 : : * pltcl_elog() - elog() support for PLTcl
1868 : : **********************************************************************/
1869 : : static int
1870 : 266 : pltcl_elog(ClientData cdata, Tcl_Interp *interp,
1871 : : int objc, Tcl_Obj *const objv[])
1872 : : {
1873 : : volatile int level;
1874 : : MemoryContext oldcontext;
1875 : : int priIndex;
1876 : :
1877 : : static const char *logpriorities[] = {
1878 : : "DEBUG", "LOG", "INFO", "NOTICE",
1879 : : "WARNING", "ERROR", "FATAL", (const char *) NULL
1880 : : };
1881 : :
1882 : : static const int loglevels[] = {
1883 : : DEBUG2, LOG, INFO, NOTICE,
1884 : : WARNING, ERROR, FATAL
1885 : : };
1886 : :
1887 [ + + ]: 266 : if (objc != 3)
1888 : : {
1889 : 1 : Tcl_WrongNumArgs(interp, 1, objv, "level msg");
1890 : 1 : return TCL_ERROR;
1891 : : }
1892 : :
1893 [ + + ]: 265 : if (Tcl_GetIndexFromObj(interp, objv[1], logpriorities, "priority",
1894 : : TCL_EXACT, &priIndex) != TCL_OK)
1895 : 1 : return TCL_ERROR;
1896 : :
1897 : 264 : level = loglevels[priIndex];
1898 : :
1899 [ + + ]: 264 : if (level == ERROR)
1900 : : {
1901 : : /*
1902 : : * We just pass the error back to Tcl. If it's not caught, it'll
1903 : : * eventually get converted to a PG error when we reach the call
1904 : : * handler.
1905 : : */
1906 : 6 : Tcl_SetObjResult(interp, objv[2]);
1907 : 6 : return TCL_ERROR;
1908 : : }
1909 : :
1910 : : /*
1911 : : * For non-error messages, just pass 'em to ereport(). We do not expect
1912 : : * that this will fail, but just on the off chance it does, report the
1913 : : * error back to Tcl. Note we are assuming that ereport() can't have any
1914 : : * internal failures that are so bad as to require a transaction abort.
1915 : : *
1916 : : * This path is also used for FATAL errors, which aren't going to come
1917 : : * back to us at all.
1918 : : */
1919 : 258 : oldcontext = CurrentMemoryContext;
1920 [ + - ]: 258 : PG_TRY();
1921 : : {
1922 : 258 : UTF_BEGIN;
1923 [ + - ]: 258 : ereport(level,
1924 : : (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1925 : : errmsg("%s", UTF_U2E(Tcl_GetString(objv[2])))));
1926 [ - + ]: 258 : UTF_END;
1927 : : }
1928 : 0 : PG_CATCH();
1929 : : {
1930 : : ErrorData *edata;
1931 : :
1932 : : /* Must reset elog.c's state */
1933 : 0 : MemoryContextSwitchTo(oldcontext);
1934 : 0 : edata = CopyErrorData();
1935 : 0 : FlushErrorState();
1936 : :
1937 : : /* Pass the error data to Tcl */
1938 : 0 : pltcl_construct_errorCode(interp, edata);
1939 : 0 : UTF_BEGIN;
1940 : 0 : Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
1941 [ # # ]: 0 : UTF_END;
1942 : 0 : FreeErrorData(edata);
1943 : :
1944 : 0 : return TCL_ERROR;
1945 : : }
1946 [ - + ]: 258 : PG_END_TRY();
1947 : :
1948 : 258 : return TCL_OK;
1949 : : }
1950 : :
1951 : :
1952 : : /**********************************************************************
1953 : : * pltcl_construct_errorCode() - construct a Tcl errorCode
1954 : : * list with detailed information from the PostgreSQL server
1955 : : **********************************************************************/
1956 : : static void
1957 : 18 : pltcl_construct_errorCode(Tcl_Interp *interp, ErrorData *edata)
1958 : : {
1959 : 18 : Tcl_Obj *obj = Tcl_NewObj();
1960 : :
1961 : 18 : Tcl_ListObjAppendElement(interp, obj,
1962 : : Tcl_NewStringObj("POSTGRES", -1));
1963 : 18 : Tcl_ListObjAppendElement(interp, obj,
1964 : : Tcl_NewStringObj(PG_VERSION, -1));
1965 : 18 : Tcl_ListObjAppendElement(interp, obj,
1966 : : Tcl_NewStringObj("SQLSTATE", -1));
1967 : 18 : Tcl_ListObjAppendElement(interp, obj,
1968 : 18 : Tcl_NewStringObj(unpack_sql_state(edata->sqlerrcode), -1));
1969 : 18 : Tcl_ListObjAppendElement(interp, obj,
1970 : : Tcl_NewStringObj("condition", -1));
1971 : 18 : Tcl_ListObjAppendElement(interp, obj,
1972 : : Tcl_NewStringObj(pltcl_get_condition_name(edata->sqlerrcode), -1));
1973 : 18 : Tcl_ListObjAppendElement(interp, obj,
1974 : : Tcl_NewStringObj("message", -1));
1975 : 18 : UTF_BEGIN;
1976 : 18 : Tcl_ListObjAppendElement(interp, obj,
1977 : 18 : Tcl_NewStringObj(UTF_E2U(edata->message), -1));
1978 [ - + ]: 18 : UTF_END;
1979 [ + + ]: 18 : if (edata->detail)
1980 : : {
1981 : 3 : Tcl_ListObjAppendElement(interp, obj,
1982 : : Tcl_NewStringObj("detail", -1));
1983 : 3 : UTF_BEGIN;
1984 : 3 : Tcl_ListObjAppendElement(interp, obj,
1985 : 3 : Tcl_NewStringObj(UTF_E2U(edata->detail), -1));
1986 [ - + ]: 3 : UTF_END;
1987 : : }
1988 [ + + ]: 18 : if (edata->hint)
1989 : : {
1990 : 1 : Tcl_ListObjAppendElement(interp, obj,
1991 : : Tcl_NewStringObj("hint", -1));
1992 : 1 : UTF_BEGIN;
1993 : 1 : Tcl_ListObjAppendElement(interp, obj,
1994 : 1 : Tcl_NewStringObj(UTF_E2U(edata->hint), -1));
1995 [ - + ]: 1 : UTF_END;
1996 : : }
1997 [ + + ]: 18 : if (edata->context)
1998 : : {
1999 : 9 : Tcl_ListObjAppendElement(interp, obj,
2000 : : Tcl_NewStringObj("context", -1));
2001 : 9 : UTF_BEGIN;
2002 : 9 : Tcl_ListObjAppendElement(interp, obj,
2003 : 9 : Tcl_NewStringObj(UTF_E2U(edata->context), -1));
2004 [ - + ]: 9 : UTF_END;
2005 : : }
2006 [ + + ]: 18 : if (edata->schema_name)
2007 : : {
2008 : 3 : Tcl_ListObjAppendElement(interp, obj,
2009 : : Tcl_NewStringObj("schema", -1));
2010 : 3 : UTF_BEGIN;
2011 : 3 : Tcl_ListObjAppendElement(interp, obj,
2012 : 3 : Tcl_NewStringObj(UTF_E2U(edata->schema_name), -1));
2013 [ - + ]: 3 : UTF_END;
2014 : : }
2015 [ + + ]: 18 : if (edata->table_name)
2016 : : {
2017 : 3 : Tcl_ListObjAppendElement(interp, obj,
2018 : : Tcl_NewStringObj("table", -1));
2019 : 3 : UTF_BEGIN;
2020 : 3 : Tcl_ListObjAppendElement(interp, obj,
2021 : 3 : Tcl_NewStringObj(UTF_E2U(edata->table_name), -1));
2022 [ - + ]: 3 : UTF_END;
2023 : : }
2024 [ + + ]: 18 : if (edata->column_name)
2025 : : {
2026 : 1 : Tcl_ListObjAppendElement(interp, obj,
2027 : : Tcl_NewStringObj("column", -1));
2028 : 1 : UTF_BEGIN;
2029 : 1 : Tcl_ListObjAppendElement(interp, obj,
2030 : 1 : Tcl_NewStringObj(UTF_E2U(edata->column_name), -1));
2031 [ - + ]: 1 : UTF_END;
2032 : : }
2033 [ + + ]: 18 : if (edata->datatype_name)
2034 : : {
2035 : 1 : Tcl_ListObjAppendElement(interp, obj,
2036 : : Tcl_NewStringObj("datatype", -1));
2037 : 1 : UTF_BEGIN;
2038 : 1 : Tcl_ListObjAppendElement(interp, obj,
2039 : 1 : Tcl_NewStringObj(UTF_E2U(edata->datatype_name), -1));
2040 [ - + ]: 1 : UTF_END;
2041 : : }
2042 [ + + ]: 18 : if (edata->constraint_name)
2043 : : {
2044 : 3 : Tcl_ListObjAppendElement(interp, obj,
2045 : : Tcl_NewStringObj("constraint", -1));
2046 : 3 : UTF_BEGIN;
2047 : 3 : Tcl_ListObjAppendElement(interp, obj,
2048 : 3 : Tcl_NewStringObj(UTF_E2U(edata->constraint_name), -1));
2049 [ - + ]: 3 : UTF_END;
2050 : : }
2051 : : /* cursorpos is never interesting here; report internal query/pos */
2052 [ + + ]: 18 : if (edata->internalquery)
2053 : : {
2054 : 4 : Tcl_ListObjAppendElement(interp, obj,
2055 : : Tcl_NewStringObj("statement", -1));
2056 : 4 : UTF_BEGIN;
2057 : 4 : Tcl_ListObjAppendElement(interp, obj,
2058 : 4 : Tcl_NewStringObj(UTF_E2U(edata->internalquery), -1));
2059 [ - + ]: 4 : UTF_END;
2060 : : }
2061 [ + + ]: 18 : if (edata->internalpos > 0)
2062 : : {
2063 : 4 : Tcl_ListObjAppendElement(interp, obj,
2064 : : Tcl_NewStringObj("cursor_position", -1));
2065 : 4 : Tcl_ListObjAppendElement(interp, obj,
2066 : : Tcl_NewIntObj(edata->internalpos));
2067 : : }
2068 [ + - ]: 18 : if (edata->filename)
2069 : : {
2070 : 18 : Tcl_ListObjAppendElement(interp, obj,
2071 : : Tcl_NewStringObj("filename", -1));
2072 : 18 : UTF_BEGIN;
2073 : 18 : Tcl_ListObjAppendElement(interp, obj,
2074 : 18 : Tcl_NewStringObj(UTF_E2U(edata->filename), -1));
2075 [ - + ]: 18 : UTF_END;
2076 : : }
2077 [ + - ]: 18 : if (edata->lineno > 0)
2078 : : {
2079 : 18 : Tcl_ListObjAppendElement(interp, obj,
2080 : : Tcl_NewStringObj("lineno", -1));
2081 : 18 : Tcl_ListObjAppendElement(interp, obj,
2082 : : Tcl_NewIntObj(edata->lineno));
2083 : : }
2084 [ + - ]: 18 : if (edata->funcname)
2085 : : {
2086 : 18 : Tcl_ListObjAppendElement(interp, obj,
2087 : : Tcl_NewStringObj("funcname", -1));
2088 : 18 : UTF_BEGIN;
2089 : 18 : Tcl_ListObjAppendElement(interp, obj,
2090 : 18 : Tcl_NewStringObj(UTF_E2U(edata->funcname), -1));
2091 [ - + ]: 18 : UTF_END;
2092 : : }
2093 : :
2094 : 18 : Tcl_SetObjErrorCode(interp, obj);
2095 : 18 : }
2096 : :
2097 : :
2098 : : /**********************************************************************
2099 : : * pltcl_get_condition_name() - find name for SQLSTATE
2100 : : **********************************************************************/
2101 : : static const char *
2102 : 18 : pltcl_get_condition_name(int sqlstate)
2103 : : {
2104 : : int i;
2105 : :
2106 [ + - ]: 2295 : for (i = 0; exception_name_map[i].label != NULL; i++)
2107 : : {
2108 [ + + ]: 2295 : if (exception_name_map[i].sqlerrstate == sqlstate)
2109 : 18 : return exception_name_map[i].label;
2110 : : }
2111 : 0 : return "unrecognized_sqlstate";
2112 : : }
2113 : :
2114 : :
2115 : : /**********************************************************************
2116 : : * pltcl_quote() - quote literal strings that are to
2117 : : * be used in SPI_execute query strings
2118 : : **********************************************************************/
2119 : : static int
2120 : 11 : pltcl_quote(ClientData cdata, Tcl_Interp *interp,
2121 : : int objc, Tcl_Obj *const objv[])
2122 : : {
2123 : : char *tmp;
2124 : : const char *cp1;
2125 : : char *cp2;
2126 : : Tcl_Size length;
2127 : :
2128 : : /************************************************************
2129 : : * Check call syntax
2130 : : ************************************************************/
2131 [ + + ]: 11 : if (objc != 2)
2132 : : {
2133 : 1 : Tcl_WrongNumArgs(interp, 1, objv, "string");
2134 : 1 : return TCL_ERROR;
2135 : : }
2136 : :
2137 : : /************************************************************
2138 : : * Allocate space for the maximum the string can
2139 : : * grow to and initialize pointers
2140 : : ************************************************************/
2141 : 10 : cp1 = Tcl_GetStringFromObj(objv[1], &length);
2142 : 10 : tmp = palloc(add_size(mul_size(length, 2), 1));
2143 : 10 : cp2 = tmp;
2144 : :
2145 : : /************************************************************
2146 : : * Walk through string and double every quote and backslash
2147 : : ************************************************************/
2148 [ + + ]: 56 : while (*cp1)
2149 : : {
2150 [ + + ]: 46 : if (*cp1 == '\'')
2151 : 1 : *cp2++ = '\'';
2152 : : else
2153 : : {
2154 [ + + ]: 45 : if (*cp1 == '\\')
2155 : 1 : *cp2++ = '\\';
2156 : : }
2157 : 46 : *cp2++ = *cp1++;
2158 : : }
2159 : :
2160 : : /************************************************************
2161 : : * Terminate the string and set it as result
2162 : : ************************************************************/
2163 : 10 : *cp2 = '\0';
2164 : 10 : Tcl_SetObjResult(interp, Tcl_NewStringObj(tmp, -1));
2165 : 10 : pfree(tmp);
2166 : 10 : return TCL_OK;
2167 : : }
2168 : :
2169 : :
2170 : : /**********************************************************************
2171 : : * pltcl_argisnull() - determine if a specific argument is NULL
2172 : : **********************************************************************/
2173 : : static int
2174 : 7 : pltcl_argisnull(ClientData cdata, Tcl_Interp *interp,
2175 : : int objc, Tcl_Obj *const objv[])
2176 : : {
2177 : : int argno;
2178 : 7 : FunctionCallInfo fcinfo = pltcl_current_call_state->fcinfo;
2179 : :
2180 : : /************************************************************
2181 : : * Check call syntax
2182 : : ************************************************************/
2183 [ + + ]: 7 : if (objc != 2)
2184 : : {
2185 : 1 : Tcl_WrongNumArgs(interp, 1, objv, "argno");
2186 : 1 : return TCL_ERROR;
2187 : : }
2188 : :
2189 : : /************************************************************
2190 : : * Check that we're called as a normal function
2191 : : ************************************************************/
2192 [ + + ]: 6 : if (fcinfo == NULL)
2193 : : {
2194 : 1 : Tcl_SetObjResult(interp,
2195 : : Tcl_NewStringObj("argisnull cannot be used in triggers", -1));
2196 : 1 : return TCL_ERROR;
2197 : : }
2198 : :
2199 : : /************************************************************
2200 : : * Get the argument number
2201 : : ************************************************************/
2202 [ + + ]: 5 : if (Tcl_GetIntFromObj(interp, objv[1], &argno) != TCL_OK)
2203 : 1 : return TCL_ERROR;
2204 : :
2205 : : /************************************************************
2206 : : * Check that the argno is valid
2207 : : ************************************************************/
2208 : 4 : argno--;
2209 [ + - + + ]: 4 : if (argno < 0 || argno >= fcinfo->nargs)
2210 : : {
2211 : 1 : Tcl_SetObjResult(interp,
2212 : : Tcl_NewStringObj("argno out of range", -1));
2213 : 1 : return TCL_ERROR;
2214 : : }
2215 : :
2216 : : /************************************************************
2217 : : * Get the requested NULL state
2218 : : ************************************************************/
2219 : 3 : Tcl_SetObjResult(interp, Tcl_NewBooleanObj(PG_ARGISNULL(argno)));
2220 : 3 : return TCL_OK;
2221 : : }
2222 : :
2223 : :
2224 : : /**********************************************************************
2225 : : * pltcl_returnnull() - Cause a NULL return from the current function
2226 : : **********************************************************************/
2227 : : static int
2228 : 3 : pltcl_returnnull(ClientData cdata, Tcl_Interp *interp,
2229 : : int objc, Tcl_Obj *const objv[])
2230 : : {
2231 : 3 : FunctionCallInfo fcinfo = pltcl_current_call_state->fcinfo;
2232 : :
2233 : : /************************************************************
2234 : : * Check call syntax
2235 : : ************************************************************/
2236 [ + + ]: 3 : if (objc != 1)
2237 : : {
2238 : 1 : Tcl_WrongNumArgs(interp, 1, objv, "");
2239 : 1 : return TCL_ERROR;
2240 : : }
2241 : :
2242 : : /************************************************************
2243 : : * Check that we're called as a normal function
2244 : : ************************************************************/
2245 [ + + ]: 2 : if (fcinfo == NULL)
2246 : : {
2247 : 1 : Tcl_SetObjResult(interp,
2248 : : Tcl_NewStringObj("return_null cannot be used in triggers", -1));
2249 : 1 : return TCL_ERROR;
2250 : : }
2251 : :
2252 : : /************************************************************
2253 : : * Set the NULL return flag and cause Tcl to return from the
2254 : : * procedure.
2255 : : ************************************************************/
2256 : 1 : fcinfo->isnull = true;
2257 : :
2258 : 1 : return TCL_RETURN;
2259 : : }
2260 : :
2261 : :
2262 : : /**********************************************************************
2263 : : * pltcl_returnnext() - Add a row to the result tuplestore in a SRF.
2264 : : **********************************************************************/
2265 : : static int
2266 : 18 : pltcl_returnnext(ClientData cdata, Tcl_Interp *interp,
2267 : : int objc, Tcl_Obj *const objv[])
2268 : : {
2269 : 18 : pltcl_call_state *call_state = pltcl_current_call_state;
2270 : 18 : FunctionCallInfo fcinfo = call_state->fcinfo;
2271 : 18 : pltcl_proc_desc *prodesc = call_state->prodesc;
2272 : 18 : MemoryContext oldcontext = CurrentMemoryContext;
2273 : 18 : ResourceOwner oldowner = CurrentResourceOwner;
2274 : 18 : volatile int result = TCL_OK;
2275 : :
2276 : : /*
2277 : : * Check that we're called as a set-returning function
2278 : : */
2279 [ - + ]: 18 : if (fcinfo == NULL)
2280 : : {
2281 : 0 : Tcl_SetObjResult(interp,
2282 : : Tcl_NewStringObj("return_next cannot be used in triggers", -1));
2283 : 0 : return TCL_ERROR;
2284 : : }
2285 : :
2286 [ + + ]: 18 : if (!prodesc->fn_retisset)
2287 : : {
2288 : 1 : Tcl_SetObjResult(interp,
2289 : : Tcl_NewStringObj("return_next cannot be used in non-set-returning functions", -1));
2290 : 1 : return TCL_ERROR;
2291 : : }
2292 : :
2293 : : /*
2294 : : * Check call syntax
2295 : : */
2296 [ - + ]: 17 : if (objc != 2)
2297 : : {
2298 : 0 : Tcl_WrongNumArgs(interp, 1, objv, "result");
2299 : 0 : return TCL_ERROR;
2300 : : }
2301 : :
2302 : : /*
2303 : : * The rest might throw elog(ERROR), so must run in a subtransaction.
2304 : : *
2305 : : * A small advantage of using a subtransaction is that it provides a
2306 : : * short-lived memory context for free, so we needn't worry about leaking
2307 : : * memory here. To use that context, call BeginInternalSubTransaction
2308 : : * directly instead of going through pltcl_subtrans_begin.
2309 : : */
2310 : 17 : BeginInternalSubTransaction(NULL);
2311 [ + + ]: 17 : PG_TRY();
2312 : : {
2313 : : /* Set up tuple store if first output row */
2314 [ + + ]: 17 : if (call_state->tuple_store == NULL)
2315 : 5 : pltcl_init_tuple_store(call_state);
2316 : :
2317 [ + + ]: 17 : if (prodesc->fn_retistuple)
2318 : : {
2319 : : Tcl_Obj **rowObjv;
2320 : : Tcl_Size rowObjc;
2321 : :
2322 : : /* result should be a list, so break it down */
2323 [ - + ]: 7 : if (Tcl_ListObjGetElements(interp, objv[1], &rowObjc, &rowObjv) == TCL_ERROR)
2324 : 0 : result = TCL_ERROR;
2325 : : else
2326 : : {
2327 : : HeapTuple tuple;
2328 : :
2329 : 7 : tuple = pltcl_build_tuple_result(interp, rowObjv, rowObjc,
2330 : : call_state);
2331 : 5 : tuplestore_puttuple(call_state->tuple_store, tuple);
2332 : : }
2333 : : }
2334 : : else
2335 : : {
2336 : : Datum retval;
2337 : 10 : bool isNull = false;
2338 : :
2339 : : /* for paranoia's sake, check that tupdesc has exactly one column */
2340 [ - + ]: 10 : if (call_state->ret_tupdesc->natts != 1)
2341 [ # # ]: 0 : elog(ERROR, "wrong result type supplied in return_next");
2342 : :
2343 : : /* as in pltcl_func_handler, copy the string out of Tcl */
2344 : 30 : retval = InputFunctionCall(&prodesc->result_in_func,
2345 : 10 : utf_u2e_copy(Tcl_GetString(objv[1])),
2346 : : prodesc->result_typioparam,
2347 : : -1);
2348 : 10 : tuplestore_putvalues(call_state->tuple_store, call_state->ret_tupdesc,
2349 : : &retval, &isNull);
2350 : : }
2351 : :
2352 : 15 : pltcl_subtrans_commit(oldcontext, oldowner);
2353 : : }
2354 : 2 : PG_CATCH();
2355 : : {
2356 : 2 : pltcl_subtrans_abort(interp, oldcontext, oldowner);
2357 : 2 : return TCL_ERROR;
2358 : : }
2359 [ - + ]: 15 : PG_END_TRY();
2360 : :
2361 : 15 : return result;
2362 : : }
2363 : :
2364 : :
2365 : : /*----------
2366 : : * Support for running SPI operations inside subtransactions
2367 : : *
2368 : : * Intended usage pattern is:
2369 : : *
2370 : : * MemoryContext oldcontext = CurrentMemoryContext;
2371 : : * ResourceOwner oldowner = CurrentResourceOwner;
2372 : : *
2373 : : * ...
2374 : : * pltcl_subtrans_begin(oldcontext, oldowner);
2375 : : * PG_TRY();
2376 : : * {
2377 : : * do something risky;
2378 : : * pltcl_subtrans_commit(oldcontext, oldowner);
2379 : : * }
2380 : : * PG_CATCH();
2381 : : * {
2382 : : * pltcl_subtrans_abort(interp, oldcontext, oldowner);
2383 : : * return TCL_ERROR;
2384 : : * }
2385 : : * PG_END_TRY();
2386 : : * return TCL_OK;
2387 : : *----------
2388 : : */
2389 : : static void
2390 : 124 : pltcl_subtrans_begin(MemoryContext oldcontext, ResourceOwner oldowner)
2391 : : {
2392 : 124 : BeginInternalSubTransaction(NULL);
2393 : :
2394 : : /* Want to run inside function's memory context */
2395 : 124 : MemoryContextSwitchTo(oldcontext);
2396 : 124 : }
2397 : :
2398 : : static void
2399 : 129 : pltcl_subtrans_commit(MemoryContext oldcontext, ResourceOwner oldowner)
2400 : : {
2401 : : /* Commit the inner transaction, return to outer xact context */
2402 : 129 : ReleaseCurrentSubTransaction();
2403 : 129 : MemoryContextSwitchTo(oldcontext);
2404 : 129 : CurrentResourceOwner = oldowner;
2405 : 129 : }
2406 : :
2407 : : static void
2408 : 12 : pltcl_subtrans_abort(Tcl_Interp *interp,
2409 : : MemoryContext oldcontext, ResourceOwner oldowner)
2410 : : {
2411 : : ErrorData *edata;
2412 : :
2413 : : /* Save error info */
2414 : 12 : MemoryContextSwitchTo(oldcontext);
2415 : 12 : edata = CopyErrorData();
2416 : 12 : FlushErrorState();
2417 : :
2418 : : /* Abort the inner transaction */
2419 : 12 : RollbackAndReleaseCurrentSubTransaction();
2420 : 12 : MemoryContextSwitchTo(oldcontext);
2421 : 12 : CurrentResourceOwner = oldowner;
2422 : :
2423 : : /* Pass the error data to Tcl */
2424 : 12 : pltcl_construct_errorCode(interp, edata);
2425 : 12 : UTF_BEGIN;
2426 : 12 : Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
2427 [ - + ]: 12 : UTF_END;
2428 : 12 : FreeErrorData(edata);
2429 : 12 : }
2430 : :
2431 : :
2432 : : /**********************************************************************
2433 : : * pltcl_SPI_execute() - The builtin SPI_execute command
2434 : : * for the Tcl interpreter
2435 : : **********************************************************************/
2436 : : static int
2437 : 65 : pltcl_SPI_execute(ClientData cdata, Tcl_Interp *interp,
2438 : : int objc, Tcl_Obj *const objv[])
2439 : : {
2440 : : int my_rc;
2441 : : int spi_rc;
2442 : : int query_idx;
2443 : : int i;
2444 : : int optIndex;
2445 : 65 : int count = 0;
2446 : 65 : const char *volatile arrayname = NULL;
2447 : 65 : Tcl_Obj *volatile loop_body = NULL;
2448 : 65 : MemoryContext oldcontext = CurrentMemoryContext;
2449 : 65 : ResourceOwner oldowner = CurrentResourceOwner;
2450 : :
2451 : : enum options
2452 : : {
2453 : : OPT_ARRAY, OPT_COUNT
2454 : : };
2455 : :
2456 : : static const char *options[] = {
2457 : : "-array", "-count", (const char *) NULL
2458 : : };
2459 : :
2460 : : /************************************************************
2461 : : * Check the call syntax and get the options
2462 : : ************************************************************/
2463 [ + + ]: 65 : if (objc < 2)
2464 : : {
2465 : 1 : Tcl_WrongNumArgs(interp, 1, objv,
2466 : : "?-count n? ?-array name? query ?loop body?");
2467 : 1 : return TCL_ERROR;
2468 : : }
2469 : :
2470 : 64 : i = 1;
2471 [ + - ]: 136 : while (i < objc)
2472 : : {
2473 [ + + ]: 72 : if (Tcl_GetIndexFromObj(NULL, objv[i], options, NULL,
2474 : : TCL_EXACT, &optIndex) != TCL_OK)
2475 : 61 : break;
2476 : :
2477 [ + + ]: 11 : if (++i >= objc)
2478 : : {
2479 : 2 : Tcl_SetObjResult(interp,
2480 : : Tcl_NewStringObj("missing argument to -count or -array", -1));
2481 : 2 : return TCL_ERROR;
2482 : : }
2483 : :
2484 [ - + + ]: 9 : switch ((enum options) optIndex)
2485 : : {
2486 : 8 : case OPT_ARRAY:
2487 : 8 : arrayname = Tcl_GetString(objv[i++]);
2488 : 8 : break;
2489 : :
2490 : 1 : case OPT_COUNT:
2491 [ + - ]: 1 : if (Tcl_GetIntFromObj(interp, objv[i++], &count) != TCL_OK)
2492 : 1 : return TCL_ERROR;
2493 : 0 : break;
2494 : : }
2495 : : }
2496 : :
2497 : 61 : query_idx = i;
2498 [ + - + + ]: 61 : if (query_idx >= objc || query_idx + 2 < objc)
2499 : : {
2500 : 1 : Tcl_WrongNumArgs(interp, query_idx - 1, objv, "query ?loop body?");
2501 : 1 : return TCL_ERROR;
2502 : : }
2503 : :
2504 [ + + ]: 60 : if (query_idx + 1 < objc)
2505 : 8 : loop_body = objv[query_idx + 1];
2506 : :
2507 : : /************************************************************
2508 : : * Execute the query inside a sub-transaction, so we can cope with
2509 : : * errors sanely
2510 : : ************************************************************/
2511 : :
2512 : 60 : pltcl_subtrans_begin(oldcontext, oldowner);
2513 : :
2514 [ + + ]: 60 : PG_TRY();
2515 : : {
2516 : 60 : UTF_BEGIN;
2517 : 60 : spi_rc = SPI_execute(UTF_U2E(Tcl_GetString(objv[query_idx])),
2518 : 60 : pltcl_current_call_state->prodesc->fn_readonly, count);
2519 [ - + ]: 52 : UTF_END;
2520 : :
2521 : 52 : my_rc = pltcl_process_SPI_result(interp,
2522 : : arrayname,
2523 : : loop_body,
2524 : : spi_rc,
2525 : : SPI_tuptable,
2526 : : SPI_processed);
2527 : :
2528 : 52 : pltcl_subtrans_commit(oldcontext, oldowner);
2529 : : }
2530 : 8 : PG_CATCH();
2531 : : {
2532 : 8 : pltcl_subtrans_abort(interp, oldcontext, oldowner);
2533 : 8 : return TCL_ERROR;
2534 : : }
2535 [ - + ]: 52 : PG_END_TRY();
2536 : :
2537 : 52 : return my_rc;
2538 : : }
2539 : :
2540 : : /*
2541 : : * Process the result from SPI_execute or SPI_execute_plan
2542 : : *
2543 : : * Shared code between pltcl_SPI_execute and pltcl_SPI_execute_plan
2544 : : */
2545 : : static int
2546 : 101 : pltcl_process_SPI_result(Tcl_Interp *interp,
2547 : : const char *arrayname,
2548 : : Tcl_Obj *loop_body,
2549 : : int spi_rc,
2550 : : SPITupleTable *tuptable,
2551 : : uint64 ntuples)
2552 : : {
2553 : 101 : int my_rc = TCL_OK;
2554 : : int loop_rc;
2555 : : HeapTuple *tuples;
2556 : : TupleDesc tupdesc;
2557 : :
2558 [ + + + + ]: 101 : switch (spi_rc)
2559 : : {
2560 : 37 : case SPI_OK_SELINTO:
2561 : : case SPI_OK_INSERT:
2562 : : case SPI_OK_DELETE:
2563 : : case SPI_OK_UPDATE:
2564 : : case SPI_OK_MERGE:
2565 : 37 : Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
2566 : 37 : break;
2567 : :
2568 : 1 : case SPI_OK_UTILITY:
2569 : : case SPI_OK_REWRITTEN:
2570 [ + - ]: 1 : if (tuptable == NULL)
2571 : : {
2572 : 1 : Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
2573 : 1 : break;
2574 : : }
2575 : : /* fall through for utility returning tuples */
2576 : : pg_fallthrough;
2577 : :
2578 : : case SPI_OK_SELECT:
2579 : : case SPI_OK_INSERT_RETURNING:
2580 : : case SPI_OK_DELETE_RETURNING:
2581 : : case SPI_OK_UPDATE_RETURNING:
2582 : : case SPI_OK_MERGE_RETURNING:
2583 : :
2584 : : /*
2585 : : * Process the tuples we got
2586 : : */
2587 : 62 : tuples = tuptable->vals;
2588 : 62 : tupdesc = tuptable->tupdesc;
2589 : :
2590 [ + + ]: 62 : if (loop_body == NULL)
2591 : : {
2592 : : /*
2593 : : * If there is no loop body given, just set the variables from
2594 : : * the first tuple (if any)
2595 : : */
2596 [ + + ]: 50 : if (ntuples > 0)
2597 : 29 : pltcl_set_tuple_values(interp, arrayname, 0,
2598 : : tuples[0], tupdesc);
2599 : : }
2600 : : else
2601 : : {
2602 : : /*
2603 : : * There is a loop body - process all tuples and evaluate the
2604 : : * body on each
2605 : : */
2606 : : uint64 i;
2607 : :
2608 [ + + ]: 26 : for (i = 0; i < ntuples; i++)
2609 : : {
2610 : 22 : pltcl_set_tuple_values(interp, arrayname, i,
2611 : 22 : tuples[i], tupdesc);
2612 : :
2613 : 22 : loop_rc = Tcl_EvalObjEx(interp, loop_body, 0);
2614 : :
2615 [ + + ]: 22 : if (loop_rc == TCL_OK)
2616 : 12 : continue;
2617 [ + + ]: 10 : if (loop_rc == TCL_CONTINUE)
2618 : 2 : continue;
2619 [ + + ]: 8 : if (loop_rc == TCL_RETURN)
2620 : : {
2621 : 2 : my_rc = TCL_RETURN;
2622 : 2 : break;
2623 : : }
2624 [ + + ]: 6 : if (loop_rc == TCL_BREAK)
2625 : 2 : break;
2626 : 4 : my_rc = TCL_ERROR;
2627 : 4 : break;
2628 : : }
2629 : : }
2630 : :
2631 [ + + ]: 62 : if (my_rc == TCL_OK)
2632 : : {
2633 : 56 : Tcl_SetObjResult(interp, Tcl_NewWideIntObj(ntuples));
2634 : : }
2635 : 62 : break;
2636 : :
2637 : 1 : default:
2638 : 1 : Tcl_AppendResult(interp, "pltcl: SPI_execute failed: ",
2639 : : SPI_result_code_string(spi_rc), NULL);
2640 : 1 : my_rc = TCL_ERROR;
2641 : 1 : break;
2642 : : }
2643 : :
2644 : 101 : SPI_freetuptable(tuptable);
2645 : :
2646 : 101 : return my_rc;
2647 : : }
2648 : :
2649 : :
2650 : : /**********************************************************************
2651 : : * pltcl_SPI_prepare() - Builtin support for prepared plans
2652 : : * The Tcl command SPI_prepare
2653 : : * always saves the plan using
2654 : : * SPI_keepplan and returns a key for
2655 : : * access. There is no chance to prepare
2656 : : * and not save the plan currently.
2657 : : **********************************************************************/
2658 : : static int
2659 : 17 : pltcl_SPI_prepare(ClientData cdata, Tcl_Interp *interp,
2660 : : int objc, Tcl_Obj *const objv[])
2661 : : {
2662 : 17 : volatile MemoryContext plan_cxt = NULL;
2663 : : Tcl_Size nargs;
2664 : : Tcl_Obj **argsObj;
2665 : : pltcl_query_desc *qdesc;
2666 : : int i;
2667 : : Tcl_HashEntry *hashent;
2668 : : int hashnew;
2669 : : Tcl_HashTable *query_hash;
2670 : 17 : MemoryContext oldcontext = CurrentMemoryContext;
2671 : 17 : ResourceOwner oldowner = CurrentResourceOwner;
2672 : :
2673 : : /************************************************************
2674 : : * Check the call syntax
2675 : : ************************************************************/
2676 [ + + ]: 17 : if (objc != 3)
2677 : : {
2678 : 1 : Tcl_WrongNumArgs(interp, 1, objv, "query argtypes");
2679 : 1 : return TCL_ERROR;
2680 : : }
2681 : :
2682 : : /************************************************************
2683 : : * Split the argument type list
2684 : : ************************************************************/
2685 [ + + ]: 16 : if (Tcl_ListObjGetElements(interp, objv[2], &nargs, &argsObj) != TCL_OK)
2686 : 1 : return TCL_ERROR;
2687 : :
2688 : : /************************************************************
2689 : : * Allocate the new querydesc structure
2690 : : *
2691 : : * struct qdesc and subsidiary data all live in plan_cxt. Note that if the
2692 : : * function is recompiled for whatever reason, permanent memory leaks
2693 : : * occur. FIXME someday.
2694 : : ************************************************************/
2695 : 15 : plan_cxt = AllocSetContextCreate(TopMemoryContext,
2696 : : "PL/Tcl spi_prepare query",
2697 : : ALLOCSET_SMALL_SIZES);
2698 : 15 : MemoryContextSwitchTo(plan_cxt);
2699 : 15 : qdesc = palloc0_object(pltcl_query_desc);
2700 : 15 : snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
2701 : 15 : qdesc->nargs = nargs;
2702 : 15 : qdesc->argtypes = palloc_array(Oid, nargs);
2703 : 15 : qdesc->arginfuncs = palloc_array(FmgrInfo, nargs);
2704 : 15 : qdesc->argtypioparams = palloc_array(Oid, nargs);
2705 : 15 : MemoryContextSwitchTo(oldcontext);
2706 : :
2707 : : /************************************************************
2708 : : * Execute the prepare inside a sub-transaction, so we can cope with
2709 : : * errors sanely
2710 : : ************************************************************/
2711 : :
2712 : 15 : pltcl_subtrans_begin(oldcontext, oldowner);
2713 : :
2714 [ + + ]: 15 : PG_TRY();
2715 : : {
2716 : : /************************************************************
2717 : : * Resolve argument type names and then look them up by oid
2718 : : * in the system cache, and remember the required information
2719 : : * for input conversion.
2720 : : ************************************************************/
2721 [ + + ]: 34 : for (i = 0; i < nargs; i++)
2722 : : {
2723 : : Oid typId,
2724 : : typInput,
2725 : : typIOParam;
2726 : : int32 typmod;
2727 : :
2728 : 20 : (void) parseTypeString(Tcl_GetString(argsObj[i]),
2729 : : &typId, &typmod, NULL);
2730 : :
2731 : 19 : getTypeInputInfo(typId, &typInput, &typIOParam);
2732 : :
2733 : 19 : qdesc->argtypes[i] = typId;
2734 : 19 : fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
2735 : 19 : qdesc->argtypioparams[i] = typIOParam;
2736 : : }
2737 : :
2738 : : /************************************************************
2739 : : * Prepare the plan and check for errors
2740 : : ************************************************************/
2741 : 14 : UTF_BEGIN;
2742 : 14 : qdesc->plan = SPI_prepare(UTF_U2E(Tcl_GetString(objv[1])),
2743 : 14 : nargs, qdesc->argtypes);
2744 [ - + ]: 13 : UTF_END;
2745 : :
2746 [ - + ]: 13 : if (qdesc->plan == NULL)
2747 [ # # ]: 0 : elog(ERROR, "SPI_prepare() failed");
2748 : :
2749 : : /************************************************************
2750 : : * Save the plan into permanent memory (right now it's in the
2751 : : * SPI procCxt, which will go away at function end).
2752 : : ************************************************************/
2753 [ - + ]: 13 : if (SPI_keepplan(qdesc->plan))
2754 [ # # ]: 0 : elog(ERROR, "SPI_keepplan() failed");
2755 : :
2756 : 13 : pltcl_subtrans_commit(oldcontext, oldowner);
2757 : : }
2758 : 2 : PG_CATCH();
2759 : : {
2760 : 2 : pltcl_subtrans_abort(interp, oldcontext, oldowner);
2761 : :
2762 : 2 : MemoryContextDelete(plan_cxt);
2763 : :
2764 : 2 : return TCL_ERROR;
2765 : : }
2766 [ - + ]: 13 : PG_END_TRY();
2767 : :
2768 : : /************************************************************
2769 : : * Insert a hashtable entry for the plan and return
2770 : : * the key to the caller
2771 : : ************************************************************/
2772 : 13 : query_hash = &pltcl_current_call_state->prodesc->interp_desc->query_hash;
2773 : :
2774 : 13 : hashent = Tcl_CreateHashEntry(query_hash, qdesc->qname, &hashnew);
2775 : 13 : Tcl_SetHashValue(hashent, (ClientData) qdesc);
2776 : :
2777 : : /* qname is ASCII, so no need for encoding conversion */
2778 : 13 : Tcl_SetObjResult(interp, Tcl_NewStringObj(qdesc->qname, -1));
2779 : 13 : return TCL_OK;
2780 : : }
2781 : :
2782 : :
2783 : : /**********************************************************************
2784 : : * pltcl_SPI_execute_plan() - Execute a prepared plan
2785 : : **********************************************************************/
2786 : : static int
2787 : 55 : pltcl_SPI_execute_plan(ClientData cdata, Tcl_Interp *interp,
2788 : : int objc, Tcl_Obj *const objv[])
2789 : : {
2790 : : int my_rc;
2791 : : int spi_rc;
2792 : : int i;
2793 : : int j;
2794 : : int optIndex;
2795 : : Tcl_HashEntry *hashent;
2796 : : pltcl_query_desc *qdesc;
2797 : 55 : const char *nulls = NULL;
2798 : 55 : const char *arrayname = NULL;
2799 : 55 : Tcl_Obj *loop_body = NULL;
2800 : 55 : int count = 0;
2801 : : Tcl_Size callObjc;
2802 : 55 : Tcl_Obj **callObjv = NULL;
2803 : : char **argstrings;
2804 : : Datum *argvalues;
2805 : 55 : MemoryContext oldcontext = CurrentMemoryContext;
2806 : 55 : ResourceOwner oldowner = CurrentResourceOwner;
2807 : : Tcl_HashTable *query_hash;
2808 : :
2809 : : enum options
2810 : : {
2811 : : OPT_ARRAY, OPT_COUNT, OPT_NULLS
2812 : : };
2813 : :
2814 : : static const char *options[] = {
2815 : : "-array", "-count", "-nulls", (const char *) NULL
2816 : : };
2817 : :
2818 : : /************************************************************
2819 : : * Get the options and check syntax
2820 : : ************************************************************/
2821 : 55 : i = 1;
2822 [ + + ]: 154 : while (i < objc)
2823 : : {
2824 [ + + ]: 98 : if (Tcl_GetIndexFromObj(NULL, objv[i], options, NULL,
2825 : : TCL_EXACT, &optIndex) != TCL_OK)
2826 : 50 : break;
2827 : :
2828 [ + + ]: 48 : if (++i >= objc)
2829 : : {
2830 : 3 : Tcl_SetObjResult(interp,
2831 : : Tcl_NewStringObj("missing argument to -array, -count or -nulls", -1));
2832 : 3 : return TCL_ERROR;
2833 : : }
2834 : :
2835 [ + + - - ]: 45 : switch ((enum options) optIndex)
2836 : : {
2837 : 4 : case OPT_ARRAY:
2838 : 4 : arrayname = Tcl_GetString(objv[i++]);
2839 : 4 : break;
2840 : :
2841 : 41 : case OPT_COUNT:
2842 [ + + ]: 41 : if (Tcl_GetIntFromObj(interp, objv[i++], &count) != TCL_OK)
2843 : 1 : return TCL_ERROR;
2844 : 40 : break;
2845 : :
2846 : 0 : case OPT_NULLS:
2847 : 0 : nulls = Tcl_GetString(objv[i++]);
2848 : 0 : break;
2849 : : }
2850 : : }
2851 : :
2852 : : /************************************************************
2853 : : * Get the prepared plan descriptor by its key
2854 : : ************************************************************/
2855 [ + + ]: 51 : if (i >= objc)
2856 : : {
2857 : 1 : Tcl_SetObjResult(interp,
2858 : : Tcl_NewStringObj("missing argument to -count or -array", -1));
2859 : 1 : return TCL_ERROR;
2860 : : }
2861 : :
2862 : 50 : query_hash = &pltcl_current_call_state->prodesc->interp_desc->query_hash;
2863 : :
2864 : 50 : hashent = Tcl_FindHashEntry(query_hash, Tcl_GetString(objv[i]));
2865 [ + + ]: 50 : if (hashent == NULL)
2866 : : {
2867 : 1 : Tcl_AppendResult(interp, "invalid queryid '", Tcl_GetString(objv[i]), "'", NULL);
2868 : 1 : return TCL_ERROR;
2869 : : }
2870 : 49 : qdesc = (pltcl_query_desc *) Tcl_GetHashValue(hashent);
2871 : 49 : i++;
2872 : :
2873 : : /************************************************************
2874 : : * If a nulls string is given, check for correct length
2875 : : ************************************************************/
2876 [ - + ]: 49 : if (nulls != NULL)
2877 : : {
2878 [ # # ]: 0 : if (strlen(nulls) != qdesc->nargs)
2879 : : {
2880 : 0 : Tcl_SetObjResult(interp,
2881 : : Tcl_NewStringObj("length of nulls string doesn't match number of arguments",
2882 : : -1));
2883 : 0 : return TCL_ERROR;
2884 : : }
2885 : : }
2886 : :
2887 : : /************************************************************
2888 : : * If there was an argtype list on preparation, we need
2889 : : * an argument value list now
2890 : : ************************************************************/
2891 [ + + ]: 49 : if (qdesc->nargs > 0)
2892 : : {
2893 [ - + ]: 45 : if (i >= objc)
2894 : : {
2895 : 0 : Tcl_SetObjResult(interp,
2896 : : Tcl_NewStringObj("argument list length doesn't match number of arguments for query",
2897 : : -1));
2898 : 0 : return TCL_ERROR;
2899 : : }
2900 : :
2901 : : /************************************************************
2902 : : * Split the argument values
2903 : : ************************************************************/
2904 [ - + ]: 45 : if (Tcl_ListObjGetElements(interp, objv[i++], &callObjc, &callObjv) != TCL_OK)
2905 : 0 : return TCL_ERROR;
2906 : :
2907 : : /************************************************************
2908 : : * Check that the number of arguments matches
2909 : : ************************************************************/
2910 [ - + ]: 45 : if (callObjc != qdesc->nargs)
2911 : : {
2912 : 0 : Tcl_SetObjResult(interp,
2913 : : Tcl_NewStringObj("argument list length doesn't match number of arguments for query",
2914 : : -1));
2915 : 0 : return TCL_ERROR;
2916 : : }
2917 : : }
2918 : : else
2919 : 4 : callObjc = 0;
2920 : :
2921 : : /************************************************************
2922 : : * Get loop body if present
2923 : : ************************************************************/
2924 [ + + ]: 49 : if (i < objc)
2925 : 4 : loop_body = objv[i++];
2926 : :
2927 [ - + ]: 49 : if (i != objc)
2928 : : {
2929 : 0 : Tcl_WrongNumArgs(interp, 1, objv,
2930 : : "?-count n? ?-array name? ?-nulls string? "
2931 : : "query ?args? ?loop body?");
2932 : 0 : return TCL_ERROR;
2933 : : }
2934 : :
2935 : : /************************************************************
2936 : : * Execute the plan inside a sub-transaction, so we can cope with
2937 : : * errors sanely
2938 : : ************************************************************/
2939 : :
2940 : 49 : pltcl_subtrans_begin(oldcontext, oldowner);
2941 : :
2942 [ + - ]: 49 : PG_TRY();
2943 : : {
2944 : : /************************************************************
2945 : : * As in pltcl_func_handler, copy all the argument strings out
2946 : : * of Tcl before calling any input function. An input
2947 : : * function can re-enter the Tcl interpreter, which might free
2948 : : * not only the strings but also the callObjv array itself, if
2949 : : * the argument list object gets converted to some other type.
2950 : : ************************************************************/
2951 : 49 : argstrings = palloc_array(char *, callObjc);
2952 : :
2953 [ + + ]: 142 : for (j = 0; j < callObjc; j++)
2954 : : {
2955 [ - + - - ]: 93 : if (nulls && nulls[j] == 'n')
2956 : 0 : argstrings[j] = NULL;
2957 : : else
2958 : 93 : argstrings[j] = utf_u2e_copy(Tcl_GetString(callObjv[j]));
2959 : : }
2960 : :
2961 : : /************************************************************
2962 : : * Setup the value array for SPI_execute_plan() using
2963 : : * the type specific input functions
2964 : : ************************************************************/
2965 : 49 : argvalues = palloc_array(Datum, callObjc);
2966 : :
2967 [ + + ]: 142 : for (j = 0; j < callObjc; j++)
2968 : : {
2969 : 93 : argvalues[j] = InputFunctionCall(&qdesc->arginfuncs[j],
2970 : 93 : argstrings[j],
2971 : 93 : qdesc->argtypioparams[j],
2972 : : -1);
2973 : : }
2974 : :
2975 : : /************************************************************
2976 : : * Execute the plan
2977 : : ************************************************************/
2978 : 98 : spi_rc = SPI_execute_plan(qdesc->plan, argvalues, nulls,
2979 : 49 : pltcl_current_call_state->prodesc->fn_readonly,
2980 : : count);
2981 : :
2982 : 49 : my_rc = pltcl_process_SPI_result(interp,
2983 : : arrayname,
2984 : : loop_body,
2985 : : spi_rc,
2986 : : SPI_tuptable,
2987 : : SPI_processed);
2988 : :
2989 : 49 : pltcl_subtrans_commit(oldcontext, oldowner);
2990 : : }
2991 : 0 : PG_CATCH();
2992 : : {
2993 : 0 : pltcl_subtrans_abort(interp, oldcontext, oldowner);
2994 : 0 : return TCL_ERROR;
2995 : : }
2996 [ - + ]: 49 : PG_END_TRY();
2997 : :
2998 : 49 : return my_rc;
2999 : : }
3000 : :
3001 : :
3002 : : /**********************************************************************
3003 : : * pltcl_subtransaction() - Execute some Tcl code in a subtransaction
3004 : : *
3005 : : * The subtransaction is aborted if the Tcl code fragment returns TCL_ERROR,
3006 : : * otherwise it's subcommitted.
3007 : : **********************************************************************/
3008 : : static int
3009 : 8 : pltcl_subtransaction(ClientData cdata, Tcl_Interp *interp,
3010 : : int objc, Tcl_Obj *const objv[])
3011 : : {
3012 : 8 : MemoryContext oldcontext = CurrentMemoryContext;
3013 : 8 : ResourceOwner oldowner = CurrentResourceOwner;
3014 : : int retcode;
3015 : :
3016 [ - + ]: 8 : if (objc != 2)
3017 : : {
3018 : 0 : Tcl_WrongNumArgs(interp, 1, objv, "command");
3019 : 0 : return TCL_ERROR;
3020 : : }
3021 : :
3022 : : /*
3023 : : * Note: we don't use pltcl_subtrans_begin and friends here because we
3024 : : * don't want the error handling in pltcl_subtrans_abort. But otherwise
3025 : : * the processing should be about the same as in those functions.
3026 : : */
3027 : 8 : BeginInternalSubTransaction(NULL);
3028 : 8 : MemoryContextSwitchTo(oldcontext);
3029 : :
3030 : 8 : retcode = Tcl_EvalObjEx(interp, objv[1], 0);
3031 : :
3032 [ + + ]: 8 : if (retcode == TCL_ERROR)
3033 : : {
3034 : : /* Rollback the subtransaction */
3035 : 5 : RollbackAndReleaseCurrentSubTransaction();
3036 : : }
3037 : : else
3038 : : {
3039 : : /* Commit the subtransaction */
3040 : 3 : ReleaseCurrentSubTransaction();
3041 : : }
3042 : :
3043 : : /* In either case, restore previous memory context and resource owner */
3044 : 8 : MemoryContextSwitchTo(oldcontext);
3045 : 8 : CurrentResourceOwner = oldowner;
3046 : :
3047 : 8 : return retcode;
3048 : : }
3049 : :
3050 : :
3051 : : /**********************************************************************
3052 : : * pltcl_commit()
3053 : : *
3054 : : * Commit the transaction and start a new one.
3055 : : **********************************************************************/
3056 : : static int
3057 : 10 : pltcl_commit(ClientData cdata, Tcl_Interp *interp,
3058 : : int objc, Tcl_Obj *const objv[])
3059 : : {
3060 : 10 : MemoryContext oldcontext = CurrentMemoryContext;
3061 : :
3062 [ + + ]: 10 : PG_TRY();
3063 : : {
3064 : 10 : SPI_commit();
3065 : : }
3066 : 5 : PG_CATCH();
3067 : : {
3068 : : ErrorData *edata;
3069 : :
3070 : : /* Save error info */
3071 : 5 : MemoryContextSwitchTo(oldcontext);
3072 : 5 : edata = CopyErrorData();
3073 : 5 : FlushErrorState();
3074 : :
3075 : : /* Pass the error data to Tcl */
3076 : 5 : pltcl_construct_errorCode(interp, edata);
3077 : 5 : UTF_BEGIN;
3078 : 5 : Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
3079 [ - + ]: 5 : UTF_END;
3080 : 5 : FreeErrorData(edata);
3081 : :
3082 : 5 : return TCL_ERROR;
3083 : : }
3084 [ - + ]: 5 : PG_END_TRY();
3085 : :
3086 : 5 : return TCL_OK;
3087 : : }
3088 : :
3089 : :
3090 : : /**********************************************************************
3091 : : * pltcl_rollback()
3092 : : *
3093 : : * Abort the transaction and start a new one.
3094 : : **********************************************************************/
3095 : : static int
3096 : 6 : pltcl_rollback(ClientData cdata, Tcl_Interp *interp,
3097 : : int objc, Tcl_Obj *const objv[])
3098 : : {
3099 : 6 : MemoryContext oldcontext = CurrentMemoryContext;
3100 : :
3101 [ + + ]: 6 : PG_TRY();
3102 : : {
3103 : 6 : SPI_rollback();
3104 : : }
3105 : 1 : PG_CATCH();
3106 : : {
3107 : : ErrorData *edata;
3108 : :
3109 : : /* Save error info */
3110 : 1 : MemoryContextSwitchTo(oldcontext);
3111 : 1 : edata = CopyErrorData();
3112 : 1 : FlushErrorState();
3113 : :
3114 : : /* Pass the error data to Tcl */
3115 : 1 : pltcl_construct_errorCode(interp, edata);
3116 : 1 : UTF_BEGIN;
3117 : 1 : Tcl_SetObjResult(interp, Tcl_NewStringObj(UTF_E2U(edata->message), -1));
3118 [ - + ]: 1 : UTF_END;
3119 : 1 : FreeErrorData(edata);
3120 : :
3121 : 1 : return TCL_ERROR;
3122 : : }
3123 [ - + ]: 5 : PG_END_TRY();
3124 : :
3125 : 5 : return TCL_OK;
3126 : : }
3127 : :
3128 : :
3129 : : /**********************************************************************
3130 : : * pltcl_set_tuple_values() - Set variables for all attributes
3131 : : * of a given tuple
3132 : : *
3133 : : * Note: arrayname is presumed to be UTF8; it usually came from Tcl
3134 : : **********************************************************************/
3135 : : static void
3136 : 51 : pltcl_set_tuple_values(Tcl_Interp *interp, const char *arrayname,
3137 : : uint64 tupno, HeapTuple tuple, TupleDesc tupdesc)
3138 : : {
3139 : : int i;
3140 : : char *outputstr;
3141 : : Datum attr;
3142 : : bool isnull;
3143 : : const char *attname;
3144 : : Oid typoutput;
3145 : : bool typisvarlena;
3146 : : const char **arrptr;
3147 : : const char **nameptr;
3148 : 51 : const char *nullname = NULL;
3149 : :
3150 : : /************************************************************
3151 : : * Prepare pointers for Tcl_SetVar2Ex() below
3152 : : ************************************************************/
3153 [ + + ]: 51 : if (arrayname == NULL)
3154 : : {
3155 : 29 : arrptr = &attname;
3156 : 29 : nameptr = &nullname;
3157 : : }
3158 : : else
3159 : : {
3160 : 22 : arrptr = &arrayname;
3161 : 22 : nameptr = &attname;
3162 : :
3163 : : /*
3164 : : * When outputting to an array, fill the ".tupno" element with the
3165 : : * current tuple number. This will be overridden below if ".tupno" is
3166 : : * in use as an actual field name in the rowtype.
3167 : : */
3168 : 22 : Tcl_SetVar2Ex(interp, arrayname, ".tupno", Tcl_NewWideIntObj(tupno), 0);
3169 : : }
3170 : :
3171 [ + + ]: 122 : for (i = 0; i < tupdesc->natts; i++)
3172 : : {
3173 : 71 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3174 : :
3175 : : /* ignore dropped attributes */
3176 [ - + ]: 71 : if (att->attisdropped)
3177 : 0 : continue;
3178 : :
3179 : : /************************************************************
3180 : : * Get the attribute name
3181 : : ************************************************************/
3182 : 71 : UTF_BEGIN;
3183 : 71 : attname = pstrdup(UTF_E2U(NameStr(att->attname)));
3184 [ - + ]: 71 : UTF_END;
3185 : :
3186 : : /************************************************************
3187 : : * Get the attributes value
3188 : : ************************************************************/
3189 : 71 : attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3190 : :
3191 : : /************************************************************
3192 : : * If there is a value, set the variable
3193 : : * If not, unset it
3194 : : *
3195 : : * Hmmm - Null attributes will cause functions to
3196 : : * crash if they don't expect them - need something
3197 : : * smarter here.
3198 : : ************************************************************/
3199 [ + - ]: 71 : if (!isnull)
3200 : : {
3201 : 71 : getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3202 : 71 : outputstr = OidOutputFunctionCall(typoutput, attr);
3203 : 71 : UTF_BEGIN;
3204 : 71 : Tcl_SetVar2Ex(interp, *arrptr, *nameptr,
3205 : 71 : Tcl_NewStringObj(UTF_E2U(outputstr), -1), 0);
3206 [ - + ]: 71 : UTF_END;
3207 : 71 : pfree(outputstr);
3208 : : }
3209 : : else
3210 : 0 : Tcl_UnsetVar2(interp, *arrptr, *nameptr, 0);
3211 : :
3212 : 71 : pfree(unconstify(char *, attname));
3213 : : }
3214 : 51 : }
3215 : :
3216 : :
3217 : : /**********************************************************************
3218 : : * pltcl_build_tuple_argument() - Build a list object usable for 'array set'
3219 : : * from all attributes of a given tuple
3220 : : **********************************************************************/
3221 : : static Tcl_Obj *
3222 : 69 : pltcl_build_tuple_argument(HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
3223 : : {
3224 : 69 : Tcl_Obj *retobj = Tcl_NewObj();
3225 : : int i;
3226 : : char *outputstr;
3227 : : Datum attr;
3228 : : bool isnull;
3229 : : char *attname;
3230 : : Oid typoutput;
3231 : : bool typisvarlena;
3232 : :
3233 [ + + ]: 293 : for (i = 0; i < tupdesc->natts; i++)
3234 : : {
3235 : 224 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3236 : :
3237 : : /* ignore dropped attributes */
3238 [ + + ]: 224 : if (att->attisdropped)
3239 : 8 : continue;
3240 : :
3241 [ + + ]: 216 : if (att->attgenerated)
3242 : : {
3243 : : /* don't include unless requested */
3244 [ + + ]: 18 : if (!include_generated)
3245 : 6 : continue;
3246 : : /* never include virtual columns */
3247 [ + + ]: 12 : if (att->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
3248 : 6 : continue;
3249 : : }
3250 : :
3251 : : /************************************************************
3252 : : * Get the attribute name
3253 : : ************************************************************/
3254 : 204 : attname = NameStr(att->attname);
3255 : :
3256 : : /************************************************************
3257 : : * Get the attributes value
3258 : : ************************************************************/
3259 : 204 : attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3260 : :
3261 : : /************************************************************
3262 : : * If there is a value, append the attribute name and the
3263 : : * value to the list
3264 : : *
3265 : : * Hmmm - Null attributes will cause functions to
3266 : : * crash if they don't expect them - need something
3267 : : * smarter here.
3268 : : ************************************************************/
3269 [ + + ]: 204 : if (!isnull)
3270 : : {
3271 : 200 : getTypeOutputInfo(att->atttypid,
3272 : : &typoutput, &typisvarlena);
3273 : 200 : outputstr = OidOutputFunctionCall(typoutput, attr);
3274 : 200 : UTF_BEGIN;
3275 : 200 : Tcl_ListObjAppendElement(NULL, retobj,
3276 : 200 : Tcl_NewStringObj(UTF_E2U(attname), -1));
3277 [ - + ]: 200 : UTF_END;
3278 : 200 : UTF_BEGIN;
3279 : 200 : Tcl_ListObjAppendElement(NULL, retobj,
3280 : 200 : Tcl_NewStringObj(UTF_E2U(outputstr), -1));
3281 [ - + ]: 200 : UTF_END;
3282 : 200 : pfree(outputstr);
3283 : : }
3284 : : }
3285 : :
3286 : 69 : return retobj;
3287 : : }
3288 : :
3289 : : /**********************************************************************
3290 : : * pltcl_build_tuple_result() - Build a tuple of function's result rowtype
3291 : : * from a Tcl list of column names and values
3292 : : *
3293 : : * In a trigger function, we build a tuple of the trigger table's rowtype.
3294 : : *
3295 : : * Note: this function leaks memory. Even if we made it clean up its own
3296 : : * mess, there's no way to prevent the datatype input functions it calls
3297 : : * from leaking. Run it in a short-lived context, unless we're about to
3298 : : * exit the procedure anyway.
3299 : : **********************************************************************/
3300 : : static HeapTuple
3301 : 31 : pltcl_build_tuple_result(Tcl_Interp *interp, Tcl_Obj **kvObjv, int kvObjc,
3302 : : pltcl_call_state *call_state)
3303 : : {
3304 : : HeapTuple tuple;
3305 : : TupleDesc tupdesc;
3306 : : AttInMetadata *attinmeta;
3307 : : char **values;
3308 : : int i;
3309 : :
3310 [ + + ]: 31 : if (call_state->ret_tupdesc)
3311 : : {
3312 : 21 : tupdesc = call_state->ret_tupdesc;
3313 : 21 : attinmeta = call_state->attinmeta;
3314 : : }
3315 [ + - ]: 10 : else if (call_state->trigdata)
3316 : : {
3317 : 10 : tupdesc = RelationGetDescr(call_state->trigdata->tg_relation);
3318 : 10 : attinmeta = TupleDescGetAttInMetadata(tupdesc);
3319 : : }
3320 : : else
3321 : : {
3322 [ # # ]: 0 : elog(ERROR, "PL/Tcl function does not return a tuple");
3323 : : tupdesc = NULL; /* keep compiler quiet */
3324 : : attinmeta = NULL;
3325 : : }
3326 : :
3327 : 31 : values = palloc0_array(char *, tupdesc->natts);
3328 : :
3329 [ + + ]: 31 : if (kvObjc % 2 != 0)
3330 [ + - ]: 2 : ereport(ERROR,
3331 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3332 : : errmsg("column name/value list must have even number of elements")));
3333 : :
3334 [ + + ]: 98 : for (i = 0; i < kvObjc; i += 2)
3335 : : {
3336 : 73 : char *fieldName = utf_u2e(Tcl_GetString(kvObjv[i]));
3337 : 73 : int attn = SPI_fnumber(tupdesc, fieldName);
3338 : :
3339 : : /*
3340 : : * We silently ignore ".tupno", if it's present but doesn't match any
3341 : : * actual output column. This allows direct use of a row returned by
3342 : : * pltcl_set_tuple_values().
3343 : : */
3344 [ + + ]: 73 : if (attn == SPI_ERROR_NOATTRIBUTE)
3345 : : {
3346 [ - + ]: 3 : if (strcmp(fieldName, ".tupno") == 0)
3347 : 0 : continue;
3348 [ + - ]: 3 : ereport(ERROR,
3349 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
3350 : : errmsg("column name/value list contains nonexistent column name \"%s\"",
3351 : : fieldName)));
3352 : : }
3353 : :
3354 [ - + ]: 70 : if (attn <= 0)
3355 [ # # ]: 0 : ereport(ERROR,
3356 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3357 : : errmsg("cannot set system attribute \"%s\"",
3358 : : fieldName)));
3359 : :
3360 [ + + ]: 70 : if (TupleDescAttr(tupdesc, attn - 1)->attgenerated)
3361 [ + - ]: 1 : ereport(ERROR,
3362 : : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
3363 : : errmsg("cannot set generated column \"%s\"",
3364 : : fieldName)));
3365 : :
3366 : : /*
3367 : : * As in pltcl_func_handler, copy each string out of the Tcl
3368 : : * interpreter before proceeding, to ensure it can't get freed or
3369 : : * overwritten by re-entrant use of the Tcl interpreter.
3370 : : */
3371 : 69 : values[attn - 1] = utf_u2e_copy(Tcl_GetString(kvObjv[i + 1]));
3372 : : }
3373 : :
3374 : 25 : tuple = BuildTupleFromCStrings(attinmeta, values);
3375 : :
3376 : : /* if result type is domain-over-composite, check domain constraints */
3377 [ + + ]: 25 : if (call_state->prodesc->fn_retisdomain)
3378 : 3 : domain_check(HeapTupleGetDatum(tuple), false,
3379 : 3 : call_state->prodesc->result_typid,
3380 : 3 : &call_state->prodesc->domain_info,
3381 : 3 : call_state->prodesc->fn_cxt);
3382 : :
3383 : 24 : return tuple;
3384 : : }
3385 : :
3386 : : /**********************************************************************
3387 : : * pltcl_init_tuple_store() - Initialize the result tuplestore for a SRF
3388 : : **********************************************************************/
3389 : : static void
3390 : 5 : pltcl_init_tuple_store(pltcl_call_state *call_state)
3391 : : {
3392 : 5 : ReturnSetInfo *rsi = call_state->rsi;
3393 : : MemoryContext oldcxt;
3394 : : ResourceOwner oldowner;
3395 : :
3396 : : /* Should be in a SRF */
3397 : : Assert(rsi);
3398 : : /* Should be first time through */
3399 : : Assert(!call_state->tuple_store);
3400 : : Assert(!call_state->attinmeta);
3401 : :
3402 : : /* We expect caller to provide an appropriate result tupdesc */
3403 : : Assert(rsi->expectedDesc);
3404 : 5 : call_state->ret_tupdesc = rsi->expectedDesc;
3405 : :
3406 : : /*
3407 : : * Switch to the right memory context and resource owner for storing the
3408 : : * tuplestore. If we're within a subtransaction opened for an exception
3409 : : * block, for example, we must still create the tuplestore in the resource
3410 : : * owner that was active when this function was entered, and not in the
3411 : : * subtransaction's resource owner.
3412 : : */
3413 : 5 : oldcxt = MemoryContextSwitchTo(call_state->tuple_store_cxt);
3414 : 5 : oldowner = CurrentResourceOwner;
3415 : 5 : CurrentResourceOwner = call_state->tuple_store_owner;
3416 : :
3417 : 5 : call_state->tuple_store =
3418 : 5 : tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
3419 : : false, work_mem);
3420 : :
3421 : : /* Build attinmeta in this context, too */
3422 : 5 : call_state->attinmeta = TupleDescGetAttInMetadata(call_state->ret_tupdesc);
3423 : :
3424 : 5 : CurrentResourceOwner = oldowner;
3425 : 5 : MemoryContextSwitchTo(oldcxt);
3426 : 5 : }
|