1 /*
2  * interface to SPI functions
3  *
4  * src/pl/plpython/plpy_spi.c
5  */
6 
7 #include "postgres.h"
8 
9 #include <limits.h>
10 
11 #include "access/htup_details.h"
12 #include "access/xact.h"
13 #include "catalog/pg_type.h"
14 #include "executor/spi.h"
15 #include "mb/pg_wchar.h"
16 #include "parser/parse_type.h"
17 #include "utils/memutils.h"
18 #include "utils/syscache.h"
19 
20 #include "plpython.h"
21 
22 #include "plpy_spi.h"
23 
24 #include "plpy_elog.h"
25 #include "plpy_main.h"
26 #include "plpy_planobject.h"
27 #include "plpy_plpymodule.h"
28 #include "plpy_procedure.h"
29 #include "plpy_resultobject.h"
30 
31 
32 static PyObject *PLy_spi_execute_query(char *query, long limit);
33 static PyObject *PLy_spi_execute_fetch_result(SPITupleTable *tuptable,
34 							 uint64 rows, int status);
35 static void PLy_spi_exception_set(PyObject *excclass, ErrorData *edata);
36 
37 
38 /* prepare(query="select * from foo")
39  * prepare(query="select * from foo where bar = $1", params=["text"])
40  * prepare(query="select * from foo where bar = $1", params=["text"], limit=5)
41  */
42 PyObject *
PLy_spi_prepare(PyObject * self,PyObject * args)43 PLy_spi_prepare(PyObject *self, PyObject *args)
44 {
45 	PLyPlanObject *plan;
46 	PyObject   *list = NULL;
47 	PyObject   *volatile optr = NULL;
48 	char	   *query;
49 	volatile MemoryContext oldcontext;
50 	volatile ResourceOwner oldowner;
51 	volatile int nargs;
52 
53 	if (!PyArg_ParseTuple(args, "s|O:prepare", &query, &list))
54 		return NULL;
55 
56 	if (list && (!PySequence_Check(list)))
57 	{
58 		PLy_exception_set(PyExc_TypeError,
59 						  "second argument of plpy.prepare must be a sequence");
60 		return NULL;
61 	}
62 
63 	if ((plan = (PLyPlanObject *) PLy_plan_new()) == NULL)
64 		return NULL;
65 
66 	plan->mcxt = AllocSetContextCreate(TopMemoryContext,
67 									   "PL/Python plan context",
68 									   ALLOCSET_DEFAULT_SIZES);
69 	oldcontext = MemoryContextSwitchTo(plan->mcxt);
70 
71 	nargs = list ? PySequence_Length(list) : 0;
72 
73 	plan->nargs = nargs;
74 	plan->types = nargs ? palloc(sizeof(Oid) * nargs) : NULL;
75 	plan->values = nargs ? palloc(sizeof(Datum) * nargs) : NULL;
76 	plan->args = nargs ? palloc(sizeof(PLyTypeInfo) * nargs) : NULL;
77 
78 	MemoryContextSwitchTo(oldcontext);
79 
80 	oldcontext = CurrentMemoryContext;
81 	oldowner = CurrentResourceOwner;
82 
83 	PLy_spi_subtransaction_begin(oldcontext, oldowner);
84 
85 	PG_TRY();
86 	{
87 		int			i;
88 		PLyExecutionContext *exec_ctx = PLy_current_execution_context();
89 
90 		/*
91 		 * the other loop might throw an exception, if PLyTypeInfo member
92 		 * isn't properly initialized the Py_DECREF(plan) will go boom
93 		 */
94 		for (i = 0; i < nargs; i++)
95 		{
96 			PLy_typeinfo_init(&plan->args[i], plan->mcxt);
97 			plan->values[i] = PointerGetDatum(NULL);
98 		}
99 
100 		for (i = 0; i < nargs; i++)
101 		{
102 			char	   *sptr;
103 			HeapTuple	typeTup;
104 			Oid			typeId;
105 			int32		typmod;
106 
107 			optr = PySequence_GetItem(list, i);
108 			if (PyString_Check(optr))
109 				sptr = PyString_AsString(optr);
110 			else if (PyUnicode_Check(optr))
111 				sptr = PLyUnicode_AsString(optr);
112 			else
113 			{
114 				ereport(ERROR,
115 						(errmsg("plpy.prepare: type name at ordinal position %d is not a string", i)));
116 				sptr = NULL;	/* keep compiler quiet */
117 			}
118 
119 			/********************************************************
120 			 * Resolve argument type names and then look them up by
121 			 * oid in the system cache, and remember the required
122 			 *information for input conversion.
123 			 ********************************************************/
124 
125 			parseTypeString(sptr, &typeId, &typmod, false);
126 
127 			typeTup = SearchSysCache1(TYPEOID,
128 									  ObjectIdGetDatum(typeId));
129 			if (!HeapTupleIsValid(typeTup))
130 				elog(ERROR, "cache lookup failed for type %u", typeId);
131 
132 			Py_DECREF(optr);
133 
134 			/*
135 			 * set optr to NULL, so we won't try to unref it again in case of
136 			 * an error
137 			 */
138 			optr = NULL;
139 
140 			plan->types[i] = typeId;
141 			PLy_output_datum_func(&plan->args[i], typeTup, exec_ctx->curr_proc->langid, exec_ctx->curr_proc->trftypes);
142 			ReleaseSysCache(typeTup);
143 		}
144 
145 		pg_verifymbstr(query, strlen(query), false);
146 		plan->plan = SPI_prepare(query, plan->nargs, plan->types);
147 		if (plan->plan == NULL)
148 			elog(ERROR, "SPI_prepare failed: %s",
149 				 SPI_result_code_string(SPI_result));
150 
151 		/* transfer plan from procCxt to topCxt */
152 		if (SPI_keepplan(plan->plan))
153 			elog(ERROR, "SPI_keepplan failed");
154 
155 		PLy_spi_subtransaction_commit(oldcontext, oldowner);
156 	}
157 	PG_CATCH();
158 	{
159 		Py_DECREF(plan);
160 		Py_XDECREF(optr);
161 
162 		PLy_spi_subtransaction_abort(oldcontext, oldowner);
163 		return NULL;
164 	}
165 	PG_END_TRY();
166 
167 	Assert(plan->plan != NULL);
168 	return (PyObject *) plan;
169 }
170 
171 /* execute(query="select * from foo", limit=5)
172  * execute(plan=plan, values=(foo, bar), limit=5)
173  */
174 PyObject *
PLy_spi_execute(PyObject * self,PyObject * args)175 PLy_spi_execute(PyObject *self, PyObject *args)
176 {
177 	char	   *query;
178 	PyObject   *plan;
179 	PyObject   *list = NULL;
180 	long		limit = 0;
181 
182 	if (PyArg_ParseTuple(args, "s|l", &query, &limit))
183 		return PLy_spi_execute_query(query, limit);
184 
185 	PyErr_Clear();
186 
187 	if (PyArg_ParseTuple(args, "O|Ol", &plan, &list, &limit) &&
188 		is_PLyPlanObject(plan))
189 		return PLy_spi_execute_plan(plan, list, limit);
190 
191 	PLy_exception_set(PLy_exc_error, "plpy.execute expected a query or a plan");
192 	return NULL;
193 }
194 
195 PyObject *
PLy_spi_execute_plan(PyObject * ob,PyObject * list,long limit)196 PLy_spi_execute_plan(PyObject *ob, PyObject *list, long limit)
197 {
198 	volatile int nargs;
199 	int			i,
200 				rv;
201 	PLyPlanObject *plan;
202 	volatile MemoryContext oldcontext;
203 	volatile ResourceOwner oldowner;
204 	PyObject   *ret;
205 
206 	if (list != NULL)
207 	{
208 		if (!PySequence_Check(list) || PyString_Check(list) || PyUnicode_Check(list))
209 		{
210 			PLy_exception_set(PyExc_TypeError, "plpy.execute takes a sequence as its second argument");
211 			return NULL;
212 		}
213 		nargs = PySequence_Length(list);
214 	}
215 	else
216 		nargs = 0;
217 
218 	plan = (PLyPlanObject *) ob;
219 
220 	if (nargs != plan->nargs)
221 	{
222 		char	   *sv;
223 		PyObject   *so = PyObject_Str(list);
224 
225 		if (!so)
226 			PLy_elog(ERROR, "could not execute plan");
227 		sv = PyString_AsString(so);
228 		PLy_exception_set_plural(PyExc_TypeError,
229 								 "Expected sequence of %d argument, got %d: %s",
230 								 "Expected sequence of %d arguments, got %d: %s",
231 								 plan->nargs,
232 								 plan->nargs, nargs, sv);
233 		Py_DECREF(so);
234 
235 		return NULL;
236 	}
237 
238 	oldcontext = CurrentMemoryContext;
239 	oldowner = CurrentResourceOwner;
240 
241 	PLy_spi_subtransaction_begin(oldcontext, oldowner);
242 
243 	PG_TRY();
244 	{
245 		PLyExecutionContext *exec_ctx = PLy_current_execution_context();
246 		char	   *volatile nulls;
247 		volatile int j;
248 
249 		if (nargs > 0)
250 			nulls = palloc(nargs * sizeof(char));
251 		else
252 			nulls = NULL;
253 
254 		for (j = 0; j < nargs; j++)
255 		{
256 			PyObject   *elem;
257 
258 			elem = PySequence_GetItem(list, j);
259 			if (elem != Py_None)
260 			{
261 				PG_TRY();
262 				{
263 					plan->values[j] =
264 						plan->args[j].out.d.func(&(plan->args[j].out.d),
265 												 -1,
266 												 elem,
267 												 false);
268 				}
269 				PG_CATCH();
270 				{
271 					Py_DECREF(elem);
272 					PG_RE_THROW();
273 				}
274 				PG_END_TRY();
275 
276 				Py_DECREF(elem);
277 				nulls[j] = ' ';
278 			}
279 			else
280 			{
281 				Py_DECREF(elem);
282 				plan->values[j] =
283 					InputFunctionCall(&(plan->args[j].out.d.typfunc),
284 									  NULL,
285 									  plan->args[j].out.d.typioparam,
286 									  -1);
287 				nulls[j] = 'n';
288 			}
289 		}
290 
291 		rv = SPI_execute_plan(plan->plan, plan->values, nulls,
292 							  exec_ctx->curr_proc->fn_readonly, limit);
293 		ret = PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
294 
295 		if (nargs > 0)
296 			pfree(nulls);
297 
298 		PLy_spi_subtransaction_commit(oldcontext, oldowner);
299 	}
300 	PG_CATCH();
301 	{
302 		int			k;
303 
304 		/*
305 		 * cleanup plan->values array
306 		 */
307 		for (k = 0; k < nargs; k++)
308 		{
309 			if (!plan->args[k].out.d.typbyval &&
310 				(plan->values[k] != PointerGetDatum(NULL)))
311 			{
312 				pfree(DatumGetPointer(plan->values[k]));
313 				plan->values[k] = PointerGetDatum(NULL);
314 			}
315 		}
316 
317 		PLy_spi_subtransaction_abort(oldcontext, oldowner);
318 		return NULL;
319 	}
320 	PG_END_TRY();
321 
322 	for (i = 0; i < nargs; i++)
323 	{
324 		if (!plan->args[i].out.d.typbyval &&
325 			(plan->values[i] != PointerGetDatum(NULL)))
326 		{
327 			pfree(DatumGetPointer(plan->values[i]));
328 			plan->values[i] = PointerGetDatum(NULL);
329 		}
330 	}
331 
332 	if (rv < 0)
333 	{
334 		PLy_exception_set(PLy_exc_spi_error,
335 						  "SPI_execute_plan failed: %s",
336 						  SPI_result_code_string(rv));
337 		return NULL;
338 	}
339 
340 	return ret;
341 }
342 
343 static PyObject *
PLy_spi_execute_query(char * query,long limit)344 PLy_spi_execute_query(char *query, long limit)
345 {
346 	int			rv;
347 	volatile MemoryContext oldcontext;
348 	volatile ResourceOwner oldowner;
349 	PyObject   *ret = NULL;
350 
351 	oldcontext = CurrentMemoryContext;
352 	oldowner = CurrentResourceOwner;
353 
354 	PLy_spi_subtransaction_begin(oldcontext, oldowner);
355 
356 	PG_TRY();
357 	{
358 		PLyExecutionContext *exec_ctx = PLy_current_execution_context();
359 
360 		pg_verifymbstr(query, strlen(query), false);
361 		rv = SPI_execute(query, exec_ctx->curr_proc->fn_readonly, limit);
362 		ret = PLy_spi_execute_fetch_result(SPI_tuptable, SPI_processed, rv);
363 
364 		PLy_spi_subtransaction_commit(oldcontext, oldowner);
365 	}
366 	PG_CATCH();
367 	{
368 		PLy_spi_subtransaction_abort(oldcontext, oldowner);
369 		return NULL;
370 	}
371 	PG_END_TRY();
372 
373 	if (rv < 0)
374 	{
375 		Py_XDECREF(ret);
376 		PLy_exception_set(PLy_exc_spi_error,
377 						  "SPI_execute failed: %s",
378 						  SPI_result_code_string(rv));
379 		return NULL;
380 	}
381 
382 	return ret;
383 }
384 
385 static PyObject *
PLy_spi_execute_fetch_result(SPITupleTable * tuptable,uint64 rows,int status)386 PLy_spi_execute_fetch_result(SPITupleTable *tuptable, uint64 rows, int status)
387 {
388 	PLyResultObject *result;
389 	volatile MemoryContext oldcontext;
390 
391 	result = (PLyResultObject *) PLy_result_new();
392 	Py_DECREF(result->status);
393 	result->status = PyInt_FromLong(status);
394 
395 	if (status > 0 && tuptable == NULL)
396 	{
397 		Py_DECREF(result->nrows);
398 		result->nrows = (rows > (uint64) LONG_MAX) ?
399 			PyFloat_FromDouble((double) rows) :
400 			PyInt_FromLong((long) rows);
401 	}
402 	else if (status > 0 && tuptable != NULL)
403 	{
404 		PLyTypeInfo args;
405 		MemoryContext cxt;
406 
407 		Py_DECREF(result->nrows);
408 		result->nrows = (rows > (uint64) LONG_MAX) ?
409 			PyFloat_FromDouble((double) rows) :
410 			PyInt_FromLong((long) rows);
411 
412 		cxt = AllocSetContextCreate(CurrentMemoryContext,
413 									"PL/Python temp context",
414 									ALLOCSET_DEFAULT_SIZES);
415 		PLy_typeinfo_init(&args, cxt);
416 
417 		oldcontext = CurrentMemoryContext;
418 		PG_TRY();
419 		{
420 			MemoryContext oldcontext2;
421 
422 			if (rows)
423 			{
424 				uint64		i;
425 
426 				/*
427 				 * PyList_New() and PyList_SetItem() use Py_ssize_t for list
428 				 * size and list indices; so we cannot support a result larger
429 				 * than PY_SSIZE_T_MAX.
430 				 */
431 				if (rows > (uint64) PY_SSIZE_T_MAX)
432 					ereport(ERROR,
433 							(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
434 							 errmsg("query result has too many rows to fit in a Python list")));
435 
436 				Py_DECREF(result->rows);
437 				result->rows = PyList_New(rows);
438 
439 				PLy_input_tuple_funcs(&args, tuptable->tupdesc);
440 				for (i = 0; i < rows; i++)
441 				{
442 					PyObject   *row = PLyDict_FromTuple(&args,
443 														tuptable->vals[i],
444 														tuptable->tupdesc);
445 
446 					PyList_SetItem(result->rows, i, row);
447 				}
448 			}
449 
450 			/*
451 			 * Save tuple descriptor for later use by result set metadata
452 			 * functions.  Save it in TopMemoryContext so that it survives
453 			 * outside of an SPI context.  We trust that PLy_result_dealloc()
454 			 * will clean it up when the time is right.  (Do this as late as
455 			 * possible, to minimize the number of ways the tupdesc could get
456 			 * leaked due to errors.)
457 			 */
458 			oldcontext2 = MemoryContextSwitchTo(TopMemoryContext);
459 			result->tupdesc = CreateTupleDescCopy(tuptable->tupdesc);
460 			MemoryContextSwitchTo(oldcontext2);
461 		}
462 		PG_CATCH();
463 		{
464 			MemoryContextSwitchTo(oldcontext);
465 			MemoryContextDelete(cxt);
466 			Py_DECREF(result);
467 			PG_RE_THROW();
468 		}
469 		PG_END_TRY();
470 
471 		MemoryContextDelete(cxt);
472 		SPI_freetuptable(tuptable);
473 	}
474 
475 	return (PyObject *) result;
476 }
477 
478 /*
479  * Utilities for running SPI functions in subtransactions.
480  *
481  * Usage:
482  *
483  *	MemoryContext oldcontext = CurrentMemoryContext;
484  *	ResourceOwner oldowner = CurrentResourceOwner;
485  *
486  *	PLy_spi_subtransaction_begin(oldcontext, oldowner);
487  *	PG_TRY();
488  *	{
489  *		<call SPI functions>
490  *		PLy_spi_subtransaction_commit(oldcontext, oldowner);
491  *	}
492  *	PG_CATCH();
493  *	{
494  *		<do cleanup>
495  *		PLy_spi_subtransaction_abort(oldcontext, oldowner);
496  *		return NULL;
497  *	}
498  *	PG_END_TRY();
499  *
500  * These utilities take care of restoring connection to the SPI manager and
501  * setting a Python exception in case of an abort.
502  */
503 void
PLy_spi_subtransaction_begin(MemoryContext oldcontext,ResourceOwner oldowner)504 PLy_spi_subtransaction_begin(MemoryContext oldcontext, ResourceOwner oldowner)
505 {
506 	BeginInternalSubTransaction(NULL);
507 	/* Want to run inside function's memory context */
508 	MemoryContextSwitchTo(oldcontext);
509 }
510 
511 void
PLy_spi_subtransaction_commit(MemoryContext oldcontext,ResourceOwner oldowner)512 PLy_spi_subtransaction_commit(MemoryContext oldcontext, ResourceOwner oldowner)
513 {
514 	/* Commit the inner transaction, return to outer xact context */
515 	ReleaseCurrentSubTransaction();
516 	MemoryContextSwitchTo(oldcontext);
517 	CurrentResourceOwner = oldowner;
518 }
519 
520 void
PLy_spi_subtransaction_abort(MemoryContext oldcontext,ResourceOwner oldowner)521 PLy_spi_subtransaction_abort(MemoryContext oldcontext, ResourceOwner oldowner)
522 {
523 	ErrorData  *edata;
524 	PLyExceptionEntry *entry;
525 	PyObject   *exc;
526 
527 	/* Save error info */
528 	MemoryContextSwitchTo(oldcontext);
529 	edata = CopyErrorData();
530 	FlushErrorState();
531 
532 	/* Abort the inner transaction */
533 	RollbackAndReleaseCurrentSubTransaction();
534 	MemoryContextSwitchTo(oldcontext);
535 	CurrentResourceOwner = oldowner;
536 
537 	/* Look up the correct exception */
538 	entry = hash_search(PLy_spi_exceptions, &(edata->sqlerrcode),
539 						HASH_FIND, NULL);
540 
541 	/*
542 	 * This could be a custom error code, if that's the case fallback to
543 	 * SPIError
544 	 */
545 	exc = entry ? entry->exc : PLy_exc_spi_error;
546 	/* Make Python raise the exception */
547 	PLy_spi_exception_set(exc, edata);
548 	FreeErrorData(edata);
549 }
550 
551 /*
552  * Raise a SPIError, passing in it more error details, like the
553  * internal query and error position.
554  */
555 static void
PLy_spi_exception_set(PyObject * excclass,ErrorData * edata)556 PLy_spi_exception_set(PyObject *excclass, ErrorData *edata)
557 {
558 	PyObject   *args = NULL;
559 	PyObject   *spierror = NULL;
560 	PyObject   *spidata = NULL;
561 
562 	args = Py_BuildValue("(s)", edata->message);
563 	if (!args)
564 		goto failure;
565 
566 	/* create a new SPI exception with the error message as the parameter */
567 	spierror = PyObject_CallObject(excclass, args);
568 	if (!spierror)
569 		goto failure;
570 
571 	spidata = Py_BuildValue("(izzzizzzzz)", edata->sqlerrcode, edata->detail, edata->hint,
572 							edata->internalquery, edata->internalpos,
573 							edata->schema_name, edata->table_name, edata->column_name,
574 							edata->datatype_name, edata->constraint_name);
575 	if (!spidata)
576 		goto failure;
577 
578 	if (PyObject_SetAttrString(spierror, "spidata", spidata) == -1)
579 		goto failure;
580 
581 	PyErr_SetObject(excclass, spierror);
582 
583 	Py_DECREF(args);
584 	Py_DECREF(spierror);
585 	Py_DECREF(spidata);
586 	return;
587 
588 failure:
589 	Py_XDECREF(args);
590 	Py_XDECREF(spierror);
591 	Py_XDECREF(spidata);
592 	elog(ERROR, "could not convert SPI error to Python exception");
593 }
594