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