PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
prepare.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "commands/createas.h"
#include "commands/prepare.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/analyze.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_type.h"
#include "rewrite/rewriteHandler.h"
#include "tcop/pquery.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/snapmgr.h"
#include "utils/timestamp.h"
Include dependency graph for prepare.c:

Go to the source code of this file.

Functions

static void InitQueryHashTable (void)
 
static ParamListInfo EvaluateParams (PreparedStatement *pstmt, List *params, const char *queryString, EState *estate)
 
static Datum build_regtype_array (Oid *param_types, int num_params)
 
void PrepareQuery (PrepareStmt *stmt, const char *queryString, int stmt_location, int stmt_len)
 
void ExecuteQuery (ExecuteStmt *stmt, IntoClause *intoClause, const char *queryString, ParamListInfo params, DestReceiver *dest, char *completionTag)
 
void StorePreparedStatement (const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
 
PreparedStatementFetchPreparedStatement (const char *stmt_name, bool throwError)
 
TupleDesc FetchPreparedStatementResultDesc (PreparedStatement *stmt)
 
ListFetchPreparedStatementTargetList (PreparedStatement *stmt)
 
void DeallocateQuery (DeallocateStmt *stmt)
 
void DropPreparedStatement (const char *stmt_name, bool showError)
 
void DropAllPreparedStatements (void)
 
void ExplainExecuteQuery (ExecuteStmt *execstmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
 
Datum pg_prepared_statement (PG_FUNCTION_ARGS)
 

Variables

static HTABprepared_queries = NULL
 

Function Documentation

static Datum build_regtype_array ( Oid param_types,
int  num_params 
)
static

Definition at line 800 of file prepare.c.

References construct_array(), i, ObjectIdGetDatum, palloc(), PointerGetDatum, REGTYPEOID, and result.

Referenced by pg_prepared_statement().

801 {
802  Datum *tmp_ary;
803  ArrayType *result;
804  int i;
805 
806  tmp_ary = (Datum *) palloc(num_params * sizeof(Datum));
807 
808  for (i = 0; i < num_params; i++)
809  tmp_ary[i] = ObjectIdGetDatum(param_types[i]);
810 
811  /* XXX: this hardcodes assumptions about the regtype type */
812  result = construct_array(tmp_ary, num_params, REGTYPEOID, 4, true, 'i');
813  return PointerGetDatum(result);
814 }
#define PointerGetDatum(X)
Definition: postgres.h:562
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3306
return result
Definition: formatting.c:1618
#define REGTYPEOID
Definition: pg_type.h:581
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
uintptr_t Datum
Definition: postgres.h:372
void * palloc(Size size)
Definition: mcxt.c:849
int i
void DeallocateQuery ( DeallocateStmt stmt)

Definition at line 565 of file prepare.c.

References DropAllPreparedStatements(), DropPreparedStatement(), and DeallocateStmt::name.

Referenced by standard_ProcessUtility().

566 {
567  if (stmt->name)
568  DropPreparedStatement(stmt->name, true);
569  else
571 }
void DropAllPreparedStatements(void)
Definition: prepare.c:600
void DropPreparedStatement(const char *stmt_name, bool showError)
Definition: prepare.c:579
void DropAllPreparedStatements ( void  )

Definition at line 600 of file prepare.c.

References DropCachedPlan(), HASH_REMOVE, hash_search(), hash_seq_init(), hash_seq_search(), NULL, PreparedStatement::plansource, and PreparedStatement::stmt_name.

Referenced by DeallocateQuery(), and DiscardAll().

601 {
602  HASH_SEQ_STATUS seq;
603  PreparedStatement *entry;
604 
605  /* nothing cached */
606  if (!prepared_queries)
607  return;
608 
609  /* walk over cache */
611  while ((entry = hash_seq_search(&seq)) != NULL)
612  {
613  /* Release the plancache entry */
614  DropCachedPlan(entry->plansource);
615 
616  /* Now we can remove the hash table entry */
618  }
619 }
CachedPlanSource * plansource
Definition: prepare.h:31
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static HTAB * prepared_queries
Definition: prepare.c:46
char stmt_name[NAMEDATALEN]
Definition: prepare.h:30
#define NULL
Definition: c.h:229
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1351
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1341
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:486
void DropPreparedStatement ( const char *  stmt_name,
bool  showError 
)

Definition at line 579 of file prepare.c.

References DropCachedPlan(), FetchPreparedStatement(), HASH_REMOVE, hash_search(), NULL, PreparedStatement::plansource, and PreparedStatement::stmt_name.

Referenced by DeallocateQuery(), and PostgresMain().

580 {
581  PreparedStatement *entry;
582 
583  /* Find the query's hash table entry; raise error if wanted */
584  entry = FetchPreparedStatement(stmt_name, showError);
585 
586  if (entry)
587  {
588  /* Release the plancache entry */
589  DropCachedPlan(entry->plansource);
590 
591  /* Now we can remove the hash table entry */
593  }
594 }
CachedPlanSource * plansource
Definition: prepare.h:31
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static HTAB * prepared_queries
Definition: prepare.c:46
char stmt_name[NAMEDATALEN]
Definition: prepare.h:30
#define NULL
Definition: c.h:229
void DropCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:486
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:494
static ParamListInfo EvaluateParams ( PreparedStatement pstmt,
List params,
const char *  queryString,
EState estate 
)
static

Definition at line 327 of file prepare.c.

References assign_expr_collations(), COERCE_IMPLICIT_CAST, coerce_to_target_type(), COERCION_ASSIGNMENT, copyObject, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, ExecEvalExprSwitchContext(), ExecPrepareExprList(), EXPR_KIND_EXECUTE_PARAMETER, exprType(), format_type_be(), GetPerTupleExprContext, i, ParamExternData::isnull, lfirst, list_length(), make_parsestate(), NULL, CachedPlanSource::num_params, ParamListInfoData::numParams, offsetof, ParseState::p_sourcetext, palloc(), PARAM_FLAG_CONST, CachedPlanSource::param_types, ParamListInfoData::paramFetch, ParamListInfoData::paramFetchArg, ParamListInfoData::paramMask, ParamListInfoData::params, ParamListInfoData::parserSetup, ParamListInfoData::parserSetupArg, ParamExternData::pflags, PreparedStatement::plansource, ParamExternData::ptype, PreparedStatement::stmt_name, transformExpr(), and ParamExternData::value.

Referenced by ExecuteQuery(), and ExplainExecuteQuery().

329 {
330  Oid *param_types = pstmt->plansource->param_types;
331  int num_params = pstmt->plansource->num_params;
332  int nparams = list_length(params);
333  ParseState *pstate;
334  ParamListInfo paramLI;
335  List *exprstates;
336  ListCell *l;
337  int i;
338 
339  if (nparams != num_params)
340  ereport(ERROR,
341  (errcode(ERRCODE_SYNTAX_ERROR),
342  errmsg("wrong number of parameters for prepared statement \"%s\"",
343  pstmt->stmt_name),
344  errdetail("Expected %d parameters but got %d.",
345  num_params, nparams)));
346 
347  /* Quick exit if no parameters */
348  if (num_params == 0)
349  return NULL;
350 
351  /*
352  * We have to run parse analysis for the expressions. Since the parser is
353  * not cool about scribbling on its input, copy first.
354  */
355  params = copyObject(params);
356 
357  pstate = make_parsestate(NULL);
358  pstate->p_sourcetext = queryString;
359 
360  i = 0;
361  foreach(l, params)
362  {
363  Node *expr = lfirst(l);
364  Oid expected_type_id = param_types[i];
365  Oid given_type_id;
366 
367  expr = transformExpr(pstate, expr, EXPR_KIND_EXECUTE_PARAMETER);
368 
369  given_type_id = exprType(expr);
370 
371  expr = coerce_to_target_type(pstate, expr, given_type_id,
372  expected_type_id, -1,
375  -1);
376 
377  if (expr == NULL)
378  ereport(ERROR,
379  (errcode(ERRCODE_DATATYPE_MISMATCH),
380  errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
381  i + 1,
382  format_type_be(given_type_id),
383  format_type_be(expected_type_id)),
384  errhint("You will need to rewrite or cast the expression.")));
385 
386  /* Take care of collations in the finished expression. */
387  assign_expr_collations(pstate, expr);
388 
389  lfirst(l) = expr;
390  i++;
391  }
392 
393  /* Prepare the expressions for execution */
394  exprstates = ExecPrepareExprList(params, estate);
395 
396  paramLI = (ParamListInfo)
398  num_params * sizeof(ParamExternData));
399  /* we have static list of params, so no hooks needed */
400  paramLI->paramFetch = NULL;
401  paramLI->paramFetchArg = NULL;
402  paramLI->parserSetup = NULL;
403  paramLI->parserSetupArg = NULL;
404  paramLI->numParams = num_params;
405  paramLI->paramMask = NULL;
406 
407  i = 0;
408  foreach(l, exprstates)
409  {
410  ExprState *n = (ExprState *) lfirst(l);
411  ParamExternData *prm = &paramLI->params[i];
412 
413  prm->ptype = param_types[i];
414  prm->pflags = PARAM_FLAG_CONST;
416  GetPerTupleExprContext(estate),
417  &prm->isnull);
418 
419  i++;
420  }
421 
422  return paramLI;
423 }
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:76
Datum value
Definition: params.h:56
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:280
int errhint(const char *fmt,...)
Definition: elog.c:987
void * parserSetupArg
Definition: params.h:73
CachedPlanSource * plansource
Definition: prepare.h:31
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:147
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
ParserSetupHook parserSetup
Definition: params.h:72
struct ParamListInfoData * ParamListInfo
Definition: params.h:62
unsigned int Oid
Definition: postgres_ext.h:31
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void assign_expr_collations(ParseState *pstate, Node *expr)
#define GetPerTupleExprContext(estate)
Definition: executor.h:455
void * paramFetchArg
Definition: params.h:71
ParamFetchHook paramFetch
Definition: params.h:70
char stmt_name[NAMEDATALEN]
Definition: prepare.h:30
#define ERROR
Definition: elog.h:43
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:77
Oid * param_types
Definition: plancache.h:86
int errdetail(const char *fmt,...)
Definition: elog.c:873
struct Bitmapset * paramMask
Definition: params.h:75
const char * p_sourcetext
Definition: parse_node.h:168
#define ereport(elevel, rest)
Definition: elog.h:122
List * ExecPrepareExprList(List *nodes, EState *estate)
Definition: execExpr.c:511
struct ParamExternData ParamExternData
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
uint16 pflags
Definition: params.h:58
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define copyObject(obj)
Definition: nodes.h:621
Definition: pg_list.h:45
bool isnull
Definition: params.h:57
#define offsetof(type, field)
Definition: c.h:555
#define PARAM_FLAG_CONST
Definition: params.h:52
void ExecuteQuery ( ExecuteStmt stmt,
IntoClause intoClause,
const char *  queryString,
ParamListInfo  params,
DestReceiver dest,
char *  completionTag 
)

Definition at line 200 of file prepare.c.

References CMD_SELECT, CachedPlanSource::commandTag, PlannedStmt::commandType, CreateExecutorState(), CreateNewPortal(), elog, ereport, errcode(), errmsg(), ERROR, EState::es_param_list_info, EvaluateParams(), FETCH_ALL, FetchPreparedStatement(), CachedPlanSource::fixed_result, FreeExecutorState(), GetActiveSnapshot(), GetCachedPlan(), GetIntoRelEFlags(), linitial_node, list_length(), MemoryContextStrdup(), ExecuteStmt::name, NULL, CachedPlanSource::num_params, ExecuteStmt::params, PreparedStatement::plansource, PortalDefineQuery(), PortalDrop(), PortalGetHeapMemory, PortalRun(), PortalStart(), CachedPlanSource::query_string, IntoClause::skipData, CachedPlan::stmt_list, and PortalData::visible.

Referenced by ExecCreateTableAs(), and standard_ProcessUtility().

203 {
204  PreparedStatement *entry;
205  CachedPlan *cplan;
206  List *plan_list;
207  ParamListInfo paramLI = NULL;
208  EState *estate = NULL;
209  Portal portal;
210  char *query_string;
211  int eflags;
212  long count;
213 
214  /* Look it up in the hash table */
215  entry = FetchPreparedStatement(stmt->name, true);
216 
217  /* Shouldn't find a non-fixed-result cached plan */
218  if (!entry->plansource->fixed_result)
219  elog(ERROR, "EXECUTE does not support variable-result cached plans");
220 
221  /* Evaluate parameters, if any */
222  if (entry->plansource->num_params > 0)
223  {
224  /*
225  * Need an EState to evaluate parameters; must not delete it till end
226  * of query, in case parameters are pass-by-reference. Note that the
227  * passed-in "params" could possibly be referenced in the parameter
228  * expressions.
229  */
230  estate = CreateExecutorState();
231  estate->es_param_list_info = params;
232  paramLI = EvaluateParams(entry, stmt->params,
233  queryString, estate);
234  }
235 
236  /* Create a new portal to run the query in */
237  portal = CreateNewPortal();
238  /* Don't display the portal in pg_cursors, it is for internal use only */
239  portal->visible = false;
240 
241  /* Copy the plan's saved query string into the portal's memory */
242  query_string = MemoryContextStrdup(PortalGetHeapMemory(portal),
243  entry->plansource->query_string);
244 
245  /* Replan if needed, and increment plan refcount for portal */
246  cplan = GetCachedPlan(entry->plansource, paramLI, false, NULL);
247  plan_list = cplan->stmt_list;
248 
249  /*
250  * For CREATE TABLE ... AS EXECUTE, we must verify that the prepared
251  * statement is one that produces tuples. Currently we insist that it be
252  * a plain old SELECT. In future we might consider supporting other
253  * things such as INSERT ... RETURNING, but there are a couple of issues
254  * to be settled first, notably how WITH NO DATA should be handled in such
255  * a case (do we really want to suppress execution?) and how to pass down
256  * the OID-determining eflags (PortalStart won't handle them in such a
257  * case, and for that matter it's not clear the executor will either).
258  *
259  * For CREATE TABLE ... AS EXECUTE, we also have to ensure that the proper
260  * eflags and fetch count are passed to PortalStart/PortalRun.
261  */
262  if (intoClause)
263  {
264  PlannedStmt *pstmt;
265 
266  if (list_length(plan_list) != 1)
267  ereport(ERROR,
268  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
269  errmsg("prepared statement is not a SELECT")));
270  pstmt = linitial_node(PlannedStmt, plan_list);
271  if (pstmt->commandType != CMD_SELECT)
272  ereport(ERROR,
273  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
274  errmsg("prepared statement is not a SELECT")));
275 
276  /* Set appropriate eflags */
277  eflags = GetIntoRelEFlags(intoClause);
278 
279  /* And tell PortalRun whether to run to completion or not */
280  if (intoClause->skipData)
281  count = 0;
282  else
283  count = FETCH_ALL;
284  }
285  else
286  {
287  /* Plain old EXECUTE */
288  eflags = 0;
289  count = FETCH_ALL;
290  }
291 
292  PortalDefineQuery(portal,
293  NULL,
294  query_string,
295  entry->plansource->commandTag,
296  plan_list,
297  cplan);
298 
299  /*
300  * Run the portal as appropriate.
301  */
302  PortalStart(portal, paramLI, eflags, GetActiveSnapshot());
303 
304  (void) PortalRun(portal, count, false, true, dest, dest, completionTag);
305 
306  PortalDrop(portal, false);
307 
308  if (estate)
309  FreeExecutorState(estate);
310 
311  /* No need to pfree other memory, MemoryContext will be reset */
312 }
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, bool useResOwner, QueryEnvironment *queryEnv)
Definition: plancache.c:1135
Portal CreateNewPortal(void)
Definition: portalmem.c:230
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition: pquery.c:446
bool visible
Definition: portal.h:192
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, const char *commandTag, List *stmts, CachedPlan *cplan)
Definition: portalmem.c:277
const char * commandTag
Definition: plancache.h:85
CachedPlanSource * plansource
Definition: prepare.h:31
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:834
bool PortalRun(Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, char *completionTag)
Definition: pquery.c:690
int errcode(int sqlerrcode)
Definition: elog.c:575
bool skipData
Definition: primnodes.h:115
#define linitial_node(type, l)
Definition: pg_list.h:114
void FreeExecutorState(EState *estate)
Definition: execUtils.c:178
int GetIntoRelEFlags(IntoClause *intoClause)
Definition: createas.c:392
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
EState * CreateExecutorState(void)
Definition: execUtils.c:80
CmdType commandType
Definition: plannodes.h:45
#define NULL
Definition: c.h:229
const char * query_string
Definition: plancache.h:84
static int list_length(const List *l)
Definition: pg_list.h:89
#define PortalGetHeapMemory(portal)
Definition: portal.h:205
static ParamListInfo EvaluateParams(PreparedStatement *pstmt, List *params, const char *queryString, EState *estate)
Definition: prepare.c:327
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PortalDrop(Portal portal, bool isTopCommit)
Definition: portalmem.c:461
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1064
char * name
Definition: parsenodes.h:3264
ParamListInfo es_param_list_info
Definition: execnodes.h:432
List * params
Definition: parsenodes.h:3265
List * stmt_list
Definition: plancache.h:133
#define elog
Definition: elog.h:219
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:494
Definition: pg_list.h:45
#define FETCH_ALL
Definition: parsenodes.h:2638
void ExplainExecuteQuery ( ExecuteStmt execstmt,
IntoClause into,
ExplainState es,
const char *  queryString,
ParamListInfo  params,
QueryEnvironment queryEnv 
)

Definition at line 631 of file prepare.c.

References CMD_UTILITY, PlannedStmt::commandType, CreateExecutorState(), elog, ERROR, EState::es_param_list_info, EvaluateParams(), ExplainOnePlan(), ExplainOneUtility(), ExplainSeparatePlans(), FetchPreparedStatement(), CachedPlanSource::fixed_result, FreeExecutorState(), GetCachedPlan(), INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, lfirst_node, lnext, ExecuteStmt::name, NULL, CachedPlanSource::num_params, ExecuteStmt::params, PreparedStatement::plansource, CachedPlanSource::query_string, ReleaseCachedPlan(), CachedPlan::stmt_list, and PlannedStmt::utilityStmt.

Referenced by ExplainOneUtility().

634 {
635  PreparedStatement *entry;
636  const char *query_string;
637  CachedPlan *cplan;
638  List *plan_list;
639  ListCell *p;
640  ParamListInfo paramLI = NULL;
641  EState *estate = NULL;
642  instr_time planstart;
643  instr_time planduration;
644 
645  INSTR_TIME_SET_CURRENT(planstart);
646 
647  /* Look it up in the hash table */
648  entry = FetchPreparedStatement(execstmt->name, true);
649 
650  /* Shouldn't find a non-fixed-result cached plan */
651  if (!entry->plansource->fixed_result)
652  elog(ERROR, "EXPLAIN EXECUTE does not support variable-result cached plans");
653 
654  query_string = entry->plansource->query_string;
655 
656  /* Evaluate parameters, if any */
657  if (entry->plansource->num_params)
658  {
659  /*
660  * Need an EState to evaluate parameters; must not delete it till end
661  * of query, in case parameters are pass-by-reference. Note that the
662  * passed-in "params" could possibly be referenced in the parameter
663  * expressions.
664  */
665  estate = CreateExecutorState();
666  estate->es_param_list_info = params;
667  paramLI = EvaluateParams(entry, execstmt->params,
668  queryString, estate);
669  }
670 
671  /* Replan if needed, and acquire a transient refcount */
672  cplan = GetCachedPlan(entry->plansource, paramLI, true, queryEnv);
673 
674  INSTR_TIME_SET_CURRENT(planduration);
675  INSTR_TIME_SUBTRACT(planduration, planstart);
676 
677  plan_list = cplan->stmt_list;
678 
679  /* Explain each query */
680  foreach(p, plan_list)
681  {
682  PlannedStmt *pstmt = lfirst_node(PlannedStmt, p);
683 
684  if (pstmt->commandType != CMD_UTILITY)
685  ExplainOnePlan(pstmt, into, es, query_string, paramLI, queryEnv,
686  &planduration);
687  else
688  ExplainOneUtility(pstmt->utilityStmt, into, es, query_string,
689  paramLI, queryEnv);
690 
691  /* No need for CommandCounterIncrement, as ExplainOnePlan did it */
692 
693  /* Separate plans with an appropriate separator */
694  if (lnext(p) != NULL)
696  }
697 
698  if (estate)
699  FreeExecutorState(estate);
700 
701  ReleaseCachedPlan(cplan, true);
702 }
void ExplainOnePlan(PlannedStmt *plannedstmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv, const instr_time *planduration)
Definition: explain.c:467
CachedPlan * GetCachedPlan(CachedPlanSource *plansource, ParamListInfo boundParams, bool useResOwner, QueryEnvironment *queryEnv)
Definition: plancache.c:1135
void ExplainSeparatePlans(ExplainState *es)
Definition: explain.c:3422
CachedPlanSource * plansource
Definition: prepare.h:31
struct timeval instr_time
Definition: instr_time.h:147
void FreeExecutorState(EState *estate)
Definition: execUtils.c:178
#define ERROR
Definition: elog.h:43
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:167
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Node * utilityStmt
Definition: plannodes.h:84
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1256
#define lnext(lc)
Definition: pg_list.h:105
EState * CreateExecutorState(void)
Definition: execUtils.c:80
CmdType commandType
Definition: plannodes.h:45
#define NULL
Definition: c.h:229
const char * query_string
Definition: plancache.h:84
static ParamListInfo EvaluateParams(PreparedStatement *pstmt, List *params, const char *queryString, EState *estate)
Definition: prepare.c:327
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:153
char * name
Definition: parsenodes.h:3264
ParamListInfo es_param_list_info
Definition: execnodes.h:432
List * params
Definition: parsenodes.h:3265
List * stmt_list
Definition: plancache.h:133
#define elog
Definition: elog.h:219
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:494
Definition: pg_list.h:45
void ExplainOneUtility(Node *utilityStmt, IntoClause *into, ExplainState *es, const char *queryString, ParamListInfo params, QueryEnvironment *queryEnv)
Definition: explain.c:390
PreparedStatement* FetchPreparedStatement ( const char *  stmt_name,
bool  throwError 
)

Definition at line 494 of file prepare.c.

References ereport, errcode(), errmsg(), ERROR, HASH_FIND, hash_search(), and NULL.

Referenced by DropPreparedStatement(), errdetail_execute(), exec_bind_message(), exec_describe_statement_message(), ExecuteQuery(), ExplainExecuteQuery(), FetchStatementTargetList(), GetCommandLogLevel(), UtilityReturnsTuples(), and UtilityTupleDescriptor().

495 {
496  PreparedStatement *entry;
497 
498  /*
499  * If the hash table hasn't been initialized, it can't be storing
500  * anything, therefore it couldn't possibly store our plan.
501  */
502  if (prepared_queries)
504  stmt_name,
505  HASH_FIND,
506  NULL);
507  else
508  entry = NULL;
509 
510  if (!entry && throwError)
511  ereport(ERROR,
512  (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
513  errmsg("prepared statement \"%s\" does not exist",
514  stmt_name)));
515 
516  return entry;
517 }
int errcode(int sqlerrcode)
Definition: elog.c:575
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static HTAB * prepared_queries
Definition: prepare.c:46
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
TupleDesc FetchPreparedStatementResultDesc ( PreparedStatement stmt)

Definition at line 526 of file prepare.c.

References Assert, CreateTupleDescCopy(), CachedPlanSource::fixed_result, NULL, PreparedStatement::plansource, and CachedPlanSource::resultDesc.

Referenced by UtilityTupleDescriptor().

527 {
528  /*
529  * Since we don't allow prepared statements' result tupdescs to change,
530  * there's no need to worry about revalidating the cached plan here.
531  */
533  if (stmt->plansource->resultDesc)
535  else
536  return NULL;
537 }
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:141
CachedPlanSource * plansource
Definition: prepare.h:31
TupleDesc resultDesc
Definition: plancache.h:92
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
List* FetchPreparedStatementTargetList ( PreparedStatement stmt)

Definition at line 549 of file prepare.c.

References CachedPlanGetTargetList(), copyObject, NULL, and PreparedStatement::plansource.

Referenced by FetchStatementTargetList().

550 {
551  List *tlist;
552 
553  /* Get the plan's primary targetlist */
554  tlist = CachedPlanGetTargetList(stmt->plansource, NULL);
555 
556  /* Copy into caller's context in case plan gets invalidated */
557  return copyObject(tlist);
558 }
CachedPlanSource * plansource
Definition: prepare.h:31
List * CachedPlanGetTargetList(CachedPlanSource *plansource, QueryEnvironment *queryEnv)
Definition: plancache.c:1425
#define NULL
Definition: c.h:229
#define copyObject(obj)
Definition: nodes.h:621
Definition: pg_list.h:45
static void InitQueryHashTable ( void  )
static

Definition at line 430 of file prepare.c.

References HASHCTL::entrysize, hash_create(), HASH_ELEM, HASHCTL::keysize, MemSet, and NAMEDATALEN.

Referenced by StorePreparedStatement().

431 {
432  HASHCTL hash_ctl;
433 
434  MemSet(&hash_ctl, 0, sizeof(hash_ctl));
435 
436  hash_ctl.keysize = NAMEDATALEN;
437  hash_ctl.entrysize = sizeof(PreparedStatement);
438 
439  prepared_queries = hash_create("Prepared Queries",
440  32,
441  &hash_ctl,
442  HASH_ELEM);
443 }
#define HASH_ELEM
Definition: hsearch.h:87
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:857
#define NAMEDATALEN
static HTAB * prepared_queries
Definition: prepare.c:46
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
Size keysize
Definition: hsearch.h:72
Datum pg_prepared_statement ( PG_FUNCTION_ARGS  )

Definition at line 709 of file prepare.c.

References ReturnSetInfo::allowedModes, BoolGetDatum, BOOLOID, build_regtype_array(), CreateTemplateTupleDesc(), CStringGetTextDatum, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, PreparedStatement::from_sql, hash_seq_init(), hash_seq_search(), IsA, MemoryContextSwitchTo(), MemSet, NULL, CachedPlanSource::num_params, CachedPlanSource::param_types, PreparedStatement::plansource, PreparedStatement::prepare_time, CachedPlanSource::query_string, REGTYPEARRAYOID, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, PreparedStatement::stmt_name, TEXTOID, TimestampTzGetDatum, TIMESTAMPTZOID, TupleDescInitEntry(), tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), values, and work_mem.

710 {
711  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
712  TupleDesc tupdesc;
713  Tuplestorestate *tupstore;
714  MemoryContext per_query_ctx;
715  MemoryContext oldcontext;
716 
717  /* check to see if caller supports us returning a tuplestore */
718  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
719  ereport(ERROR,
720  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
721  errmsg("set-valued function called in context that cannot accept a set")));
722  if (!(rsinfo->allowedModes & SFRM_Materialize))
723  ereport(ERROR,
724  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
725  errmsg("materialize mode required, but it is not " \
726  "allowed in this context")));
727 
728  /* need to build tuplestore in query context */
729  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
730  oldcontext = MemoryContextSwitchTo(per_query_ctx);
731 
732  /*
733  * build tupdesc for result tuples. This must match the definition of the
734  * pg_prepared_statements view in system_views.sql
735  */
736  tupdesc = CreateTemplateTupleDesc(5, false);
737  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "name",
738  TEXTOID, -1, 0);
739  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "statement",
740  TEXTOID, -1, 0);
741  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepare_time",
742  TIMESTAMPTZOID, -1, 0);
743  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "parameter_types",
744  REGTYPEARRAYOID, -1, 0);
745  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "from_sql",
746  BOOLOID, -1, 0);
747 
748  /*
749  * We put all the tuples into a tuplestore in one scan of the hashtable.
750  * This avoids any issue of the hashtable possibly changing between calls.
751  */
752  tupstore =
754  false, work_mem);
755 
756  /* generate junk in short-term context */
757  MemoryContextSwitchTo(oldcontext);
758 
759  /* hash table might be uninitialized */
760  if (prepared_queries)
761  {
762  HASH_SEQ_STATUS hash_seq;
763  PreparedStatement *prep_stmt;
764 
765  hash_seq_init(&hash_seq, prepared_queries);
766  while ((prep_stmt = hash_seq_search(&hash_seq)) != NULL)
767  {
768  Datum values[5];
769  bool nulls[5];
770 
771  MemSet(nulls, 0, sizeof(nulls));
772 
773  values[0] = CStringGetTextDatum(prep_stmt->stmt_name);
774  values[1] = CStringGetTextDatum(prep_stmt->plansource->query_string);
775  values[2] = TimestampTzGetDatum(prep_stmt->prepare_time);
776  values[3] = build_regtype_array(prep_stmt->plansource->param_types,
777  prep_stmt->plansource->num_params);
778  values[4] = BoolGetDatum(prep_stmt->from_sql);
779 
780  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
781  }
782  }
783 
784  /* clean up and return the tuplestore */
785  tuplestore_donestoring(tupstore);
786 
787  rsinfo->returnMode = SFRM_Materialize;
788  rsinfo->setResult = tupstore;
789  rsinfo->setDesc = tupdesc;
790 
791  return (Datum) 0;
792 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
#define TIMESTAMPTZOID
Definition: pg_type.h:525
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#define TEXTOID
Definition: pg_type.h:324
CachedPlanSource * plansource
Definition: prepare.h:31
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:857
static HTAB * prepared_queries
Definition: prepare.c:46
char stmt_name[NAMEDATALEN]
Definition: prepare.h:30
#define ERROR
Definition: elog.h:43
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
Oid * param_types
Definition: plancache.h:86
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:497
#define ereport(elevel, rest)
Definition: elog.h:122
static Datum build_regtype_array(Oid *param_types, int num_params)
Definition: prepare.c:800
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
uintptr_t Datum
Definition: postgres.h:372
int work_mem
Definition: globals.c:112
#define BoolGetDatum(X)
Definition: postgres.h:408
int allowedModes
Definition: execnodes.h:268
TimestampTz prepare_time
Definition: prepare.h:33
SetFunctionReturnMode returnMode
Definition: execnodes.h:270
#define NULL
Definition: c.h:229
const char * query_string
Definition: plancache.h:84
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1351
#define BOOLOID
Definition: pg_type.h:288
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1341
Tuplestorestate * setResult
Definition: execnodes.h:273
static Datum values[MAXATTR]
Definition: bootstrap.c:163
#define REGTYPEARRAYOID
Definition: pg_type.h:596
ExprContext * econtext
Definition: execnodes.h:266
TupleDesc setDesc
Definition: execnodes.h:274
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CStringGetTextDatum(s)
Definition: builtins.h:91
int16 AttrNumber
Definition: attnum.h:21
void PrepareQuery ( PrepareStmt stmt,
const char *  queryString,
int  stmt_location,
int  stmt_len 
)

Definition at line 57 of file prepare.c.

References PrepareStmt::argtypes, CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, Query::commandType, CompleteCachedPlan(), copyObject, CreateCachedPlan(), CreateCommandTag(), CURSOR_OPT_PARALLEL_OK, ereport, errcode(), errmsg(), ERROR, i, InvalidOid, lfirst, list_length(), make_parsestate(), makeNode, PrepareStmt::name, NULL, ParseState::p_sourcetext, palloc(), parse_analyze_varparams(), PrepareStmt::query, QueryRewrite(), RawStmt::stmt, RawStmt::stmt_len, RawStmt::stmt_location, StorePreparedStatement(), typenameTypeId(), and UNKNOWNOID.

Referenced by standard_ProcessUtility().

59 {
60  RawStmt *rawstmt;
61  CachedPlanSource *plansource;
62  Oid *argtypes = NULL;
63  int nargs;
64  Query *query;
65  List *query_list;
66  int i;
67 
68  /*
69  * Disallow empty-string statement name (conflicts with protocol-level
70  * unnamed statement).
71  */
72  if (!stmt->name || stmt->name[0] == '\0')
73  ereport(ERROR,
74  (errcode(ERRCODE_INVALID_PSTATEMENT_DEFINITION),
75  errmsg("invalid statement name: must not be empty")));
76 
77  /*
78  * Need to wrap the contained statement in a RawStmt node to pass it to
79  * parse analysis.
80  *
81  * Because parse analysis scribbles on the raw querytree, we must make a
82  * copy to ensure we don't modify the passed-in tree. FIXME someday.
83  */
84  rawstmt = makeNode(RawStmt);
85  rawstmt->stmt = (Node *) copyObject(stmt->query);
86  rawstmt->stmt_location = stmt_location;
87  rawstmt->stmt_len = stmt_len;
88 
89  /*
90  * Create the CachedPlanSource before we do parse analysis, since it needs
91  * to see the unmodified raw parse tree.
92  */
93  plansource = CreateCachedPlan(rawstmt, queryString,
94  CreateCommandTag(stmt->query));
95 
96  /* Transform list of TypeNames to array of type OIDs */
97  nargs = list_length(stmt->argtypes);
98 
99  if (nargs)
100  {
101  ParseState *pstate;
102  ListCell *l;
103 
104  /*
105  * typenameTypeId wants a ParseState to carry the source query string.
106  * Is it worth refactoring its API to avoid this?
107  */
108  pstate = make_parsestate(NULL);
109  pstate->p_sourcetext = queryString;
110 
111  argtypes = (Oid *) palloc(nargs * sizeof(Oid));
112  i = 0;
113 
114  foreach(l, stmt->argtypes)
115  {
116  TypeName *tn = lfirst(l);
117  Oid toid = typenameTypeId(pstate, tn);
118 
119  argtypes[i++] = toid;
120  }
121  }
122 
123  /*
124  * Analyze the statement using these parameter types (any parameters
125  * passed in from above us will not be visible to it), allowing
126  * information about unknown parameters to be deduced from context.
127  */
128  query = parse_analyze_varparams(rawstmt, queryString,
129  &argtypes, &nargs);
130 
131  /*
132  * Check that all parameter types were determined.
133  */
134  for (i = 0; i < nargs; i++)
135  {
136  Oid argtype = argtypes[i];
137 
138  if (argtype == InvalidOid || argtype == UNKNOWNOID)
139  ereport(ERROR,
140  (errcode(ERRCODE_INDETERMINATE_DATATYPE),
141  errmsg("could not determine data type of parameter $%d",
142  i + 1)));
143  }
144 
145  /*
146  * grammar only allows OptimizableStmt, so this check should be redundant
147  */
148  switch (query->commandType)
149  {
150  case CMD_SELECT:
151  case CMD_INSERT:
152  case CMD_UPDATE:
153  case CMD_DELETE:
154  /* OK */
155  break;
156  default:
157  ereport(ERROR,
158  (errcode(ERRCODE_INVALID_PSTATEMENT_DEFINITION),
159  errmsg("utility statements cannot be prepared")));
160  break;
161  }
162 
163  /* Rewrite the query. The result could be 0, 1, or many queries. */
164  query_list = QueryRewrite(query);
165 
166  /* Finish filling in the CachedPlanSource */
167  CompleteCachedPlan(plansource,
168  query_list,
169  NULL,
170  argtypes,
171  nargs,
172  NULL,
173  NULL,
174  CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
175  true); /* fixed result */
176 
177  /*
178  * Save the results.
179  */
181  plansource,
182  true);
183 }
List * QueryRewrite(Query *parsetree)
Definition: nodes.h:509
int errcode(int sqlerrcode)
Definition: elog.c:575
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams)
Definition: analyze.c:130
unsigned int Oid
Definition: postgres_ext.h:31
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define ERROR
Definition: elog.h:43
Node * stmt
Definition: parsenodes.h:1392
CachedPlanSource * CreateCachedPlan(RawStmt *raw_parse_tree, const char *query_string, const char *commandTag)
Definition: plancache.c:152
const char * p_sourcetext
Definition: parse_node.h:168
#define ereport(elevel, rest)
Definition: elog.h:122
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2033
int stmt_len
Definition: parsenodes.h:1394
int stmt_location
Definition: parsenodes.h:1393
void StorePreparedStatement(const char *stmt_name, CachedPlanSource *plansource, bool from_sql)
Definition: prepare.c:452
#define InvalidOid
Definition: postgres_ext.h:36
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
char * name
Definition: parsenodes.h:3250
#define lfirst(lc)
Definition: pg_list.h:106
void CompleteCachedPlan(CachedPlanSource *plansource, List *querytree_list, MemoryContext querytree_context, Oid *param_types, int num_params, ParserSetupHook parserSetup, void *parserSetupArg, int cursor_options, bool fixed_result)
Definition: plancache.c:325
Node * query
Definition: parsenodes.h:3252
static int list_length(const List *l)
Definition: pg_list.h:89
List * argtypes
Definition: parsenodes.h:3251
#define UNKNOWNOID
Definition: pg_type.h:431
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2603
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define copyObject(obj)
Definition: nodes.h:621
Definition: pg_list.h:45
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition: parse_type.c:274
void StorePreparedStatement ( const char *  stmt_name,
CachedPlanSource plansource,
bool  from_sql 
)

Definition at line 452 of file prepare.c.

References ereport, errcode(), errmsg(), ERROR, PreparedStatement::from_sql, GetCurrentStatementStartTimestamp(), HASH_ENTER, hash_search(), InitQueryHashTable(), PreparedStatement::plansource, PreparedStatement::prepare_time, and SaveCachedPlan().

Referenced by exec_parse_message(), and PrepareQuery().

455 {
456  PreparedStatement *entry;
458  bool found;
459 
460  /* Initialize the hash table, if necessary */
461  if (!prepared_queries)
463 
464  /* Add entry to hash table */
466  stmt_name,
467  HASH_ENTER,
468  &found);
469 
470  /* Shouldn't get a duplicate entry */
471  if (found)
472  ereport(ERROR,
473  (errcode(ERRCODE_DUPLICATE_PSTATEMENT),
474  errmsg("prepared statement \"%s\" already exists",
475  stmt_name)));
476 
477  /* Fill in the hash table entry */
478  entry->plansource = plansource;
479  entry->from_sql = from_sql;
480  entry->prepare_time = cur_ts;
481 
482  /* Now it's safe to move the CachedPlanSource to permanent memory */
483  SaveCachedPlan(plansource);
484 }
static void InitQueryHashTable(void)
Definition: prepare.c:430
CachedPlanSource * plansource
Definition: prepare.h:31
int64 TimestampTz
Definition: timestamp.h:39
int errcode(int sqlerrcode)
Definition: elog.c:575
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
static HTAB * prepared_queries
Definition: prepare.c:46
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
void SaveCachedPlan(CachedPlanSource *plansource)
Definition: plancache.c:441
TimestampTz prepare_time
Definition: prepare.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:797
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition: xact.c:717

Variable Documentation

HTAB* prepared_queries = NULL
static

Definition at line 46 of file prepare.c.