PostgreSQL Source Code  git master
pquery.h File Reference
#include "nodes/parsenodes.h"
#include "utils/portal.h"
Include dependency graph for pquery.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

PortalStrategy ChoosePortalStrategy (List *stmts)
 
ListFetchPortalTargetList (Portal portal)
 
ListFetchStatementTargetList (Node *stmt)
 
void PortalStart (Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
 
void PortalSetResultFormat (Portal portal, int nFormats, int16 *formats)
 
bool PortalRun (Portal portal, long count, bool isTopLevel, bool run_once, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
 
uint64 PortalRunFetch (Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
 
bool PlannedStmtRequiresSnapshot (struct PlannedStmt *pstmt)
 
void EnsurePortalSnapshotExists (void)
 

Variables

PGDLLIMPORT Portal ActivePortal
 

Function Documentation

◆ ChoosePortalStrategy()

PortalStrategy ChoosePortalStrategy ( List stmts)

Definition at line 206 of file pquery.c.

References PlannedStmt::canSetTag, Query::canSetTag, CMD_SELECT, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, elog, ERROR, PlannedStmt::hasModifyingCTE, Query::hasModifyingCTE, PlannedStmt::hasReturning, IsA, lfirst, linitial, list_length(), NIL, nodeTag, PORTAL_MULTI_QUERY, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_UTIL_SELECT, Query::returningList, UtilityReturnsTuples(), PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by PlanCacheComputeResultDesc(), and PortalStart().

207 {
208  int nSetTag;
209  ListCell *lc;
210 
211  /*
212  * PORTAL_ONE_SELECT and PORTAL_UTIL_SELECT need only consider the
213  * single-statement case, since there are no rewrite rules that can add
214  * auxiliary queries to a SELECT or a utility command. PORTAL_ONE_MOD_WITH
215  * likewise allows only one top-level statement.
216  */
217  if (list_length(stmts) == 1)
218  {
219  Node *stmt = (Node *) linitial(stmts);
220 
221  if (IsA(stmt, Query))
222  {
223  Query *query = (Query *) stmt;
224 
225  if (query->canSetTag)
226  {
227  if (query->commandType == CMD_SELECT)
228  {
229  if (query->hasModifyingCTE)
230  return PORTAL_ONE_MOD_WITH;
231  else
232  return PORTAL_ONE_SELECT;
233  }
234  if (query->commandType == CMD_UTILITY)
235  {
236  if (UtilityReturnsTuples(query->utilityStmt))
237  return PORTAL_UTIL_SELECT;
238  /* it can't be ONE_RETURNING, so give up */
239  return PORTAL_MULTI_QUERY;
240  }
241  }
242  }
243  else if (IsA(stmt, PlannedStmt))
244  {
245  PlannedStmt *pstmt = (PlannedStmt *) stmt;
246 
247  if (pstmt->canSetTag)
248  {
249  if (pstmt->commandType == CMD_SELECT)
250  {
251  if (pstmt->hasModifyingCTE)
252  return PORTAL_ONE_MOD_WITH;
253  else
254  return PORTAL_ONE_SELECT;
255  }
256  if (pstmt->commandType == CMD_UTILITY)
257  {
258  if (UtilityReturnsTuples(pstmt->utilityStmt))
259  return PORTAL_UTIL_SELECT;
260  /* it can't be ONE_RETURNING, so give up */
261  return PORTAL_MULTI_QUERY;
262  }
263  }
264  }
265  else
266  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
267  }
268 
269  /*
270  * PORTAL_ONE_RETURNING has to allow auxiliary queries added by rewrite.
271  * Choose PORTAL_ONE_RETURNING if there is exactly one canSetTag query and
272  * it has a RETURNING list.
273  */
274  nSetTag = 0;
275  foreach(lc, stmts)
276  {
277  Node *stmt = (Node *) lfirst(lc);
278 
279  if (IsA(stmt, Query))
280  {
281  Query *query = (Query *) stmt;
282 
283  if (query->canSetTag)
284  {
285  if (++nSetTag > 1)
286  return PORTAL_MULTI_QUERY; /* no need to look further */
287  if (query->commandType == CMD_UTILITY ||
288  query->returningList == NIL)
289  return PORTAL_MULTI_QUERY; /* no need to look further */
290  }
291  }
292  else if (IsA(stmt, PlannedStmt))
293  {
294  PlannedStmt *pstmt = (PlannedStmt *) stmt;
295 
296  if (pstmt->canSetTag)
297  {
298  if (++nSetTag > 1)
299  return PORTAL_MULTI_QUERY; /* no need to look further */
300  if (pstmt->commandType == CMD_UTILITY ||
301  !pstmt->hasReturning)
302  return PORTAL_MULTI_QUERY; /* no need to look further */
303  }
304  }
305  else
306  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(stmt));
307  }
308  if (nSetTag == 1)
309  return PORTAL_ONE_RETURNING;
310 
311  /* Else, it's the general case... */
312  return PORTAL_MULTI_QUERY;
313 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
Definition: nodes.h:536
Node * utilityStmt
Definition: parsenodes.h:128
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
bool hasReturning
Definition: plannodes.h:50
Node * utilityStmt
Definition: plannodes.h:86
bool UtilityReturnsTuples(Node *parsetree)
Definition: utility.c:2004
List * returningList
Definition: parsenodes.h:156
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
CmdType commandType
Definition: parsenodes.h:120
#define lfirst(lc)
Definition: pg_list.h:169
bool hasModifyingCTE
Definition: plannodes.h:52
bool canSetTag
Definition: parsenodes.h:126
static int list_length(const List *l)
Definition: pg_list.h:149
#define nodeTag(nodeptr)
Definition: nodes.h:541
#define elog(elevel,...)
Definition: elog.h:232
bool hasModifyingCTE
Definition: parsenodes.h:139

◆ EnsurePortalSnapshotExists()

void EnsurePortalSnapshotExists ( void  )

Definition at line 1769 of file pquery.c.

References ActivePortal, ActiveSnapshotSet(), Assert, elog, ERROR, GetActiveSnapshot(), GetTransactionSnapshot(), PortalData::portalSnapshot, PushActiveSnapshot(), and unlikely.

Referenced by _SPI_execute_plan(), exec_eval_simple_expr(), and ExecuteCallStmt().

1770 {
1771  Portal portal;
1772 
1773  /*
1774  * Nothing to do if a snapshot is set. (We take it on faith that the
1775  * outermost active snapshot belongs to some Portal; or if there is no
1776  * Portal, it's somebody else's responsibility to manage things.)
1777  */
1778  if (ActiveSnapshotSet())
1779  return;
1780 
1781  /* Otherwise, we'd better have an active Portal */
1782  portal = ActivePortal;
1783  if (unlikely(portal == NULL))
1784  elog(ERROR, "cannot execute SQL without an outer snapshot or portal");
1785  Assert(portal->portalSnapshot == NULL);
1786 
1787  /* Create a new snapshot and make it active */
1789  /* PushActiveSnapshot might have copied the snapshot */
1790  portal->portalSnapshot = GetActiveSnapshot();
1791 }
Portal ActivePortal
Definition: pquery.c:35
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define ERROR
Definition: elog.h:46
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:798
#define Assert(condition)
Definition: c.h:804
Snapshot portalSnapshot
Definition: portal.h:169
#define elog(elevel,...)
Definition: elog.h:232
#define unlikely(x)
Definition: c.h:273

◆ FetchPortalTargetList()

List* FetchPortalTargetList ( Portal  portal)

Definition at line 323 of file pquery.c.

References FetchStatementTargetList(), NIL, PORTAL_MULTI_QUERY, PortalGetPrimaryStmt(), and PortalData::strategy.

Referenced by exec_describe_portal_message(), FetchStatementTargetList(), and printtup_startup().

324 {
325  /* no point in looking if we determined it doesn't return tuples */
326  if (portal->strategy == PORTAL_MULTI_QUERY)
327  return NIL;
328  /* get the primary statement and find out what it returns */
330 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:536
PlannedStmt * PortalGetPrimaryStmt(Portal portal)
Definition: portalmem.c:151
List * FetchStatementTargetList(Node *stmt)
Definition: pquery.c:345
PortalStrategy strategy
Definition: portal.h:145

◆ FetchStatementTargetList()

List* FetchStatementTargetList ( Node stmt)

Definition at line 345 of file pquery.c.

References Assert, CMD_SELECT, CMD_UTILITY, PlannedStmt::commandType, Query::commandType, FetchPortalTargetList(), FetchPreparedStatement(), FetchPreparedStatementTargetList(), GetPortalByName(), PlannedStmt::hasReturning, IsA, FetchStmt::ismove, ExecuteStmt::name, NIL, PlannedStmt::planTree, PortalIsValid, FetchStmt::portalname, Query::returningList, Plan::targetlist, Query::targetList, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by CachedPlanGetTargetList(), and FetchPortalTargetList().

346 {
347  if (stmt == NULL)
348  return NIL;
349  if (IsA(stmt, Query))
350  {
351  Query *query = (Query *) stmt;
352 
353  if (query->commandType == CMD_UTILITY)
354  {
355  /* transfer attention to utility statement */
356  stmt = query->utilityStmt;
357  }
358  else
359  {
360  if (query->commandType == CMD_SELECT)
361  return query->targetList;
362  if (query->returningList)
363  return query->returningList;
364  return NIL;
365  }
366  }
367  if (IsA(stmt, PlannedStmt))
368  {
369  PlannedStmt *pstmt = (PlannedStmt *) stmt;
370 
371  if (pstmt->commandType == CMD_UTILITY)
372  {
373  /* transfer attention to utility statement */
374  stmt = pstmt->utilityStmt;
375  }
376  else
377  {
378  if (pstmt->commandType == CMD_SELECT)
379  return pstmt->planTree->targetlist;
380  if (pstmt->hasReturning)
381  return pstmt->planTree->targetlist;
382  return NIL;
383  }
384  }
385  if (IsA(stmt, FetchStmt))
386  {
387  FetchStmt *fstmt = (FetchStmt *) stmt;
388  Portal subportal;
389 
390  Assert(!fstmt->ismove);
391  subportal = GetPortalByName(fstmt->portalname);
392  Assert(PortalIsValid(subportal));
393  return FetchPortalTargetList(subportal);
394  }
395  if (IsA(stmt, ExecuteStmt))
396  {
397  ExecuteStmt *estmt = (ExecuteStmt *) stmt;
398  PreparedStatement *entry;
399 
400  entry = FetchPreparedStatement(estmt->name, true);
401  return FetchPreparedStatementTargetList(entry);
402  }
403  return NIL;
404 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
Node * utilityStmt
Definition: parsenodes.h:128
struct Plan * planTree
Definition: plannodes.h:64
List * targetList
Definition: parsenodes.h:150
bool hasReturning
Definition: plannodes.h:50
Node * utilityStmt
Definition: plannodes.h:86
List * returningList
Definition: parsenodes.h:156
char * portalname
Definition: parsenodes.h:2870
#define PortalIsValid(p)
Definition: portal.h:211
bool ismove
Definition: parsenodes.h:2871
CmdType commandType
Definition: plannodes.h:46
List * FetchPreparedStatementTargetList(PreparedStatement *stmt)
Definition: prepare.c:523
CmdType commandType
Definition: parsenodes.h:120
#define Assert(condition)
Definition: c.h:804
List * targetlist
Definition: plannodes.h:141
char * name
Definition: parsenodes.h:3564
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:323
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:468

◆ PlannedStmtRequiresSnapshot()

bool PlannedStmtRequiresSnapshot ( struct PlannedStmt pstmt)

Definition at line 1721 of file pquery.c.

References IsA, and PlannedStmt::utilityStmt.

Referenced by _SPI_execute_plan(), and PortalRunUtility().

1722 {
1723  Node *utilityStmt = pstmt->utilityStmt;
1724 
1725  /* If it's not a utility statement, it definitely needs a snapshot */
1726  if (utilityStmt == NULL)
1727  return true;
1728 
1729  /*
1730  * Most utility statements need a snapshot, and the default presumption
1731  * about new ones should be that they do too. Hence, enumerate those that
1732  * do not need one.
1733  *
1734  * Transaction control, LOCK, and SET must *not* set a snapshot, since
1735  * they need to be executable at the start of a transaction-snapshot-mode
1736  * transaction without freezing a snapshot. By extension we allow SHOW
1737  * not to set a snapshot. The other stmts listed are just efficiency
1738  * hacks. Beware of listing anything that can modify the database --- if,
1739  * say, it has to update an index with expressions that invoke
1740  * user-defined functions, then it had better have a snapshot.
1741  */
1742  if (IsA(utilityStmt, TransactionStmt) ||
1743  IsA(utilityStmt, LockStmt) ||
1744  IsA(utilityStmt, VariableSetStmt) ||
1745  IsA(utilityStmt, VariableShowStmt) ||
1746  IsA(utilityStmt, ConstraintsSetStmt) ||
1747  /* efficiency hacks from here down */
1748  IsA(utilityStmt, FetchStmt) ||
1749  IsA(utilityStmt, ListenStmt) ||
1750  IsA(utilityStmt, NotifyStmt) ||
1751  IsA(utilityStmt, UnlistenStmt) ||
1752  IsA(utilityStmt, CheckPointStmt))
1753  return false;
1754 
1755  return true;
1756 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
Definition: nodes.h:536
Node * utilityStmt
Definition: plannodes.h:86

◆ PortalRun()

bool PortalRun ( Portal  portal,
long  count,
bool  isTopLevel,
bool  run_once,
DestReceiver dest,
DestReceiver altdest,
QueryCompletion qc 
)

Definition at line 679 of file pquery.c.

References ActivePortal, Assert, AssertArg, PortalData::atEnd, QueryCompletion::commandTag, CopyQueryCompletion(), CurrentMemoryContext, CurrentResourceOwner, DEBUG3, elog, ERROR, FillPortalStore(), PortalData::holdStore, InitializeQueryCompletion(), log_executor_stats, MarkPortalActive(), MarkPortalDone(), MarkPortalFailed(), MemoryContextSwitchTo(), QueryCompletion::nprocessed, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PORTAL_MULTI_QUERY, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_READY, PORTAL_UTIL_SELECT, PortalContext, PortalData::portalContext, PortalIsValid, PortalRunMulti(), PortalRunSelect(), PortalData::qc, ResetUsage(), PortalData::resowner, PortalData::run_once, ShowUsage(), PortalData::status, PortalData::strategy, TopTransactionContext, and TopTransactionResourceOwner.

Referenced by exec_execute_message(), exec_simple_query(), and ExecuteQuery().

682 {
683  bool result;
684  uint64 nprocessed;
685  ResourceOwner saveTopTransactionResourceOwner;
686  MemoryContext saveTopTransactionContext;
687  Portal saveActivePortal;
688  ResourceOwner saveResourceOwner;
689  MemoryContext savePortalContext;
690  MemoryContext saveMemoryContext;
691 
692  AssertArg(PortalIsValid(portal));
693 
694  TRACE_POSTGRESQL_QUERY_EXECUTE_START();
695 
696  /* Initialize empty completion data */
697  if (qc)
699 
701  {
702  elog(DEBUG3, "PortalRun");
703  /* PORTAL_MULTI_QUERY logs its own stats per query */
704  ResetUsage();
705  }
706 
707  /*
708  * Check for improper portal use, and mark portal active.
709  */
710  MarkPortalActive(portal);
711 
712  /* Set run_once flag. Shouldn't be clear if previously set. */
713  Assert(!portal->run_once || run_once);
714  portal->run_once = run_once;
715 
716  /*
717  * Set up global portal context pointers.
718  *
719  * We have to play a special game here to support utility commands like
720  * VACUUM and CLUSTER, which internally start and commit transactions.
721  * When we are called to execute such a command, CurrentResourceOwner will
722  * be pointing to the TopTransactionResourceOwner --- which will be
723  * destroyed and replaced in the course of the internal commit and
724  * restart. So we need to be prepared to restore it as pointing to the
725  * exit-time TopTransactionResourceOwner. (Ain't that ugly? This idea of
726  * internally starting whole new transactions is not good.)
727  * CurrentMemoryContext has a similar problem, but the other pointers we
728  * save here will be NULL or pointing to longer-lived objects.
729  */
730  saveTopTransactionResourceOwner = TopTransactionResourceOwner;
731  saveTopTransactionContext = TopTransactionContext;
732  saveActivePortal = ActivePortal;
733  saveResourceOwner = CurrentResourceOwner;
734  savePortalContext = PortalContext;
735  saveMemoryContext = CurrentMemoryContext;
736  PG_TRY();
737  {
738  ActivePortal = portal;
739  if (portal->resowner)
740  CurrentResourceOwner = portal->resowner;
741  PortalContext = portal->portalContext;
742 
744 
745  switch (portal->strategy)
746  {
747  case PORTAL_ONE_SELECT:
749  case PORTAL_ONE_MOD_WITH:
750  case PORTAL_UTIL_SELECT:
751 
752  /*
753  * If we have not yet run the command, do so, storing its
754  * results in the portal's tuplestore. But we don't do that
755  * for the PORTAL_ONE_SELECT case.
756  */
757  if (portal->strategy != PORTAL_ONE_SELECT && !portal->holdStore)
758  FillPortalStore(portal, isTopLevel);
759 
760  /*
761  * Now fetch desired portion of results.
762  */
763  nprocessed = PortalRunSelect(portal, true, count, dest);
764 
765  /*
766  * If the portal result contains a command tag and the caller
767  * gave us a pointer to store it, copy it and update the
768  * rowcount.
769  */
770  if (qc && portal->qc.commandTag != CMDTAG_UNKNOWN)
771  {
772  CopyQueryCompletion(qc, &portal->qc);
773  qc->nprocessed = nprocessed;
774  }
775 
776  /* Mark portal not active */
777  portal->status = PORTAL_READY;
778 
779  /*
780  * Since it's a forward fetch, say DONE iff atEnd is now true.
781  */
782  result = portal->atEnd;
783  break;
784 
785  case PORTAL_MULTI_QUERY:
786  PortalRunMulti(portal, isTopLevel, false,
787  dest, altdest, qc);
788 
789  /* Prevent portal's commands from being re-executed */
790  MarkPortalDone(portal);
791 
792  /* Always complete at end of RunMulti */
793  result = true;
794  break;
795 
796  default:
797  elog(ERROR, "unrecognized portal strategy: %d",
798  (int) portal->strategy);
799  result = false; /* keep compiler quiet */
800  break;
801  }
802  }
803  PG_CATCH();
804  {
805  /* Uncaught error while executing portal: mark it dead */
806  MarkPortalFailed(portal);
807 
808  /* Restore global vars and propagate error */
809  if (saveMemoryContext == saveTopTransactionContext)
811  else
812  MemoryContextSwitchTo(saveMemoryContext);
813  ActivePortal = saveActivePortal;
814  if (saveResourceOwner == saveTopTransactionResourceOwner)
816  else
817  CurrentResourceOwner = saveResourceOwner;
818  PortalContext = savePortalContext;
819 
820  PG_RE_THROW();
821  }
822  PG_END_TRY();
823 
824  if (saveMemoryContext == saveTopTransactionContext)
826  else
827  MemoryContextSwitchTo(saveMemoryContext);
828  ActivePortal = saveActivePortal;
829  if (saveResourceOwner == saveTopTransactionResourceOwner)
831  else
832  CurrentResourceOwner = saveResourceOwner;
833  PortalContext = savePortalContext;
834 
836  ShowUsage("EXECUTOR STATISTICS");
837 
838  TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
839 
840  return result;
841 }
bool atEnd
Definition: portal.h:199
MemoryContext TopTransactionContext
Definition: mcxt.c:53
#define DEBUG3
Definition: elog.h:23
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:148
void ShowUsage(const char *title)
Definition: postgres.c:4806
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
void MarkPortalActive(Portal portal)
Definition: portalmem.c:394
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext portalContext
Definition: portal.h:120
static uint64 PortalRunSelect(Portal portal, bool forward, long count, DestReceiver *dest)
Definition: pquery.c:862
bool run_once
Definition: portal.h:147
MemoryContext PortalContext
Definition: mcxt.c:57
void ResetUsage(void)
Definition: postgres.c:4799
#define ERROR
Definition: elog.h:46
uint64 nprocessed
Definition: cmdtag.h:31
void InitializeQueryCompletion(QueryCompletion *qc)
Definition: cmdtag.c:38
static void FillPortalStore(Portal portal, bool isTopLevel)
Definition: pquery.c:995
void MarkPortalDone(Portal portal)
Definition: portalmem.c:413
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
PortalStrategy strategy
Definition: portal.h:145
#define AssertArg(condition)
Definition: c.h:806
#define PortalIsValid(p)
Definition: portal.h:211
CommandTag commandTag
Definition: cmdtag.h:30
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition: cmdtag.h:44
#define PG_CATCH()
Definition: elog.h:323
QueryCompletion qc
Definition: portal.h:137
#define Assert(condition)
Definition: c.h:804
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:354
ResourceOwner resowner
Definition: portal.h:121
Tuplestorestate * holdStore
Definition: portal.h:176
#define elog(elevel,...)
Definition: elog.h:232
bool log_executor_stats
Definition: guc.c:579
static void PortalRunMulti(Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:1179
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338

◆ PortalRunFetch()

uint64 PortalRunFetch ( Portal  portal,
FetchDirection  fdirection,
long  count,
DestReceiver dest 
)

Definition at line 1380 of file pquery.c.

References ActivePortal, Assert, AssertArg, CurrentResourceOwner, DoPortalRunFetch(), elog, ERROR, FillPortalStore(), PortalData::holdStore, MarkPortalActive(), MarkPortalFailed(), MemoryContextSwitchTo(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_READY, PORTAL_UTIL_SELECT, PortalContext, PortalData::portalContext, PortalIsValid, PortalData::resowner, PortalData::run_once, PortalData::status, and PortalData::strategy.

Referenced by _SPI_cursor_operation(), and PerformPortalFetch().

1384 {
1385  uint64 result;
1386  Portal saveActivePortal;
1387  ResourceOwner saveResourceOwner;
1388  MemoryContext savePortalContext;
1389  MemoryContext oldContext;
1390 
1391  AssertArg(PortalIsValid(portal));
1392 
1393  /*
1394  * Check for improper portal use, and mark portal active.
1395  */
1396  MarkPortalActive(portal);
1397 
1398  /* If supporting FETCH, portal can't be run-once. */
1399  Assert(!portal->run_once);
1400 
1401  /*
1402  * Set up global portal context pointers.
1403  */
1404  saveActivePortal = ActivePortal;
1405  saveResourceOwner = CurrentResourceOwner;
1406  savePortalContext = PortalContext;
1407  PG_TRY();
1408  {
1409  ActivePortal = portal;
1410  if (portal->resowner)
1411  CurrentResourceOwner = portal->resowner;
1412  PortalContext = portal->portalContext;
1413 
1414  oldContext = MemoryContextSwitchTo(PortalContext);
1415 
1416  switch (portal->strategy)
1417  {
1418  case PORTAL_ONE_SELECT:
1419  result = DoPortalRunFetch(portal, fdirection, count, dest);
1420  break;
1421 
1422  case PORTAL_ONE_RETURNING:
1423  case PORTAL_ONE_MOD_WITH:
1424  case PORTAL_UTIL_SELECT:
1425 
1426  /*
1427  * If we have not yet run the command, do so, storing its
1428  * results in the portal's tuplestore.
1429  */
1430  if (!portal->holdStore)
1431  FillPortalStore(portal, false /* isTopLevel */ );
1432 
1433  /*
1434  * Now fetch desired portion of results.
1435  */
1436  result = DoPortalRunFetch(portal, fdirection, count, dest);
1437  break;
1438 
1439  default:
1440  elog(ERROR, "unsupported portal strategy");
1441  result = 0; /* keep compiler quiet */
1442  break;
1443  }
1444  }
1445  PG_CATCH();
1446  {
1447  /* Uncaught error while executing portal: mark it dead */
1448  MarkPortalFailed(portal);
1449 
1450  /* Restore global vars and propagate error */
1451  ActivePortal = saveActivePortal;
1452  CurrentResourceOwner = saveResourceOwner;
1453  PortalContext = savePortalContext;
1454 
1455  PG_RE_THROW();
1456  }
1457  PG_END_TRY();
1458 
1459  MemoryContextSwitchTo(oldContext);
1460 
1461  /* Mark portal not active */
1462  portal->status = PORTAL_READY;
1463 
1464  ActivePortal = saveActivePortal;
1465  CurrentResourceOwner = saveResourceOwner;
1466  PortalContext = savePortalContext;
1467 
1468  return result;
1469 }
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
void MarkPortalActive(Portal portal)
Definition: portalmem.c:394
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext portalContext
Definition: portal.h:120
static uint64 DoPortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition: pquery.c:1481
bool run_once
Definition: portal.h:147
MemoryContext PortalContext
Definition: mcxt.c:57
#define ERROR
Definition: elog.h:46
static void FillPortalStore(Portal portal, bool isTopLevel)
Definition: pquery.c:995
PortalStrategy strategy
Definition: portal.h:145
#define AssertArg(condition)
Definition: c.h:806
#define PortalIsValid(p)
Definition: portal.h:211
#define PG_CATCH()
Definition: elog.h:323
#define Assert(condition)
Definition: c.h:804
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:354
ResourceOwner resowner
Definition: portal.h:121
Tuplestorestate * holdStore
Definition: portal.h:176
#define elog(elevel,...)
Definition: elog.h:232
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338

◆ PortalSetResultFormat()

void PortalSetResultFormat ( Portal  portal,
int  nFormats,
int16 formats 
)

Definition at line 618 of file pquery.c.

References ereport, errcode(), errmsg(), ERROR, PortalData::formats, i, MemoryContextAlloc(), TupleDescData::natts, PortalData::portalContext, and PortalData::tupDesc.

Referenced by exec_bind_message(), and exec_simple_query().

619 {
620  int natts;
621  int i;
622 
623  /* Do nothing if portal won't return tuples */
624  if (portal->tupDesc == NULL)
625  return;
626  natts = portal->tupDesc->natts;
627  portal->formats = (int16 *)
629  natts * sizeof(int16));
630  if (nFormats > 1)
631  {
632  /* format specified for each column */
633  if (nFormats != natts)
634  ereport(ERROR,
635  (errcode(ERRCODE_PROTOCOL_VIOLATION),
636  errmsg("bind message has %d result formats but query has %d columns",
637  nFormats, natts)));
638  memcpy(portal->formats, formats, natts * sizeof(int16));
639  }
640  else if (nFormats > 0)
641  {
642  /* single format specified, use for all columns */
643  int16 format1 = formats[0];
644 
645  for (i = 0; i < natts; i++)
646  portal->formats[i] = format1;
647  }
648  else
649  {
650  /* use default format for all columns */
651  for (i = 0; i < natts; i++)
652  portal->formats[i] = 0;
653  }
654 }
signed short int16
Definition: c.h:428
int errcode(int sqlerrcode)
Definition: elog.c:698
MemoryContext portalContext
Definition: portal.h:120
#define ERROR
Definition: elog.h:46
int16 * formats
Definition: portal.h:161
TupleDesc tupDesc
Definition: portal.h:159
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
int i

◆ PortalStart()

void PortalStart ( Portal  portal,
ParamListInfo  params,
int  eflags,
Snapshot  snapshot 
)

Definition at line 430 of file pquery.c.

References ActivePortal, Assert, AssertArg, AssertState, PortalData::atEnd, PortalData::atStart, ChoosePortalStrategy(), CMD_UTILITY, PlannedStmt::commandType, CreateQueryDesc(), CurrentResourceOwner, CURSOR_OPT_SCROLL, PortalData::cursorOptions, EXEC_FLAG_BACKWARD, EXEC_FLAG_REWIND, ExecCleanTypeFromTL(), ExecutorStart(), GetActiveSnapshot(), GetTransactionSnapshot(), InvalidSnapshot, linitial_node, MarkPortalFailed(), MemoryContextSwitchTo(), None_Receiver, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PlannedStmt::planTree, PopActiveSnapshot(), PORTAL_DEFINED, PORTAL_MULTI_QUERY, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_READY, PORTAL_UTIL_SELECT, PortalContext, PortalData::portalContext, PortalGetPrimaryStmt(), PortalIsValid, PortalData::portalParams, PortalData::portalPos, PushActiveSnapshot(), PortalData::queryDesc, PortalData::queryEnv, PortalData::resowner, PortalData::sourceText, PortalData::status, PortalData::stmts, PortalData::strategy, Plan::targetlist, QueryDesc::tupDesc, PortalData::tupDesc, PlannedStmt::utilityStmt, and UtilityTupleDescriptor().

Referenced by exec_bind_message(), exec_simple_query(), ExecuteQuery(), PerformCursorOpen(), and SPI_cursor_open_internal().

432 {
433  Portal saveActivePortal;
434  ResourceOwner saveResourceOwner;
435  MemoryContext savePortalContext;
436  MemoryContext oldContext;
437  QueryDesc *queryDesc;
438  int myeflags;
439 
440  AssertArg(PortalIsValid(portal));
441  AssertState(portal->status == PORTAL_DEFINED);
442 
443  /*
444  * Set up global portal context pointers.
445  */
446  saveActivePortal = ActivePortal;
447  saveResourceOwner = CurrentResourceOwner;
448  savePortalContext = PortalContext;
449  PG_TRY();
450  {
451  ActivePortal = portal;
452  if (portal->resowner)
453  CurrentResourceOwner = portal->resowner;
454  PortalContext = portal->portalContext;
455 
456  oldContext = MemoryContextSwitchTo(PortalContext);
457 
458  /* Must remember portal param list, if any */
459  portal->portalParams = params;
460 
461  /*
462  * Determine the portal execution strategy
463  */
464  portal->strategy = ChoosePortalStrategy(portal->stmts);
465 
466  /*
467  * Fire her up according to the strategy
468  */
469  switch (portal->strategy)
470  {
471  case PORTAL_ONE_SELECT:
472 
473  /* Must set snapshot before starting executor. */
474  if (snapshot)
475  PushActiveSnapshot(snapshot);
476  else
478 
479  /*
480  * We could remember the snapshot in portal->portalSnapshot,
481  * but presently there seems no need to, as this code path
482  * cannot be used for non-atomic execution. Hence there can't
483  * be any commit/abort that might destroy the snapshot.
484  */
485 
486  /*
487  * Create QueryDesc in portal's context; for the moment, set
488  * the destination to DestNone.
489  */
490  queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts),
491  portal->sourceText,
495  params,
496  portal->queryEnv,
497  0);
498 
499  /*
500  * If it's a scrollable cursor, executor needs to support
501  * REWIND and backwards scan, as well as whatever the caller
502  * might've asked for.
503  */
504  if (portal->cursorOptions & CURSOR_OPT_SCROLL)
505  myeflags = eflags | EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD;
506  else
507  myeflags = eflags;
508 
509  /*
510  * Call ExecutorStart to prepare the plan for execution
511  */
512  ExecutorStart(queryDesc, myeflags);
513 
514  /*
515  * This tells PortalCleanup to shut down the executor
516  */
517  portal->queryDesc = queryDesc;
518 
519  /*
520  * Remember tuple descriptor (computed by ExecutorStart)
521  */
522  portal->tupDesc = queryDesc->tupDesc;
523 
524  /*
525  * Reset cursor position data to "start of query"
526  */
527  portal->atStart = true;
528  portal->atEnd = false; /* allow fetches */
529  portal->portalPos = 0;
530 
532  break;
533 
535  case PORTAL_ONE_MOD_WITH:
536 
537  /*
538  * We don't start the executor until we are told to run the
539  * portal. We do need to set up the result tupdesc.
540  */
541  {
542  PlannedStmt *pstmt;
543 
544  pstmt = PortalGetPrimaryStmt(portal);
545  portal->tupDesc =
547  }
548 
549  /*
550  * Reset cursor position data to "start of query"
551  */
552  portal->atStart = true;
553  portal->atEnd = false; /* allow fetches */
554  portal->portalPos = 0;
555  break;
556 
557  case PORTAL_UTIL_SELECT:
558 
559  /*
560  * We don't set snapshot here, because PortalRunUtility will
561  * take care of it if needed.
562  */
563  {
564  PlannedStmt *pstmt = PortalGetPrimaryStmt(portal);
565 
566  Assert(pstmt->commandType == CMD_UTILITY);
567  portal->tupDesc = UtilityTupleDescriptor(pstmt->utilityStmt);
568  }
569 
570  /*
571  * Reset cursor position data to "start of query"
572  */
573  portal->atStart = true;
574  portal->atEnd = false; /* allow fetches */
575  portal->portalPos = 0;
576  break;
577 
578  case PORTAL_MULTI_QUERY:
579  /* Need do nothing now */
580  portal->tupDesc = NULL;
581  break;
582  }
583  }
584  PG_CATCH();
585  {
586  /* Uncaught error while executing portal: mark it dead */
587  MarkPortalFailed(portal);
588 
589  /* Restore global vars and propagate error */
590  ActivePortal = saveActivePortal;
591  CurrentResourceOwner = saveResourceOwner;
592  PortalContext = savePortalContext;
593 
594  PG_RE_THROW();
595  }
596  PG_END_TRY();
597 
598  MemoryContextSwitchTo(oldContext);
599 
600  ActivePortal = saveActivePortal;
601  CurrentResourceOwner = saveResourceOwner;
602  PortalContext = savePortalContext;
603 
604  portal->status = PORTAL_READY;
605 }
#define AssertState(condition)
Definition: c.h:807
bool atEnd
Definition: portal.h:199
TupleDesc ExecCleanTypeFromTL(List *targetList)
Definition: execTuples.c:1950
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:130
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
List * stmts
Definition: portal.h:138
#define linitial_node(type, l)
Definition: pg_list.h:177
DestReceiver * None_Receiver
Definition: dest.c:96
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
MemoryContext portalContext
Definition: portal.h:120
struct Plan * planTree
Definition: plannodes.h:64
MemoryContext PortalContext
Definition: mcxt.c:57
ParamListInfo portalParams
Definition: portal.h:141
PlannedStmt * PortalGetPrimaryStmt(Portal portal)
Definition: portalmem.c:151
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
#define EXEC_FLAG_BACKWARD
Definition: executor.h:58
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
Node * utilityStmt
Definition: plannodes.h:86
PortalStrategy strategy
Definition: portal.h:145
#define EXEC_FLAG_REWIND
Definition: executor.h:57
#define AssertArg(condition)
Definition: c.h:806
QueryDesc * queryDesc
Definition: portal.h:156
TupleDesc tupDesc
Definition: execdesc.h:47
#define InvalidSnapshot
Definition: snapshot.h:123
#define PortalIsValid(p)
Definition: portal.h:211
CmdType commandType
Definition: plannodes.h:46
const char * sourceText
Definition: portal.h:135
TupleDesc tupDesc
Definition: portal.h:159
#define PG_CATCH()
Definition: elog.h:323
#define Assert(condition)
Definition: c.h:804
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:354
QueryEnvironment * queryEnv
Definition: portal.h:142
PortalStrategy ChoosePortalStrategy(List *stmts)
Definition: pquery.c:206
List * targetlist
Definition: plannodes.h:141
ResourceOwner resowner
Definition: portal.h:121
bool atStart
Definition: portal.h:198
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:2819
int cursorOptions
Definition: portal.h:146
#define PG_TRY()
Definition: elog.h:313
TupleDesc UtilityTupleDescriptor(Node *parsetree)
Definition: utility.c:2060
#define PG_END_TRY()
Definition: elog.h:338
uint64 portalPos
Definition: portal.h:200

Variable Documentation

◆ ActivePortal