PostgreSQL Source Code  git master
pquery.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/xact.h"
#include "commands/prepare.h"
#include "executor/tstoreReceiver.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "tcop/pquery.h"
#include "tcop/utility.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
Include dependency graph for pquery.c:

Go to the source code of this file.

Functions

static void ProcessQuery (PlannedStmt *plan, const char *sourceText, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
 
static void FillPortalStore (Portal portal, bool isTopLevel)
 
static uint64 RunFromStore (Portal portal, ScanDirection direction, uint64 count, DestReceiver *dest)
 
static uint64 PortalRunSelect (Portal portal, bool forward, long count, DestReceiver *dest)
 
static void PortalRunUtility (Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
 
static void PortalRunMulti (Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
 
static uint64 DoPortalRunFetch (Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
 
static void DoPortalRewind (Portal portal)
 
QueryDescCreateQueryDesc (PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
 
void FreeQueryDesc (QueryDesc *qdesc)
 
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)
 

Variables

Portal ActivePortal = NULL
 

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:579
Definition: nodes.h:528
Node * utilityStmt
Definition: parsenodes.h:120
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:43
bool hasReturning
Definition: plannodes.h:50
Node * utilityStmt
Definition: plannodes.h:86
bool UtilityReturnsTuples(Node *parsetree)
Definition: utility.c:1960
List * returningList
Definition: parsenodes.h:146
bool canSetTag
Definition: plannodes.h:54
CmdType commandType
Definition: plannodes.h:46
CmdType commandType
Definition: parsenodes.h:112
#define lfirst(lc)
Definition: pg_list.h:169
bool hasModifyingCTE
Definition: plannodes.h:52
bool canSetTag
Definition: parsenodes.h:118
static int list_length(const List *l)
Definition: pg_list.h:149
#define nodeTag(nodeptr)
Definition: nodes.h:533
#define elog(elevel,...)
Definition: elog.h:214
bool hasModifyingCTE
Definition: parsenodes.h:131

◆ CreateQueryDesc()

QueryDesc* CreateQueryDesc ( PlannedStmt plannedstmt,
const char *  sourceText,
Snapshot  snapshot,
Snapshot  crosscheck_snapshot,
DestReceiver dest,
ParamListInfo  params,
QueryEnvironment queryEnv,
int  instrument_options 
)

Definition at line 67 of file pquery.c.

References QueryDesc::already_executed, PlannedStmt::commandType, QueryDesc::crosscheck_snapshot, QueryDesc::dest, generate_unaccent_rules::dest, QueryDesc::estate, QueryDesc::instrument_options, QueryDesc::operation, palloc(), QueryDesc::params, QueryDesc::plannedstmt, QueryDesc::planstate, QueryDesc::queryEnv, RegisterSnapshot(), QueryDesc::snapshot, QueryDesc::sourceText, QueryDesc::totaltime, and QueryDesc::tupDesc.

Referenced by _SPI_execute_plan(), BeginCopy(), ExecCreateTableAs(), ExecParallelGetQueryDesc(), execute_sql_string(), ExplainOnePlan(), PortalStart(), postquel_start(), ProcessQuery(), and refresh_matview_datafill().

75 {
76  QueryDesc *qd = (QueryDesc *) palloc(sizeof(QueryDesc));
77 
78  qd->operation = plannedstmt->commandType; /* operation */
79  qd->plannedstmt = plannedstmt; /* plan */
80  qd->sourceText = sourceText; /* query text */
81  qd->snapshot = RegisterSnapshot(snapshot); /* snapshot */
82  /* RI check snapshot */
83  qd->crosscheck_snapshot = RegisterSnapshot(crosscheck_snapshot);
84  qd->dest = dest; /* output dest */
85  qd->params = params; /* parameter values passed into query */
86  qd->queryEnv = queryEnv;
87  qd->instrument_options = instrument_options; /* instrumentation wanted? */
88 
89  /* null these fields until set by ExecutorStart */
90  qd->tupDesc = NULL;
91  qd->estate = NULL;
92  qd->planstate = NULL;
93  qd->totaltime = NULL;
94 
95  /* not yet executed */
96  qd->already_executed = false;
97 
98  return qd;
99 }
EState * estate
Definition: execdesc.h:48
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
Snapshot snapshot
Definition: execdesc.h:39
int instrument_options
Definition: execdesc.h:44
QueryEnvironment * queryEnv
Definition: execdesc.h:43
PlanState * planstate
Definition: execdesc.h:49
ParamListInfo params
Definition: execdesc.h:42
TupleDesc tupDesc
Definition: execdesc.h:47
CmdType operation
Definition: execdesc.h:36
CmdType commandType
Definition: plannodes.h:46
bool already_executed
Definition: execdesc.h:52
Snapshot crosscheck_snapshot
Definition: execdesc.h:40
struct Instrumentation * totaltime
Definition: execdesc.h:55
const char * sourceText
Definition: execdesc.h:38
DestReceiver * dest
Definition: execdesc.h:41
void * palloc(Size size)
Definition: mcxt.c:950
PlannedStmt * plannedstmt
Definition: execdesc.h:37

◆ DoPortalRewind()

static void DoPortalRewind ( Portal  portal)
static

Definition at line 1657 of file pquery.c.

References PortalData::atEnd, PortalData::atStart, ExecutorRewind(), PortalData::holdContext, PortalData::holdStore, MemoryContextSwitchTo(), PopActiveSnapshot(), PortalData::portalPos, PushActiveSnapshot(), PortalData::queryDesc, QueryDesc::snapshot, and tuplestore_rescan().

Referenced by DoPortalRunFetch().

1658 {
1659  QueryDesc *queryDesc;
1660 
1661  /* Rewind holdStore, if we have one */
1662  if (portal->holdStore)
1663  {
1664  MemoryContext oldcontext;
1665 
1666  oldcontext = MemoryContextSwitchTo(portal->holdContext);
1667  tuplestore_rescan(portal->holdStore);
1668  MemoryContextSwitchTo(oldcontext);
1669  }
1670 
1671  /* Rewind executor, if active */
1672  queryDesc = portal->queryDesc;
1673  if (queryDesc)
1674  {
1675  PushActiveSnapshot(queryDesc->snapshot);
1676  ExecutorRewind(queryDesc);
1678  }
1679 
1680  portal->atStart = true;
1681  portal->atEnd = false;
1682  portal->portalPos = 0;
1683 }
void tuplestore_rescan(Tuplestorestate *state)
Definition: tuplestore.c:1233
bool atEnd
Definition: portal.h:191
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext holdContext
Definition: portal.h:169
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Snapshot snapshot
Definition: execdesc.h:39
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
QueryDesc * queryDesc
Definition: portal.h:156
void ExecutorRewind(QueryDesc *queryDesc)
Definition: execMain.c:528
bool atStart
Definition: portal.h:190
Tuplestorestate * holdStore
Definition: portal.h:168
uint64 portalPos
Definition: portal.h:192

◆ DoPortalRunFetch()

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

Definition at line 1472 of file pquery.c.

References Assert, PortalData::atEnd, PortalData::atStart, DestNone, DoPortalRewind(), elog, ERROR, FETCH_ABSOLUTE, FETCH_ALL, FETCH_BACKWARD, FETCH_FORWARD, FETCH_RELATIVE, _DestReceiver::mydest, None_Receiver, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_ONE_SELECT, PORTAL_UTIL_SELECT, PortalData::portalPos, PortalRunSelect(), and PortalData::strategy.

Referenced by PortalRunFetch().

1476 {
1477  bool forward;
1478 
1479  Assert(portal->strategy == PORTAL_ONE_SELECT ||
1480  portal->strategy == PORTAL_ONE_RETURNING ||
1481  portal->strategy == PORTAL_ONE_MOD_WITH ||
1482  portal->strategy == PORTAL_UTIL_SELECT);
1483 
1484  switch (fdirection)
1485  {
1486  case FETCH_FORWARD:
1487  if (count < 0)
1488  {
1489  fdirection = FETCH_BACKWARD;
1490  count = -count;
1491  }
1492  /* fall out of switch to share code with FETCH_BACKWARD */
1493  break;
1494  case FETCH_BACKWARD:
1495  if (count < 0)
1496  {
1497  fdirection = FETCH_FORWARD;
1498  count = -count;
1499  }
1500  /* fall out of switch to share code with FETCH_FORWARD */
1501  break;
1502  case FETCH_ABSOLUTE:
1503  if (count > 0)
1504  {
1505  /*
1506  * Definition: Rewind to start, advance count-1 rows, return
1507  * next row (if any).
1508  *
1509  * In practice, if the goal is less than halfway back to the
1510  * start, it's better to scan from where we are.
1511  *
1512  * Also, if current portalPos is outside the range of "long",
1513  * do it the hard way to avoid possible overflow of the count
1514  * argument to PortalRunSelect. We must exclude exactly
1515  * LONG_MAX, as well, lest the count look like FETCH_ALL.
1516  *
1517  * In any case, we arrange to fetch the target row going
1518  * forwards.
1519  */
1520  if ((uint64) (count - 1) <= portal->portalPos / 2 ||
1521  portal->portalPos >= (uint64) LONG_MAX)
1522  {
1523  DoPortalRewind(portal);
1524  if (count > 1)
1525  PortalRunSelect(portal, true, count - 1,
1526  None_Receiver);
1527  }
1528  else
1529  {
1530  long pos = (long) portal->portalPos;
1531 
1532  if (portal->atEnd)
1533  pos++; /* need one extra fetch if off end */
1534  if (count <= pos)
1535  PortalRunSelect(portal, false, pos - count + 1,
1536  None_Receiver);
1537  else if (count > pos + 1)
1538  PortalRunSelect(portal, true, count - pos - 1,
1539  None_Receiver);
1540  }
1541  return PortalRunSelect(portal, true, 1L, dest);
1542  }
1543  else if (count < 0)
1544  {
1545  /*
1546  * Definition: Advance to end, back up abs(count)-1 rows,
1547  * return prior row (if any). We could optimize this if we
1548  * knew in advance where the end was, but typically we won't.
1549  * (Is it worth considering case where count > half of size of
1550  * query? We could rewind once we know the size ...)
1551  */
1552  PortalRunSelect(portal, true, FETCH_ALL, None_Receiver);
1553  if (count < -1)
1554  PortalRunSelect(portal, false, -count - 1, None_Receiver);
1555  return PortalRunSelect(portal, false, 1L, dest);
1556  }
1557  else
1558  {
1559  /* count == 0 */
1560  /* Rewind to start, return zero rows */
1561  DoPortalRewind(portal);
1562  return PortalRunSelect(portal, true, 0L, dest);
1563  }
1564  break;
1565  case FETCH_RELATIVE:
1566  if (count > 0)
1567  {
1568  /*
1569  * Definition: advance count-1 rows, return next row (if any).
1570  */
1571  if (count > 1)
1572  PortalRunSelect(portal, true, count - 1, None_Receiver);
1573  return PortalRunSelect(portal, true, 1L, dest);
1574  }
1575  else if (count < 0)
1576  {
1577  /*
1578  * Definition: back up abs(count)-1 rows, return prior row (if
1579  * any).
1580  */
1581  if (count < -1)
1582  PortalRunSelect(portal, false, -count - 1, None_Receiver);
1583  return PortalRunSelect(portal, false, 1L, dest);
1584  }
1585  else
1586  {
1587  /* count == 0 */
1588  /* Same as FETCH FORWARD 0, so fall out of switch */
1589  fdirection = FETCH_FORWARD;
1590  }
1591  break;
1592  default:
1593  elog(ERROR, "bogus direction");
1594  break;
1595  }
1596 
1597  /*
1598  * Get here with fdirection == FETCH_FORWARD or FETCH_BACKWARD, and count
1599  * >= 0.
1600  */
1601  forward = (fdirection == FETCH_FORWARD);
1602 
1603  /*
1604  * Zero count means to re-fetch the current row, if any (per SQL)
1605  */
1606  if (count == 0)
1607  {
1608  bool on_row;
1609 
1610  /* Are we sitting on a row? */
1611  on_row = (!portal->atStart && !portal->atEnd);
1612 
1613  if (dest->mydest == DestNone)
1614  {
1615  /* MOVE 0 returns 0/1 based on if FETCH 0 would return a row */
1616  return on_row ? 1 : 0;
1617  }
1618  else
1619  {
1620  /*
1621  * If we are sitting on a row, back up one so we can re-fetch it.
1622  * If we are not sitting on a row, we still have to start up and
1623  * shut down the executor so that the destination is initialized
1624  * and shut down correctly; so keep going. To PortalRunSelect,
1625  * count == 0 means we will retrieve no row.
1626  */
1627  if (on_row)
1628  {
1629  PortalRunSelect(portal, false, 1L, None_Receiver);
1630  /* Set up to fetch one row forward */
1631  count = 1;
1632  forward = true;
1633  }
1634  }
1635  }
1636 
1637  /*
1638  * Optimize MOVE BACKWARD ALL into a Rewind.
1639  */
1640  if (!forward && count == FETCH_ALL && dest->mydest == DestNone)
1641  {
1642  uint64 result = portal->portalPos;
1643 
1644  if (result > 0 && !portal->atEnd)
1645  result--;
1646  DoPortalRewind(portal);
1647  return result;
1648  }
1649 
1650  return PortalRunSelect(portal, forward, count, dest);
1651 }
bool atEnd
Definition: portal.h:191
CommandDest mydest
Definition: dest.h:129
DestReceiver * None_Receiver
Definition: dest.c:96
static uint64 PortalRunSelect(Portal portal, bool forward, long count, DestReceiver *dest)
Definition: pquery.c:855
#define ERROR
Definition: elog.h:43
Definition: dest.h:89
PortalStrategy strategy
Definition: portal.h:145
#define Assert(condition)
Definition: c.h:746
bool atStart
Definition: portal.h:190
#define elog(elevel,...)
Definition: elog.h:214
static void DoPortalRewind(Portal portal)
Definition: pquery.c:1657
uint64 portalPos
Definition: portal.h:192
#define FETCH_ALL
Definition: parsenodes.h:2756

◆ 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:528
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:579
Portal GetPortalByName(const char *name)
Definition: portalmem.c:130
Node * utilityStmt
Definition: parsenodes.h:120
struct Plan * planTree
Definition: plannodes.h:64
List * targetList
Definition: parsenodes.h:140
bool hasReturning
Definition: plannodes.h:50
Node * utilityStmt
Definition: plannodes.h:86
List * returningList
Definition: parsenodes.h:146
char * portalname
Definition: parsenodes.h:2763
#define PortalIsValid(p)
Definition: portal.h:203
bool ismove
Definition: parsenodes.h:2764
CmdType commandType
Definition: plannodes.h:46
List * FetchPreparedStatementTargetList(PreparedStatement *stmt)
Definition: prepare.c:524
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:746
List * targetlist
Definition: plannodes.h:136
char * name
Definition: parsenodes.h:3445
List * FetchPortalTargetList(Portal portal)
Definition: pquery.c:323
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition: prepare.c:469

◆ FillPortalStore()

static void FillPortalStore ( Portal  portal,
bool  isTopLevel 
)
static

Definition at line 988 of file pquery.c.

References QueryCompletion::commandTag, CopyQueryCompletion(), CreateDestReceiver(), DestTuplestore, elog, ERROR, PortalData::holdContext, PortalData::holdStore, InitializeQueryCompletion(), linitial_node, None_Receiver, PORTAL_ONE_MOD_WITH, PORTAL_ONE_RETURNING, PORTAL_UTIL_SELECT, PortalCreateHoldStore(), PortalRunMulti(), PortalRunUtility(), PortalData::qc, _DestReceiver::rDestroy, SetTuplestoreDestReceiverParams(), PortalData::stmts, and PortalData::strategy.

Referenced by PortalRun(), and PortalRunFetch().

989 {
990  DestReceiver *treceiver;
991  QueryCompletion qc;
992 
994  PortalCreateHoldStore(portal);
995  treceiver = CreateDestReceiver(DestTuplestore);
997  portal->holdStore,
998  portal->holdContext,
999  false,
1000  NULL,
1001  NULL);
1002 
1003  switch (portal->strategy)
1004  {
1005  case PORTAL_ONE_RETURNING:
1006  case PORTAL_ONE_MOD_WITH:
1007 
1008  /*
1009  * Run the portal to completion just as for the default
1010  * PORTAL_MULTI_QUERY case, but send the primary query's output to
1011  * the tuplestore. Auxiliary query outputs are discarded. Set the
1012  * portal's holdSnapshot to the snapshot used (or a copy of it).
1013  */
1014  PortalRunMulti(portal, isTopLevel, true,
1015  treceiver, None_Receiver, &qc);
1016  break;
1017 
1018  case PORTAL_UTIL_SELECT:
1019  PortalRunUtility(portal, linitial_node(PlannedStmt, portal->stmts),
1020  isTopLevel, true, treceiver, &qc);
1021  break;
1022 
1023  default:
1024  elog(ERROR, "unsupported portal strategy: %d",
1025  (int) portal->strategy);
1026  break;
1027  }
1028 
1029  /* Override portal completion data with actual command results */
1030  if (qc.commandTag != CMDTAG_UNKNOWN)
1031  CopyQueryCompletion(&portal->qc, &qc);
1032 
1033  treceiver->rDestroy(treceiver);
1034 }
void SetTuplestoreDestReceiverParams(DestReceiver *self, Tuplestorestate *tStore, MemoryContext tContext, bool detoast, TupleDesc target_tupdesc, const char *map_failure_msg)
MemoryContext holdContext
Definition: portal.h:169
List * stmts
Definition: portal.h:138
#define linitial_node(type, l)
Definition: pg_list.h:177
DestReceiver * None_Receiver
Definition: dest.c:96
static void PortalRunUtility(Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:1115
#define ERROR
Definition: elog.h:43
void InitializeQueryCompletion(QueryCompletion *qc)
Definition: cmdtag.c:38
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
PortalStrategy strategy
Definition: portal.h:145
CommandTag commandTag
Definition: cmdtag.h:30
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition: cmdtag.h:44
void(* rDestroy)(DestReceiver *self)
Definition: dest.h:127
QueryCompletion qc
Definition: portal.h:137
void PortalCreateHoldStore(Portal portal)
Definition: portalmem.c:330
Tuplestorestate * holdStore
Definition: portal.h:168
#define elog(elevel,...)
Definition: elog.h:214
static void PortalRunMulti(Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition: pquery.c:1186

◆ FreeQueryDesc()

void FreeQueryDesc ( QueryDesc qdesc)

Definition at line 105 of file pquery.c.

References Assert, QueryDesc::crosscheck_snapshot, QueryDesc::estate, pfree(), QueryDesc::snapshot, and UnregisterSnapshot().

Referenced by _SPI_execute_plan(), EndCopyTo(), ExecCreateTableAs(), execute_sql_string(), ExplainOnePlan(), ParallelQueryMain(), PersistHoldablePortal(), PortalCleanup(), postquel_end(), ProcessQuery(), and refresh_matview_datafill().

106 {
107  /* Can't be a live query */
108  Assert(qdesc->estate == NULL);
109 
110  /* forget our snapshots */
113 
114  /* Only the QueryDesc itself need be freed */
115  pfree(qdesc);
116 }
EState * estate
Definition: execdesc.h:48
Snapshot snapshot
Definition: execdesc.h:39
void pfree(void *pointer)
Definition: mcxt.c:1057
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
Snapshot crosscheck_snapshot
Definition: execdesc.h:40
#define Assert(condition)
Definition: c.h:746

◆ PortalRun()

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

Definition at line 672 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().

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

◆ PortalRunFetch()

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

Definition at line 1370 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().

1374 {
1375  uint64 result;
1376  Portal saveActivePortal;
1377  ResourceOwner saveResourceOwner;
1378  MemoryContext savePortalContext;
1379  MemoryContext oldContext;
1380 
1381  AssertArg(PortalIsValid(portal));
1382 
1383  /*
1384  * Check for improper portal use, and mark portal active.
1385  */
1386  MarkPortalActive(portal);
1387 
1388  /* If supporting FETCH, portal can't be run-once. */
1389  Assert(!portal->run_once);
1390 
1391  /*
1392  * Set up global portal context pointers.
1393  */
1394  saveActivePortal = ActivePortal;
1395  saveResourceOwner = CurrentResourceOwner;
1396  savePortalContext = PortalContext;
1397  PG_TRY();
1398  {
1399  ActivePortal = portal;
1400  if (portal->resowner)
1401  CurrentResourceOwner = portal->resowner;
1402  PortalContext = portal->portalContext;
1403 
1404  oldContext = MemoryContextSwitchTo(PortalContext);
1405 
1406  switch (portal->strategy)
1407  {
1408  case PORTAL_ONE_SELECT:
1409  result = DoPortalRunFetch(portal, fdirection, count, dest);
1410  break;
1411 
1412  case PORTAL_ONE_RETURNING:
1413  case PORTAL_ONE_MOD_WITH:
1414  case PORTAL_UTIL_SELECT:
1415 
1416  /*
1417  * If we have not yet run the command, do so, storing its
1418  * results in the portal's tuplestore.
1419  */
1420  if (!portal->holdStore)
1421  FillPortalStore(portal, false /* isTopLevel */ );
1422 
1423  /*
1424  * Now fetch desired portion of results.
1425  */
1426  result = DoPortalRunFetch(portal, fdirection, count, dest);
1427  break;
1428 
1429  default:
1430  elog(ERROR, "unsupported portal strategy");
1431  result = 0; /* keep compiler quiet */
1432  break;
1433  }
1434  }
1435  PG_CATCH();
1436  {
1437  /* Uncaught error while executing portal: mark it dead */
1438  MarkPortalFailed(portal);
1439 
1440  /* Restore global vars and propagate error */
1441  ActivePortal = saveActivePortal;
1442  CurrentResourceOwner = saveResourceOwner;
1443  PortalContext = savePortalContext;
1444 
1445  PG_RE_THROW();
1446  }
1447  PG_END_TRY();
1448 
1449  MemoryContextSwitchTo(oldContext);
1450 
1451  /* Mark portal not active */
1452  portal->status = PORTAL_READY;
1453 
1454  ActivePortal = saveActivePortal;
1455  CurrentResourceOwner = saveResourceOwner;
1456  PortalContext = savePortalContext;
1457 
1458  return result;
1459 }
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
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:1472
bool run_once
Definition: portal.h:147
MemoryContext PortalContext
Definition: mcxt.c:53
#define ERROR
Definition: elog.h:43
static void FillPortalStore(Portal portal, bool isTopLevel)
Definition: pquery.c:988
PortalStrategy strategy
Definition: portal.h:145
#define AssertArg(condition)
Definition: c.h:748
#define PortalIsValid(p)
Definition: portal.h:203
#define PG_CATCH()
Definition: elog.h:305
#define Assert(condition)
Definition: c.h:746
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:336
ResourceOwner resowner
Definition: portal.h:121
Tuplestorestate * holdStore
Definition: portal.h:168
#define elog(elevel,...)
Definition: elog.h:214
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320

◆ PortalRunMulti()

static void PortalRunMulti ( Portal  portal,
bool  isTopLevel,
bool  setHoldSnapshot,
DestReceiver dest,
DestReceiver altdest,
QueryCompletion qc 
)
static

Definition at line 1186 of file pquery.c.

References Assert, PlannedStmt::canSetTag, CHECK_FOR_INTERRUPTS, CommandCounterIncrement(), QueryCompletion::commandTag, CopyQueryCompletion(), CurrentMemoryContext, DestRemoteExecute, GetTransactionSnapshot(), PortalData::holdSnapshot, IsA, lfirst_node, lnext(), log_executor_stats, MemoryContextDeleteChildren(), _DestReceiver::mydest, None_Receiver, PopActiveSnapshot(), PortalData::portalContext, PortalData::portalParams, PortalRunUtility(), ProcessQuery(), PushCopiedSnapshot(), PortalData::qc, PortalData::queryEnv, RegisterSnapshot(), ResetUsage(), ShowUsage(), PortalData::sourceText, PortalData::stmts, UpdateActiveSnapshotCommandId(), and PlannedStmt::utilityStmt.

Referenced by FillPortalStore(), and PortalRun().

1190 {
1191  bool active_snapshot_set = false;
1192  ListCell *stmtlist_item;
1193 
1194  /*
1195  * If the destination is DestRemoteExecute, change to DestNone. The
1196  * reason is that the client won't be expecting any tuples, and indeed has
1197  * no way to know what they are, since there is no provision for Describe
1198  * to send a RowDescription message when this portal execution strategy is
1199  * in effect. This presently will only affect SELECT commands added to
1200  * non-SELECT queries by rewrite rules: such commands will be executed,
1201  * but the results will be discarded unless you use "simple Query"
1202  * protocol.
1203  */
1204  if (dest->mydest == DestRemoteExecute)
1205  dest = None_Receiver;
1206  if (altdest->mydest == DestRemoteExecute)
1207  altdest = None_Receiver;
1208 
1209  /*
1210  * Loop to handle the individual queries generated from a single parsetree
1211  * by analysis and rewrite.
1212  */
1213  foreach(stmtlist_item, portal->stmts)
1214  {
1215  PlannedStmt *pstmt = lfirst_node(PlannedStmt, stmtlist_item);
1216 
1217  /*
1218  * If we got a cancel signal in prior command, quit
1219  */
1221 
1222  if (pstmt->utilityStmt == NULL)
1223  {
1224  /*
1225  * process a plannable query.
1226  */
1227  TRACE_POSTGRESQL_QUERY_EXECUTE_START();
1228 
1229  if (log_executor_stats)
1230  ResetUsage();
1231 
1232  /*
1233  * Must always have a snapshot for plannable queries. First time
1234  * through, take a new snapshot; for subsequent queries in the
1235  * same portal, just update the snapshot's copy of the command
1236  * counter.
1237  */
1238  if (!active_snapshot_set)
1239  {
1240  Snapshot snapshot = GetTransactionSnapshot();
1241 
1242  /* If told to, register the snapshot and save in portal */
1243  if (setHoldSnapshot)
1244  {
1245  snapshot = RegisterSnapshot(snapshot);
1246  portal->holdSnapshot = snapshot;
1247  }
1248 
1249  /*
1250  * We can't have the holdSnapshot also be the active one,
1251  * because UpdateActiveSnapshotCommandId would complain. So
1252  * force an extra snapshot copy. Plain PushActiveSnapshot
1253  * would have copied the transaction snapshot anyway, so this
1254  * only adds a copy step when setHoldSnapshot is true. (It's
1255  * okay for the command ID of the active snapshot to diverge
1256  * from what holdSnapshot has.)
1257  */
1258  PushCopiedSnapshot(snapshot);
1259  active_snapshot_set = true;
1260  }
1261  else
1263 
1264  if (pstmt->canSetTag)
1265  {
1266  /* statement can set tag string */
1267  ProcessQuery(pstmt,
1268  portal->sourceText,
1269  portal->portalParams,
1270  portal->queryEnv,
1271  dest, qc);
1272  }
1273  else
1274  {
1275  /* stmt added by rewrite cannot set tag */
1276  ProcessQuery(pstmt,
1277  portal->sourceText,
1278  portal->portalParams,
1279  portal->queryEnv,
1280  altdest, NULL);
1281  }
1282 
1283  if (log_executor_stats)
1284  ShowUsage("EXECUTOR STATISTICS");
1285 
1286  TRACE_POSTGRESQL_QUERY_EXECUTE_DONE();
1287  }
1288  else
1289  {
1290  /*
1291  * process utility functions (create, destroy, etc..)
1292  *
1293  * We must not set a snapshot here for utility commands (if one is
1294  * needed, PortalRunUtility will do it). If a utility command is
1295  * alone in a portal then everything's fine. The only case where
1296  * a utility command can be part of a longer list is that rules
1297  * are allowed to include NotifyStmt. NotifyStmt doesn't care
1298  * whether it has a snapshot or not, so we just leave the current
1299  * snapshot alone if we have one.
1300  */
1301  if (pstmt->canSetTag)
1302  {
1303  Assert(!active_snapshot_set);
1304  /* statement can set tag string */
1305  PortalRunUtility(portal, pstmt, isTopLevel, false,
1306  dest, qc);
1307  }
1308  else
1309  {
1310  Assert(IsA(pstmt->utilityStmt, NotifyStmt));
1311  /* stmt added by rewrite cannot set tag */
1312  PortalRunUtility(portal, pstmt, isTopLevel, false,
1313  altdest, NULL);
1314  }
1315  }
1316 
1317  /*
1318  * Increment command counter between queries, but not after the last
1319  * one.
1320  */
1321  if (lnext(portal->stmts, stmtlist_item) != NULL)
1323 
1324  /*
1325  * Clear subsidiary contexts to recover temporary memory.
1326  */
1328 
1330  }
1331 
1332  /* Pop the snapshot if we pushed one. */
1333  if (active_snapshot_set)
1335 
1336  /*
1337  * If a query completion data was supplied, use it. Otherwise use the
1338  * portal's query completion data.
1339  *
1340  * Exception: Clients expect INSERT/UPDATE/DELETE tags to have counts, so
1341  * fake them with zeros. This can happen with DO INSTEAD rules if there
1342  * is no replacement query of the same type as the original. We print "0
1343  * 0" here because technically there is no query of the matching tag type,
1344  * and printing a non-zero count for a different query type seems wrong,
1345  * e.g. an INSERT that does an UPDATE instead should not print "0 1" if
1346  * one row was updated. See QueryRewrite(), step 3, for details.
1347  */
1348  if (qc && qc->commandTag == CMDTAG_UNKNOWN)
1349  {
1350  if (portal->qc.commandTag != CMDTAG_UNKNOWN)
1351  CopyQueryCompletion(qc, &portal->qc);
1352  /* If the caller supplied a qc, we should have set it by now. */
1353  Assert(qc->commandTag != CMDTAG_UNKNOWN);
1354  }
1355 }
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:728
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:310
void ShowUsage(const char *title)
Definition: postgres.c:4612
CommandDest mydest
Definition: dest.h:129
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
List * stmts
Definition: portal.h:138
DestReceiver * None_Receiver
Definition: dest.c:96
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
MemoryContext portalContext
Definition: portal.h:120
static void PortalRunUtility(Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:1115
void ResetUsage(void)
Definition: postgres.c:4605
ParamListInfo portalParams
Definition: portal.h:141
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:716
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Node * utilityStmt
Definition: plannodes.h:86
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:257
bool canSetTag
Definition: plannodes.h:54
void CommandCounterIncrement(void)
Definition: xact.c:1021
const char * sourceText
Definition: portal.h:135
CommandTag commandTag
Definition: cmdtag.h:30
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition: cmdtag.h:44
QueryCompletion qc
Definition: portal.h:137
#define Assert(condition)
Definition: c.h:746
Snapshot holdSnapshot
Definition: portal.h:179
QueryEnvironment * queryEnv
Definition: portal.h:142
bool log_executor_stats
Definition: guc.c:521
static void ProcessQuery(PlannedStmt *plan, const char *sourceText, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: pquery.c:136
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99

◆ PortalRunSelect()

static uint64 PortalRunSelect ( Portal  portal,
bool  forward,
long  count,
DestReceiver dest 
)
static

Definition at line 855 of file pquery.c.

References Assert, PortalData::atEnd, PortalData::atStart, BackwardScanDirection, CURSOR_OPT_NO_SCROLL, PortalData::cursorOptions, QueryDesc::dest, generate_unaccent_rules::dest, ereport, errcode(), errhint(), errmsg(), ERROR, EState::es_processed, QueryDesc::estate, ExecutorRun(), FETCH_ALL, ForwardScanDirection, PortalData::holdStore, NoMovementScanDirection, PopActiveSnapshot(), PortalData::portalPos, PushActiveSnapshot(), PortalData::queryDesc, PortalData::run_once, RunFromStore(), ScanDirectionIsNoMovement, and QueryDesc::snapshot.

Referenced by DoPortalRunFetch(), and PortalRun().

859 {
860  QueryDesc *queryDesc;
861  ScanDirection direction;
862  uint64 nprocessed;
863 
864  /*
865  * NB: queryDesc will be NULL if we are fetching from a held cursor or a
866  * completed utility query; can't use it in that path.
867  */
868  queryDesc = portal->queryDesc;
869 
870  /* Caller messed up if we have neither a ready query nor held data. */
871  Assert(queryDesc || portal->holdStore);
872 
873  /*
874  * Force the queryDesc destination to the right thing. This supports
875  * MOVE, for example, which will pass in dest = DestNone. This is okay to
876  * change as long as we do it on every fetch. (The Executor must not
877  * assume that dest never changes.)
878  */
879  if (queryDesc)
880  queryDesc->dest = dest;
881 
882  /*
883  * Determine which direction to go in, and check to see if we're already
884  * at the end of the available tuples in that direction. If so, set the
885  * direction to NoMovement to avoid trying to fetch any tuples. (This
886  * check exists because not all plan node types are robust about being
887  * called again if they've already returned NULL once.) Then call the
888  * executor (we must not skip this, because the destination needs to see a
889  * setup and shutdown even if no tuples are available). Finally, update
890  * the portal position state depending on the number of tuples that were
891  * retrieved.
892  */
893  if (forward)
894  {
895  if (portal->atEnd || count <= 0)
896  {
897  direction = NoMovementScanDirection;
898  count = 0; /* don't pass negative count to executor */
899  }
900  else
901  direction = ForwardScanDirection;
902 
903  /* In the executor, zero count processes all rows */
904  if (count == FETCH_ALL)
905  count = 0;
906 
907  if (portal->holdStore)
908  nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
909  else
910  {
911  PushActiveSnapshot(queryDesc->snapshot);
912  ExecutorRun(queryDesc, direction, (uint64) count,
913  portal->run_once);
914  nprocessed = queryDesc->estate->es_processed;
916  }
917 
918  if (!ScanDirectionIsNoMovement(direction))
919  {
920  if (nprocessed > 0)
921  portal->atStart = false; /* OK to go backward now */
922  if (count == 0 || nprocessed < (uint64) count)
923  portal->atEnd = true; /* we retrieved 'em all */
924  portal->portalPos += nprocessed;
925  }
926  }
927  else
928  {
929  if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
930  ereport(ERROR,
931  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
932  errmsg("cursor can only scan forward"),
933  errhint("Declare it with SCROLL option to enable backward scan.")));
934 
935  if (portal->atStart || count <= 0)
936  {
937  direction = NoMovementScanDirection;
938  count = 0; /* don't pass negative count to executor */
939  }
940  else
941  direction = BackwardScanDirection;
942 
943  /* In the executor, zero count processes all rows */
944  if (count == FETCH_ALL)
945  count = 0;
946 
947  if (portal->holdStore)
948  nprocessed = RunFromStore(portal, direction, (uint64) count, dest);
949  else
950  {
951  PushActiveSnapshot(queryDesc->snapshot);
952  ExecutorRun(queryDesc, direction, (uint64) count,
953  portal->run_once);
954  nprocessed = queryDesc->estate->es_processed;
956  }
957 
958  if (!ScanDirectionIsNoMovement(direction))
959  {
960  if (nprocessed > 0 && portal->atEnd)
961  {
962  portal->atEnd = false; /* OK to go forward now */
963  portal->portalPos++; /* adjust for endpoint case */
964  }
965  if (count == 0 || nprocessed < (uint64) count)
966  {
967  portal->atStart = true; /* we retrieved 'em all */
968  portal->portalPos = 0;
969  }
970  else
971  {
972  portal->portalPos -= nprocessed;
973  }
974  }
975  }
976 
977  return nprocessed;
978 }
static uint64 RunFromStore(Portal portal, ScanDirection direction, uint64 count, DestReceiver *dest)
Definition: pquery.c:1049
int errhint(const char *fmt,...)
Definition: elog.c:1068
bool atEnd
Definition: portal.h:191
EState * estate
Definition: execdesc.h:48
int errcode(int sqlerrcode)
Definition: elog.c:610
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:2714
Snapshot snapshot
Definition: execdesc.h:39
bool run_once
Definition: portal.h:147
#define ERROR
Definition: elog.h:43
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
ScanDirection
Definition: sdir.h:22
QueryDesc * queryDesc
Definition: portal.h:156
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
uint64 es_processed
Definition: execnodes.h:563
DestReceiver * dest
Definition: execdesc.h:41
bool atStart
Definition: portal.h:190
Tuplestorestate * holdStore
Definition: portal.h:168
int errmsg(const char *fmt,...)
Definition: elog.c:821
int cursorOptions
Definition: portal.h:146
uint64 portalPos
Definition: portal.h:192
#define FETCH_ALL
Definition: parsenodes.h:2756

◆ PortalRunUtility()

static void PortalRunUtility ( Portal  portal,
PlannedStmt pstmt,
bool  isTopLevel,
bool  setHoldSnapshot,
DestReceiver dest,
QueryCompletion qc 
)
static

Definition at line 1115 of file pquery.c.

References ActiveSnapshotSet(), GetActiveSnapshot(), GetTransactionSnapshot(), PortalData::holdSnapshot, IsA, MemoryContextSwitchTo(), PopActiveSnapshot(), PortalData::portalContext, PortalData::portalParams, PROCESS_UTILITY_QUERY, PROCESS_UTILITY_TOPLEVEL, ProcessUtility(), PushActiveSnapshot(), PortalData::queryEnv, RegisterSnapshot(), PortalData::sourceText, and PlannedStmt::utilityStmt.

Referenced by FillPortalStore(), and PortalRunMulti().

1118 {
1119  Node *utilityStmt = pstmt->utilityStmt;
1120  Snapshot snapshot;
1121 
1122  /*
1123  * Set snapshot if utility stmt needs one. Most reliable way to do this
1124  * seems to be to enumerate those that do not need one; this is a short
1125  * list. Transaction control, LOCK, and SET must *not* set a snapshot
1126  * since they need to be executable at the start of a transaction-snapshot
1127  * mode transaction without freezing a snapshot. By extension we allow
1128  * SHOW not to set a snapshot. The other stmts listed are just efficiency
1129  * hacks. Beware of listing anything that can modify the database --- if,
1130  * say, it has to update an index with expressions that invoke
1131  * user-defined functions, then it had better have a snapshot.
1132  */
1133  if (!(IsA(utilityStmt, TransactionStmt) ||
1134  IsA(utilityStmt, LockStmt) ||
1135  IsA(utilityStmt, VariableSetStmt) ||
1136  IsA(utilityStmt, VariableShowStmt) ||
1137  IsA(utilityStmt, ConstraintsSetStmt) ||
1138  /* efficiency hacks from here down */
1139  IsA(utilityStmt, FetchStmt) ||
1140  IsA(utilityStmt, ListenStmt) ||
1141  IsA(utilityStmt, NotifyStmt) ||
1142  IsA(utilityStmt, UnlistenStmt) ||
1143  IsA(utilityStmt, CheckPointStmt)))
1144  {
1145  snapshot = GetTransactionSnapshot();
1146  /* If told to, register the snapshot we're using and save in portal */
1147  if (setHoldSnapshot)
1148  {
1149  snapshot = RegisterSnapshot(snapshot);
1150  portal->holdSnapshot = snapshot;
1151  }
1152  PushActiveSnapshot(snapshot);
1153  /* PushActiveSnapshot might have copied the snapshot */
1154  snapshot = GetActiveSnapshot();
1155  }
1156  else
1157  snapshot = NULL;
1158 
1159  ProcessUtility(pstmt,
1160  portal->sourceText,
1162  portal->portalParams,
1163  portal->queryEnv,
1164  dest,
1165  qc);
1166 
1167  /* Some utility statements may change context on us */
1169 
1170  /*
1171  * Some utility commands may pop the ActiveSnapshot stack from under us,
1172  * so be careful to only pop the stack if our snapshot is still at the
1173  * top.
1174  */
1175  if (snapshot != NULL && ActiveSnapshotSet() &&
1176  snapshot == GetActiveSnapshot())
1178 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
Definition: nodes.h:528
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
MemoryContext portalContext
Definition: portal.h:120
ParamListInfo portalParams
Definition: portal.h:141
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
Node * utilityStmt
Definition: plannodes.h:86
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:798
const char * sourceText
Definition: portal.h:135
Snapshot holdSnapshot
Definition: portal.h:179
QueryEnvironment * queryEnv
Definition: portal.h:142
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition: utility.c:501

◆ PortalSetResultFormat()

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

Definition at line 611 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().

612 {
613  int natts;
614  int i;
615 
616  /* Do nothing if portal won't return tuples */
617  if (portal->tupDesc == NULL)
618  return;
619  natts = portal->tupDesc->natts;
620  portal->formats = (int16 *)
622  natts * sizeof(int16));
623  if (nFormats > 1)
624  {
625  /* format specified for each column */
626  if (nFormats != natts)
627  ereport(ERROR,
628  (errcode(ERRCODE_PROTOCOL_VIOLATION),
629  errmsg("bind message has %d result formats but query has %d columns",
630  nFormats, natts)));
631  memcpy(portal->formats, formats, natts * sizeof(int16));
632  }
633  else if (nFormats > 0)
634  {
635  /* single format specified, use for all columns */
636  int16 format1 = formats[0];
637 
638  for (i = 0; i < natts; i++)
639  portal->formats[i] = format1;
640  }
641  else
642  {
643  /* use default format for all columns */
644  for (i = 0; i < natts; i++)
645  portal->formats[i] = 0;
646  }
647 }
signed short int16
Definition: c.h:362
int errcode(int sqlerrcode)
Definition: elog.c:610
MemoryContext portalContext
Definition: portal.h:120
#define ERROR
Definition: elog.h:43
int16 * formats
Definition: portal.h:161
TupleDesc tupDesc
Definition: portal.h:159
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:821
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
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  * Create QueryDesc in portal's context; for the moment, set
481  * the destination to DestNone.
482  */
483  queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts),
484  portal->sourceText,
488  params,
489  portal->queryEnv,
490  0);
491 
492  /*
493  * If it's a scrollable cursor, executor needs to support
494  * REWIND and backwards scan, as well as whatever the caller
495  * might've asked for.
496  */
497  if (portal->cursorOptions & CURSOR_OPT_SCROLL)
498  myeflags = eflags | EXEC_FLAG_REWIND | EXEC_FLAG_BACKWARD;
499  else
500  myeflags = eflags;
501 
502  /*
503  * Call ExecutorStart to prepare the plan for execution
504  */
505  ExecutorStart(queryDesc, myeflags);
506 
507  /*
508  * This tells PortalCleanup to shut down the executor
509  */
510  portal->queryDesc = queryDesc;
511 
512  /*
513  * Remember tuple descriptor (computed by ExecutorStart)
514  */
515  portal->tupDesc = queryDesc->tupDesc;
516 
517  /*
518  * Reset cursor position data to "start of query"
519  */
520  portal->atStart = true;
521  portal->atEnd = false; /* allow fetches */
522  portal->portalPos = 0;
523 
525  break;
526 
528  case PORTAL_ONE_MOD_WITH:
529 
530  /*
531  * We don't start the executor until we are told to run the
532  * portal. We do need to set up the result tupdesc.
533  */
534  {
535  PlannedStmt *pstmt;
536 
537  pstmt = PortalGetPrimaryStmt(portal);
538  portal->tupDesc =
540  }
541 
542  /*
543  * Reset cursor position data to "start of query"
544  */
545  portal->atStart = true;
546  portal->atEnd = false; /* allow fetches */
547  portal->portalPos = 0;
548  break;
549 
550  case PORTAL_UTIL_SELECT:
551 
552  /*
553  * We don't set snapshot here, because PortalRunUtility will
554  * take care of it if needed.
555  */
556  {
557  PlannedStmt *pstmt = PortalGetPrimaryStmt(portal);
558 
559  Assert(pstmt->commandType == CMD_UTILITY);
560  portal->tupDesc = UtilityTupleDescriptor(pstmt->utilityStmt);
561  }
562 
563  /*
564  * Reset cursor position data to "start of query"
565  */
566  portal->atStart = true;
567  portal->atEnd = false; /* allow fetches */
568  portal->portalPos = 0;
569  break;
570 
571  case PORTAL_MULTI_QUERY:
572  /* Need do nothing now */
573  portal->tupDesc = NULL;
574  break;
575  }
576  }
577  PG_CATCH();
578  {
579  /* Uncaught error while executing portal: mark it dead */
580  MarkPortalFailed(portal);
581 
582  /* Restore global vars and propagate error */
583  ActivePortal = saveActivePortal;
584  CurrentResourceOwner = saveResourceOwner;
585  PortalContext = savePortalContext;
586 
587  PG_RE_THROW();
588  }
589  PG_END_TRY();
590 
591  MemoryContextSwitchTo(oldContext);
592 
593  ActivePortal = saveActivePortal;
594  CurrentResourceOwner = saveResourceOwner;
595  PortalContext = savePortalContext;
596 
597  portal->status = PORTAL_READY;
598 }
#define AssertState(condition)
Definition: c.h:749
bool atEnd
Definition: portal.h:191
TupleDesc ExecCleanTypeFromTL(List *targetList)
Definition: execTuples.c:1920
Portal ActivePortal
Definition: pquery.c:35
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
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:53
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:748
QueryDesc * queryDesc
Definition: portal.h:156
TupleDesc tupDesc
Definition: execdesc.h:47
#define InvalidSnapshot
Definition: snapshot.h:123
#define PortalIsValid(p)
Definition: portal.h:203
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:305
#define Assert(condition)
Definition: c.h:746
void MarkPortalFailed(Portal portal)
Definition: portalmem.c:441
PortalStatus status
Definition: portal.h:150
#define PG_RE_THROW()
Definition: elog.h:336
QueryEnvironment * queryEnv
Definition: portal.h:142
PortalStrategy ChoosePortalStrategy(List *stmts)
Definition: pquery.c:206
List * targetlist
Definition: plannodes.h:136
ResourceOwner resowner
Definition: portal.h:121
bool atStart
Definition: portal.h:190
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:2713
int cursorOptions
Definition: portal.h:146
#define PG_TRY()
Definition: elog.h:295
TupleDesc UtilityTupleDescriptor(Node *parsetree)
Definition: utility.c:2016
#define PG_END_TRY()
Definition: elog.h:320
uint64 portalPos
Definition: portal.h:192

◆ ProcessQuery()

static void ProcessQuery ( PlannedStmt plan,
const char *  sourceText,
ParamListInfo  params,
QueryEnvironment queryEnv,
DestReceiver dest,
QueryCompletion qc 
)
static

Definition at line 136 of file pquery.c.

References CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, CreateQueryDesc(), EState::es_processed, QueryDesc::estate, ExecutorEnd(), ExecutorFinish(), ExecutorRun(), ExecutorStart(), ForwardScanDirection, FreeQueryDesc(), GetActiveSnapshot(), InvalidSnapshot, QueryDesc::operation, and SetQueryCompletion().

Referenced by PortalRunMulti().

142 {
143  QueryDesc *queryDesc;
144 
145  /*
146  * Create the QueryDesc object
147  */
148  queryDesc = CreateQueryDesc(plan, sourceText,
150  dest, params, queryEnv, 0);
151 
152  /*
153  * Call ExecutorStart to prepare the plan for execution
154  */
155  ExecutorStart(queryDesc, 0);
156 
157  /*
158  * Run the plan to completion.
159  */
160  ExecutorRun(queryDesc, ForwardScanDirection, 0L, true);
161 
162  /*
163  * Build command completion status data, if caller wants one.
164  */
165  if (qc)
166  {
167  switch (queryDesc->operation)
168  {
169  case CMD_SELECT:
170  SetQueryCompletion(qc, CMDTAG_SELECT, queryDesc->estate->es_processed);
171  break;
172  case CMD_INSERT:
173  SetQueryCompletion(qc, CMDTAG_INSERT, queryDesc->estate->es_processed);
174  break;
175  case CMD_UPDATE:
176  SetQueryCompletion(qc, CMDTAG_UPDATE, queryDesc->estate->es_processed);
177  break;
178  case CMD_DELETE:
179  SetQueryCompletion(qc, CMDTAG_DELETE, queryDesc->estate->es_processed);
180  break;
181  default:
182  SetQueryCompletion(qc, CMDTAG_UNKNOWN, queryDesc->estate->es_processed);
183  break;
184  }
185  }
186 
187  /*
188  * Now, we close down all the scans and free allocated resources.
189  */
190  ExecutorFinish(queryDesc);
191  ExecutorEnd(queryDesc);
192 
193  FreeQueryDesc(queryDesc);
194 }
EState * estate
Definition: execdesc.h:48
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:301
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
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:402
CmdType operation
Definition: execdesc.h:36
#define InvalidSnapshot
Definition: snapshot.h:123
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition: cmdtag.h:36
uint64 es_processed
Definition: execnodes.h:563

◆ RunFromStore()

static uint64 RunFromStore ( Portal  portal,
ScanDirection  direction,
uint64  count,
DestReceiver dest 
)
static

Definition at line 1049 of file pquery.c.

References CMD_SELECT, ExecClearTuple(), ExecDropSingleTupleTableSlot(), PortalData::holdContext, PortalData::holdStore, MakeSingleTupleTableSlot(), MemoryContextSwitchTo(), _DestReceiver::receiveSlot, _DestReceiver::rShutdown, _DestReceiver::rStartup, ScanDirectionIsForward, ScanDirectionIsNoMovement, TTSOpsMinimalTuple, PortalData::tupDesc, and tuplestore_gettupleslot().

Referenced by PortalRunSelect().

1051 {
1052  uint64 current_tuple_count = 0;
1053  TupleTableSlot *slot;
1054 
1056 
1057  dest->rStartup(dest, CMD_SELECT, portal->tupDesc);
1058 
1059  if (ScanDirectionIsNoMovement(direction))
1060  {
1061  /* do nothing except start/stop the destination */
1062  }
1063  else
1064  {
1065  bool forward = ScanDirectionIsForward(direction);
1066 
1067  for (;;)
1068  {
1069  MemoryContext oldcontext;
1070  bool ok;
1071 
1072  oldcontext = MemoryContextSwitchTo(portal->holdContext);
1073 
1074  ok = tuplestore_gettupleslot(portal->holdStore, forward, false,
1075  slot);
1076 
1077  MemoryContextSwitchTo(oldcontext);
1078 
1079  if (!ok)
1080  break;
1081 
1082  /*
1083  * If we are not able to send the tuple, we assume the destination
1084  * has closed and no more tuples can be sent. If that's the case,
1085  * end the loop.
1086  */
1087  if (!dest->receiveSlot(slot, dest))
1088  break;
1089 
1090  ExecClearTuple(slot);
1091 
1092  /*
1093  * check our tuple count.. if we've processed the proper number
1094  * then quit, else loop again and process more tuples. Zero count
1095  * means no limit.
1096  */
1097  current_tuple_count++;
1098  if (count && count == current_tuple_count)
1099  break;
1100  }
1101  }
1102 
1103  dest->rShutdown(dest);
1104 
1106 
1107  return current_tuple_count;
1108 }
bool(* receiveSlot)(TupleTableSlot *slot, DestReceiver *self)
Definition: dest.h:119
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define ScanDirectionIsForward(direction)
Definition: sdir.h:55
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext holdContext
Definition: portal.h:169
#define ScanDirectionIsNoMovement(direction)
Definition: sdir.h:48
void(* rStartup)(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: dest.h:122
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
TupleDesc tupDesc
Definition: portal.h:159
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
void(* rShutdown)(DestReceiver *self)
Definition: dest.h:125
Tuplestorestate * holdStore
Definition: portal.h:168
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85

Variable Documentation

◆ ActivePortal

Portal ActivePortal = NULL