PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pquery.c File Reference
#include "postgres.h"
#include <limits.h>
#include "access/xact.h"
#include "commands/prepare.h"
#include "executor/executor.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, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
 
uint64 PortalRunFetch (Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
 
bool PlannedStmtRequiresSnapshot (PlannedStmt *pstmt)
 
void EnsurePortalSnapshotExists (void)
 

Variables

Portal ActivePortal = NULL
 

Function Documentation

◆ ChoosePortalStrategy()

PortalStrategy ChoosePortalStrategy ( List stmts)

Definition at line 206 of file pquery.c.

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 {
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 {
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)
310
311 /* Else, it's the general case... */
312 return PORTAL_MULTI_QUERY;
313}
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define stmt
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define nodeTag(nodeptr)
Definition nodes.h:139
@ CMD_UTILITY
Definition nodes.h:280
@ CMD_SELECT
Definition nodes.h:275
#define lfirst(lc)
Definition pg_list.h:172
static int list_length(const List *l)
Definition pg_list.h:152
#define NIL
Definition pg_list.h:68
#define linitial(l)
Definition pg_list.h:178
@ PORTAL_ONE_RETURNING
Definition portal.h:92
@ PORTAL_MULTI_QUERY
Definition portal.h:95
@ PORTAL_ONE_SELECT
Definition portal.h:91
@ PORTAL_ONE_MOD_WITH
Definition portal.h:93
@ PORTAL_UTIL_SELECT
Definition portal.h:94
static int fb(int x)
Definition nodes.h:135
bool hasModifyingCTE
Definition plannodes.h:81
bool canSetTag
Definition plannodes.h:84
bool hasReturning
Definition plannodes.h:78
CmdType commandType
Definition plannodes.h:66
Node * utilityStmt
Definition plannodes.h:153
List * returningList
Definition parsenodes.h:217
CmdType commandType
Definition parsenodes.h:121
Node * utilityStmt
Definition parsenodes.h:141
bool UtilityReturnsTuples(Node *parsetree)
Definition utility.c:2041

References PlannedStmt::canSetTag, CMD_SELECT, CMD_UTILITY, Query::commandType, PlannedStmt::commandType, elog, ERROR, fb(), PlannedStmt::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, stmt, UtilityReturnsTuples(), Query::utilityStmt, and PlannedStmt::utilityStmt.

Referenced by PlanCacheComputeResultDesc(), and PortalStart().

◆ 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 68 of file pquery.c.

76{
78
79 qd->operation = plannedstmt->commandType; /* operation */
80 qd->plannedstmt = plannedstmt; /* plan */
81 qd->sourceText = sourceText; /* query text */
82 qd->snapshot = RegisterSnapshot(snapshot); /* snapshot */
83 /* RI check snapshot */
84 qd->crosscheck_snapshot = RegisterSnapshot(crosscheck_snapshot);
85 qd->dest = dest; /* output dest */
86 qd->params = params; /* parameter values passed into query */
87 qd->queryEnv = queryEnv;
88 qd->instrument_options = instrument_options; /* instrumentation wanted? */
89 qd->query_instr_options = 0;
90
91 /* null these fields until set by ExecutorStart */
92 qd->tupDesc = NULL;
93 qd->estate = NULL;
94 qd->planstate = NULL;
95 qd->query_instr = NULL;
96
97 /* not yet executed */
98 qd->already_executed = false;
99
100 return qd;
101}
#define palloc_object(type)
Definition fe_memutils.h:74
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:824
const char * sourceText
Definition execdesc.h:38
ParamListInfo params
Definition execdesc.h:42
DestReceiver * dest
Definition execdesc.h:41
int instrument_options
Definition execdesc.h:44
EState * estate
Definition execdesc.h:50
CmdType operation
Definition execdesc.h:36
Snapshot snapshot
Definition execdesc.h:39
bool already_executed
Definition execdesc.h:54
PlannedStmt * plannedstmt
Definition execdesc.h:37
int query_instr_options
Definition execdesc.h:45
QueryEnvironment * queryEnv
Definition execdesc.h:43
struct Instrumentation * query_instr
Definition execdesc.h:57
TupleDesc tupDesc
Definition execdesc.h:49
Snapshot crosscheck_snapshot
Definition execdesc.h:40
PlanState * planstate
Definition execdesc.h:51

References QueryDesc::already_executed, PlannedStmt::commandType, QueryDesc::crosscheck_snapshot, QueryDesc::dest, QueryDesc::estate, fb(), QueryDesc::instrument_options, QueryDesc::operation, palloc_object, QueryDesc::params, QueryDesc::plannedstmt, QueryDesc::planstate, QueryDesc::query_instr, QueryDesc::query_instr_options, QueryDesc::queryEnv, RegisterSnapshot(), QueryDesc::snapshot, QueryDesc::sourceText, and QueryDesc::tupDesc.

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

◆ DoPortalRewind()

static void DoPortalRewind ( Portal  portal)
static

Definition at line 1666 of file pquery.c.

1667{
1668 QueryDesc *queryDesc;
1669
1670 /*
1671 * No work is needed if we've not advanced nor attempted to advance the
1672 * cursor (and we don't want to throw a NO SCROLL error in this case).
1673 */
1674 if (portal->atStart && !portal->atEnd)
1675 return;
1676
1677 /* Otherwise, cursor must allow scrolling */
1678 if (portal->cursorOptions & CURSOR_OPT_NO_SCROLL)
1679 ereport(ERROR,
1681 errmsg("cursor can only scan forward"),
1682 errhint("Declare it with SCROLL option to enable backward scan.")));
1683
1684 /* Rewind holdStore, if we have one */
1685 if (portal->holdStore)
1686 {
1687 MemoryContext oldcontext;
1688
1689 oldcontext = MemoryContextSwitchTo(portal->holdContext);
1691 MemoryContextSwitchTo(oldcontext);
1692 }
1693
1694 /* Rewind executor, if active */
1695 queryDesc = portal->queryDesc;
1696 if (queryDesc)
1697 {
1698 PushActiveSnapshot(queryDesc->snapshot);
1699 ExecutorRewind(queryDesc);
1701 }
1702
1703 portal->atStart = true;
1704 portal->atEnd = false;
1705 portal->portalPos = 0;
1706}
int errcode(int sqlerrcode)
Definition elog.c:874
int errhint(const char *fmt,...) pg_attribute_printf(1
#define ereport(elevel,...)
Definition elog.h:152
void ExecutorRewind(QueryDesc *queryDesc)
Definition execMain.c:547
static char * errmsg
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
#define CURSOR_OPT_NO_SCROLL
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
void PopActiveSnapshot(void)
Definition snapmgr.c:775
uint64 portalPos
Definition portal.h:200
QueryDesc * queryDesc
Definition portal.h:156
bool atEnd
Definition portal.h:199
bool atStart
Definition portal.h:198
MemoryContext holdContext
Definition portal.h:177
Tuplestorestate * holdStore
Definition portal.h:176
int cursorOptions
Definition portal.h:147
void tuplestore_rescan(Tuplestorestate *state)

References PortalData::atEnd, PortalData::atStart, CURSOR_OPT_NO_SCROLL, PortalData::cursorOptions, ereport, errcode(), errhint(), errmsg, ERROR, ExecutorRewind(), fb(), PortalData::holdContext, PortalData::holdStore, MemoryContextSwitchTo(), PopActiveSnapshot(), PortalData::portalPos, PushActiveSnapshot(), PortalData::queryDesc, QueryDesc::snapshot, and tuplestore_rescan().

Referenced by DoPortalRunFetch().

◆ DoPortalRunFetch()

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

Definition at line 1472 of file pquery.c.

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

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

Referenced by PortalRunFetch().

◆ EnsurePortalSnapshotExists()

void EnsurePortalSnapshotExists ( void  )

Definition at line 1761 of file pquery.c.

1762{
1763 Portal portal;
1764
1765 /*
1766 * Nothing to do if a snapshot is set. (We take it on faith that the
1767 * outermost active snapshot belongs to some Portal; or if there is no
1768 * Portal, it's somebody else's responsibility to manage things.)
1769 */
1770 if (ActiveSnapshotSet())
1771 return;
1772
1773 /* Otherwise, we'd better have an active Portal */
1774 portal = ActivePortal;
1775 if (unlikely(portal == NULL))
1776 elog(ERROR, "cannot execute SQL without an outer snapshot or portal");
1777 Assert(portal->portalSnapshot == NULL);
1778
1779 /*
1780 * Create a new snapshot, make it active, and remember it in portal.
1781 * Because the portal now references the snapshot, we must tell snapmgr.c
1782 * that the snapshot belongs to the portal's transaction level, else we
1783 * risk portalSnapshot becoming a dangling pointer.
1784 */
1786 /* PushActiveSnapshotWithLevel might have copied the snapshot */
1788}
#define unlikely(x)
Definition c.h:438
Portal ActivePortal
Definition pquery.c:36
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
bool ActiveSnapshotSet(void)
Definition snapmgr.c:812
void PushActiveSnapshotWithLevel(Snapshot snapshot, int snap_level)
Definition snapmgr.c:696
Snapshot GetActiveSnapshot(void)
Definition snapmgr.c:800
Snapshot portalSnapshot
Definition portal.h:169
int createLevel
Definition portal.h:133

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

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

◆ FetchPortalTargetList()

List * FetchPortalTargetList ( Portal  portal)

Definition at line 323 of file pquery.c.

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}
PlannedStmt * PortalGetPrimaryStmt(Portal portal)
Definition portalmem.c:153
List * FetchStatementTargetList(Node *stmt)
Definition pquery.c:345

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

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

◆ FetchStatementTargetList()

List * FetchStatementTargetList ( Node stmt)

Definition at line 345 of file pquery.c.

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 {
389
390 Assert(!fstmt->ismove);
391 subportal = GetPortalByName(fstmt->portalname);
394 }
395 if (IsA(stmt, ExecuteStmt))
396 {
398 PreparedStatement *entry;
399
400 entry = FetchPreparedStatement(estmt->name, true);
402 }
403 return NIL;
404}
PreparedStatement * FetchPreparedStatement(const char *stmt_name, bool throwError)
Definition prepare.c:436
List * FetchPreparedStatementTargetList(PreparedStatement *stmt)
Definition prepare.c:491
#define PortalIsValid(p)
Definition portal.h:211
Portal GetPortalByName(const char *name)
Definition portalmem.c:132
List * FetchPortalTargetList(Portal portal)
Definition pquery.c:323
List * targetlist
Definition plannodes.h:235
struct Plan * planTree
Definition plannodes.h:99
List * targetList
Definition parsenodes.h:201

References Assert, CMD_SELECT, CMD_UTILITY, Query::commandType, PlannedStmt::commandType, fb(), FetchPortalTargetList(), FetchPreparedStatement(), FetchPreparedStatementTargetList(), GetPortalByName(), PlannedStmt::hasReturning, IsA, NIL, PlannedStmt::planTree, PortalIsValid, Query::returningList, stmt, Query::targetList, Plan::targetlist, Query::utilityStmt, and PlannedStmt::utilityStmt.

Referenced by CachedPlanGetTargetList(), and FetchPortalTargetList().

◆ FillPortalStore()

static void FillPortalStore ( Portal  portal,
bool  isTopLevel 
)
static

Definition at line 991 of file pquery.c.

992{
995
997 PortalCreateHoldStore(portal);
1000 portal->holdStore,
1001 portal->holdContext,
1002 false,
1003 NULL,
1004 NULL);
1005
1006 switch (portal->strategy)
1007 {
1010
1011 /*
1012 * Run the portal to completion just as for the default
1013 * PORTAL_MULTI_QUERY case, but send the primary query's output to
1014 * the tuplestore. Auxiliary query outputs are discarded. Set the
1015 * portal's holdSnapshot to the snapshot used (or a copy of it).
1016 */
1017 PortalRunMulti(portal, isTopLevel, true,
1018 treceiver, None_Receiver, &qc);
1019 break;
1020
1021 case PORTAL_UTIL_SELECT:
1023 isTopLevel, true, treceiver, &qc);
1024 break;
1025
1026 default:
1027 elog(ERROR, "unsupported portal strategy: %d",
1028 (int) portal->strategy);
1029 break;
1030 }
1031
1032 /* Override portal completion data with actual command results */
1033 if (qc.commandTag != CMDTAG_UNKNOWN)
1034 CopyQueryCompletion(&portal->qc, &qc);
1035
1036 treceiver->rDestroy(treceiver);
1037}
void InitializeQueryCompletion(QueryCompletion *qc)
Definition cmdtag.c:40
static void CopyQueryCompletion(QueryCompletion *dst, const QueryCompletion *src)
Definition cmdtag.h:45
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition dest.c:113
@ DestTuplestore
Definition dest.h:93
#define linitial_node(type, l)
Definition pg_list.h:181
void PortalCreateHoldStore(Portal portal)
Definition portalmem.c:332
static void PortalRunMulti(Portal portal, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition pquery.c:1182
static void PortalRunUtility(Portal portal, PlannedStmt *pstmt, bool isTopLevel, bool setHoldSnapshot, DestReceiver *dest, QueryCompletion *qc)
Definition pquery.c:1118
List * stmts
Definition portal.h:139
QueryCompletion qc
Definition portal.h:138
CommandTag commandTag
Definition cmdtag.h:31
void SetTuplestoreDestReceiverParams(DestReceiver *self, Tuplestorestate *tStore, MemoryContext tContext, bool detoast, TupleDesc target_tupdesc, const char *map_failure_msg)

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

Referenced by PortalRun(), and PortalRunFetch().

◆ FreeQueryDesc()

void FreeQueryDesc ( QueryDesc qdesc)

Definition at line 107 of file pquery.c.

108{
109 /* Can't be a live query */
110 Assert(qdesc->estate == NULL);
111
112 /* forget our snapshots */
113 UnregisterSnapshot(qdesc->snapshot);
114 UnregisterSnapshot(qdesc->crosscheck_snapshot);
115
116 /* Only the QueryDesc itself need be freed */
117 pfree(qdesc);
118}
void pfree(void *pointer)
Definition mcxt.c:1616
void UnregisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:866

References Assert, fb(), pfree(), and UnregisterSnapshot().

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

◆ PlannedStmtRequiresSnapshot()

bool PlannedStmtRequiresSnapshot ( PlannedStmt pstmt)

Definition at line 1712 of file pquery.c.

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

References fb(), IsA, and PlannedStmt::utilityStmt.

Referenced by _SPI_execute_plan(), and PortalRunUtility().

◆ PortalRun()

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

Definition at line 681 of file pquery.c.

684{
685 bool result;
686 uint64 nprocessed;
693
694 Assert(PortalIsValid(portal));
695
697
698 /* Initialize empty completion data */
699 if (qc)
701
703 {
704 elog(DEBUG3, "PortalRun");
705 /* PORTAL_MULTI_QUERY logs its own stats per query */
706 ResetUsage();
707 }
708
709 /*
710 * Check for improper portal use, and mark portal active.
711 */
712 MarkPortalActive(portal);
713
714 /*
715 * Set up global portal context pointers.
716 *
717 * We have to play a special game here to support utility commands like
718 * VACUUM and CLUSTER, which internally start and commit transactions.
719 * When we are called to execute such a command, CurrentResourceOwner will
720 * be pointing to the TopTransactionResourceOwner --- which will be
721 * destroyed and replaced in the course of the internal commit and
722 * restart. So we need to be prepared to restore it as pointing to the
723 * exit-time TopTransactionResourceOwner. (Ain't that ugly? This idea of
724 * internally starting whole new transactions is not good.)
725 * CurrentMemoryContext has a similar problem, but the other pointers we
726 * save here will be NULL or pointing to longer-lived objects.
727 */
734 PG_TRY();
735 {
736 ActivePortal = portal;
737 if (portal->resowner)
740
742
743 switch (portal->strategy)
744 {
749
750 /*
751 * If we have not yet run the command, do so, storing its
752 * results in the portal's tuplestore. But we don't do that
753 * for the PORTAL_ONE_SELECT case.
754 */
755 if (portal->strategy != PORTAL_ONE_SELECT && !portal->holdStore)
757
758 /*
759 * Now fetch desired portion of results.
760 */
761 nprocessed = PortalRunSelect(portal, true, count, dest);
762
763 /*
764 * If the portal result contains a command tag and the caller
765 * gave us a pointer to store it, copy it and update the
766 * rowcount.
767 */
768 if (qc && portal->qc.commandTag != CMDTAG_UNKNOWN)
769 {
770 CopyQueryCompletion(qc, &portal->qc);
771 qc->nprocessed = nprocessed;
772 }
773
774 /* Mark portal not active */
775 portal->status = PORTAL_READY;
776
777 /*
778 * Since it's a forward fetch, say DONE iff atEnd is now true.
779 */
780 result = portal->atEnd;
781 break;
782
784 PortalRunMulti(portal, isTopLevel, false,
785 dest, altdest, qc);
786
787 /* Prevent portal's commands from being re-executed */
788 MarkPortalDone(portal);
789
790 /* Always complete at end of RunMulti */
791 result = true;
792 break;
793
794 default:
795 elog(ERROR, "unrecognized portal strategy: %d",
796 (int) portal->strategy);
797 result = false; /* keep compiler quiet */
798 break;
799 }
800 }
801 PG_CATCH();
802 {
803 /* Uncaught error while executing portal: mark it dead */
804 MarkPortalFailed(portal);
805
806 /* Restore global vars and propagate error */
809 else
814 else
817
818 PG_RE_THROW();
819 }
820 PG_END_TRY();
821
824 else
829 else
832
834 ShowUsage("EXECUTOR STATISTICS");
835
837
838 return result;
839}
#define PG_RE_THROW()
Definition elog.h:407
#define DEBUG3
Definition elog.h:29
#define PG_TRY(...)
Definition elog.h:374
#define PG_END_TRY(...)
Definition elog.h:399
#define PG_CATCH(...)
Definition elog.h:384
bool log_executor_stats
Definition guc_tables.c:550
MemoryContext TopTransactionContext
Definition mcxt.c:171
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
MemoryContext PortalContext
Definition mcxt.c:175
@ PORTAL_READY
Definition portal.h:107
void MarkPortalDone(Portal portal)
Definition portalmem.c:415
void MarkPortalFailed(Portal portal)
Definition portalmem.c:443
void MarkPortalActive(Portal portal)
Definition portalmem.c:396
void ShowUsage(const char *title)
Definition postgres.c:5137
void ResetUsage(void)
Definition postgres.c:5130
static void FillPortalStore(Portal portal, bool isTopLevel)
Definition pquery.c:991
ResourceOwner TopTransactionResourceOwner
Definition resowner.c:175
ResourceOwner CurrentResourceOwner
Definition resowner.c:173
ResourceOwner resowner
Definition portal.h:121
MemoryContext portalContext
Definition portal.h:120
PortalStatus status
Definition portal.h:150
uint64 nprocessed
Definition cmdtag.h:32

References ActivePortal, Assert, PortalData::atEnd, QueryCompletion::commandTag, CopyQueryCompletion(), CurrentMemoryContext, CurrentResourceOwner, DEBUG3, elog, ERROR, fb(), 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, result, ShowUsage(), PortalData::status, PortalData::strategy, TopTransactionContext, and TopTransactionResourceOwner.

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

◆ PortalRunFetch()

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

Definition at line 1374 of file pquery.c.

1378{
1379 uint64 result;
1384
1385 Assert(PortalIsValid(portal));
1386
1387 /*
1388 * Check for improper portal use, and mark portal active.
1389 */
1390 MarkPortalActive(portal);
1391
1392 /*
1393 * Set up global portal context pointers.
1394 */
1398 PG_TRY();
1399 {
1400 ActivePortal = portal;
1401 if (portal->resowner)
1403 PortalContext = portal->portalContext;
1404
1406
1407 switch (portal->strategy)
1408 {
1409 case PORTAL_ONE_SELECT:
1410 result = DoPortalRunFetch(portal, fdirection, count, dest);
1411 break;
1412
1415 case PORTAL_UTIL_SELECT:
1416
1417 /*
1418 * If we have not yet run the command, do so, storing its
1419 * results in the portal's tuplestore.
1420 */
1421 if (!portal->holdStore)
1422 FillPortalStore(portal, false /* isTopLevel */ );
1423
1424 /*
1425 * Now fetch desired portion of results.
1426 */
1427 result = DoPortalRunFetch(portal, fdirection, count, dest);
1428 break;
1429
1430 default:
1431 elog(ERROR, "unsupported portal strategy");
1432 result = 0; /* keep compiler quiet */
1433 break;
1434 }
1435 }
1436 PG_CATCH();
1437 {
1438 /* Uncaught error while executing portal: mark it dead */
1439 MarkPortalFailed(portal);
1440
1441 /* Restore global vars and propagate error */
1445
1446 PG_RE_THROW();
1447 }
1448 PG_END_TRY();
1449
1451
1452 /* Mark portal not active */
1453 portal->status = PORTAL_READY;
1454
1458
1459 return result;
1460}
static uint64 DoPortalRunFetch(Portal portal, FetchDirection fdirection, long count, DestReceiver *dest)
Definition pquery.c:1472

References ActivePortal, Assert, CurrentResourceOwner, DoPortalRunFetch(), elog, ERROR, fb(), 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, result, PortalData::status, and PortalData::strategy.

Referenced by _SPI_cursor_operation(), and PerformPortalFetch().

◆ PortalRunMulti()

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

Definition at line 1182 of file pquery.c.

1186{
1187 bool active_snapshot_set = false;
1189
1190 /*
1191 * If the destination is DestRemoteExecute, change to DestNone. The
1192 * reason is that the client won't be expecting any tuples, and indeed has
1193 * no way to know what they are, since there is no provision for Describe
1194 * to send a RowDescription message when this portal execution strategy is
1195 * in effect. This presently will only affect SELECT commands added to
1196 * non-SELECT queries by rewrite rules: such commands will be executed,
1197 * but the results will be discarded unless you use "simple Query"
1198 * protocol.
1199 */
1200 if (dest->mydest == DestRemoteExecute)
1202 if (altdest->mydest == DestRemoteExecute)
1204
1205 /*
1206 * Loop to handle the individual queries generated from a single parsetree
1207 * by analysis and rewrite.
1208 */
1209 foreach(stmtlist_item, portal->stmts)
1210 {
1212
1213 /*
1214 * If we got a cancel signal in prior command, quit
1215 */
1217
1218 if (pstmt->utilityStmt == NULL)
1219 {
1220 /*
1221 * process a plannable query.
1222 */
1224
1226 ResetUsage();
1227
1228 /*
1229 * Must always have a snapshot for plannable queries. First time
1230 * through, take a new snapshot; for subsequent queries in the
1231 * same portal, just update the snapshot's copy of the command
1232 * counter.
1233 */
1235 {
1236 Snapshot snapshot = GetTransactionSnapshot();
1237
1238 /* If told to, register the snapshot and save in portal */
1239 if (setHoldSnapshot)
1240 {
1241 snapshot = RegisterSnapshot(snapshot);
1242 portal->holdSnapshot = snapshot;
1243 }
1244
1245 /*
1246 * We can't have the holdSnapshot also be the active one,
1247 * because UpdateActiveSnapshotCommandId would complain. So
1248 * force an extra snapshot copy. Plain PushActiveSnapshot
1249 * would have copied the transaction snapshot anyway, so this
1250 * only adds a copy step when setHoldSnapshot is true. (It's
1251 * okay for the command ID of the active snapshot to diverge
1252 * from what holdSnapshot has.)
1253 */
1254 PushCopiedSnapshot(snapshot);
1255
1256 /*
1257 * As for PORTAL_ONE_SELECT portals, it does not seem
1258 * necessary to maintain portal->portalSnapshot here.
1259 */
1260
1261 active_snapshot_set = true;
1262 }
1263 else
1265
1266 if (pstmt->canSetTag)
1267 {
1268 /* statement can set tag string */
1269 ProcessQuery(pstmt,
1270 portal->sourceText,
1271 portal->portalParams,
1272 portal->queryEnv,
1273 dest, qc);
1274 }
1275 else
1276 {
1277 /* stmt added by rewrite cannot set tag */
1278 ProcessQuery(pstmt,
1279 portal->sourceText,
1280 portal->portalParams,
1281 portal->queryEnv,
1282 altdest, NULL);
1283 }
1284
1286 ShowUsage("EXECUTOR STATISTICS");
1287
1289 }
1290 else
1291 {
1292 /*
1293 * process utility functions (create, destroy, etc..)
1294 *
1295 * We must not set a snapshot here for utility commands (if one is
1296 * needed, PortalRunUtility will do it). If a utility command is
1297 * alone in a portal then everything's fine. The only case where
1298 * a utility command can be part of a longer list is that rules
1299 * are allowed to include NotifyStmt. NotifyStmt doesn't care
1300 * whether it has a snapshot or not, so we just leave the current
1301 * snapshot alone if we have one.
1302 */
1303 if (pstmt->canSetTag)
1304 {
1306 /* statement can set tag string */
1307 PortalRunUtility(portal, pstmt, isTopLevel, false,
1308 dest, qc);
1309 }
1310 else
1311 {
1312 Assert(IsA(pstmt->utilityStmt, NotifyStmt));
1313 /* stmt added by rewrite cannot set tag */
1314 PortalRunUtility(portal, pstmt, isTopLevel, false,
1315 altdest, NULL);
1316 }
1317 }
1318
1319 /*
1320 * Clear subsidiary contexts to recover temporary memory.
1321 */
1323
1325
1326 /*
1327 * Avoid crashing if portal->stmts has been reset. This can only
1328 * occur if a CALL or DO utility statement executed an internal
1329 * COMMIT/ROLLBACK (cf PortalReleaseCachedPlan). The CALL or DO must
1330 * have been the only statement in the portal, so there's nothing left
1331 * for us to do; but we don't want to dereference a now-dangling list
1332 * pointer.
1333 */
1334 if (portal->stmts == NIL)
1335 break;
1336
1337 /*
1338 * Increment command counter between queries, but not after the last
1339 * one.
1340 */
1341 if (lnext(portal->stmts, stmtlist_item) != NULL)
1343 }
1344
1345 /* Pop the snapshot if we pushed one. */
1348
1349 /*
1350 * If a command tag was requested and we did not fill in a run-time-
1351 * determined tag above, copy the parse-time tag from the Portal. (There
1352 * might not be any tag there either, in edge cases such as empty prepared
1353 * statements. That's OK.)
1354 */
1355 if (qc &&
1356 qc->commandTag == CMDTAG_UNKNOWN &&
1357 portal->qc.commandTag != CMDTAG_UNKNOWN)
1358 CopyQueryCompletion(qc, &portal->qc);
1359}
@ DestRemoteExecute
Definition dest.h:90
void MemoryContextDeleteChildren(MemoryContext context)
Definition mcxt.c:555
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
#define lfirst_node(type, lc)
Definition pg_list.h:176
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:375
static void ProcessQuery(PlannedStmt *plan, const char *sourceText, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition pquery.c:138
void UpdateActiveSnapshotCommandId(void)
Definition snapmgr.c:744
void PushCopiedSnapshot(Snapshot snapshot)
Definition snapmgr.c:732
const char * sourceText
Definition portal.h:136
QueryEnvironment * queryEnv
Definition portal.h:143
ParamListInfo portalParams
Definition portal.h:142
Snapshot holdSnapshot
Definition portal.h:187
void CommandCounterIncrement(void)
Definition xact.c:1130

References Assert, PlannedStmt::canSetTag, CHECK_FOR_INTERRUPTS, CommandCounterIncrement(), QueryCompletion::commandTag, CopyQueryCompletion(), CurrentMemoryContext, DestRemoteExecute, fb(), GetTransactionSnapshot(), PortalData::holdSnapshot, IsA, lfirst_node, lnext(), log_executor_stats, MemoryContextDeleteChildren(), NIL, 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().

◆ PortalRunSelect()

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

Definition at line 860 of file pquery.c.

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

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

Referenced by DoPortalRunFetch(), and PortalRun().

◆ PortalRunUtility()

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

Definition at line 1118 of file pquery.c.

1121{
1122 /*
1123 * Set snapshot if utility stmt needs one.
1124 */
1125 if (PlannedStmtRequiresSnapshot(pstmt))
1126 {
1127 Snapshot snapshot = GetTransactionSnapshot();
1128
1129 /* If told to, register the snapshot we're using and save in portal */
1130 if (setHoldSnapshot)
1131 {
1132 snapshot = RegisterSnapshot(snapshot);
1133 portal->holdSnapshot = snapshot;
1134 }
1135
1136 /*
1137 * In any case, make the snapshot active and remember it in portal.
1138 * Because the portal now references the snapshot, we must tell
1139 * snapmgr.c that the snapshot belongs to the portal's transaction
1140 * level, else we risk portalSnapshot becoming a dangling pointer.
1141 */
1142 PushActiveSnapshotWithLevel(snapshot, portal->createLevel);
1143 /* PushActiveSnapshotWithLevel might have copied the snapshot */
1145 }
1146 else
1147 portal->portalSnapshot = NULL;
1148
1149 ProcessUtility(pstmt,
1150 portal->sourceText,
1151 (portal->cplan != NULL), /* protect tree if in plancache */
1153 portal->portalParams,
1154 portal->queryEnv,
1155 dest,
1156 qc);
1157
1158 /* Some utility statements may change context on us */
1160
1161 /*
1162 * Some utility commands (e.g., VACUUM, WAIT FOR) pop the ActiveSnapshot
1163 * stack from under us, so don't complain if it's now empty. Otherwise,
1164 * our snapshot should be the top one; pop it. Note that this could be a
1165 * different snapshot from the one we made above; see
1166 * EnsurePortalSnapshotExists.
1167 */
1168 if (portal->portalSnapshot != NULL && ActiveSnapshotSet())
1169 {
1172 }
1173 portal->portalSnapshot = NULL;
1174}
bool PlannedStmtRequiresSnapshot(PlannedStmt *pstmt)
Definition pquery.c:1712
CachedPlan * cplan
Definition portal.h:140
void ProcessUtility(PlannedStmt *pstmt, const char *queryString, bool readOnlyTree, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc)
Definition utility.c:504
@ PROCESS_UTILITY_TOPLEVEL
Definition utility.h:22
@ PROCESS_UTILITY_QUERY
Definition utility.h:23

References ActiveSnapshotSet(), Assert, PortalData::cplan, PortalData::createLevel, fb(), GetActiveSnapshot(), GetTransactionSnapshot(), PortalData::holdSnapshot, MemoryContextSwitchTo(), PlannedStmtRequiresSnapshot(), PopActiveSnapshot(), PortalData::portalContext, PortalData::portalParams, PortalData::portalSnapshot, PROCESS_UTILITY_QUERY, PROCESS_UTILITY_TOPLEVEL, ProcessUtility(), PushActiveSnapshotWithLevel(), PortalData::queryEnv, RegisterSnapshot(), and PortalData::sourceText.

Referenced by FillPortalStore(), and PortalRunMulti().

◆ PortalSetResultFormat()

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

Definition at line 620 of file pquery.c.

621{
622 int natts;
623 int i;
624
625 /* Do nothing if portal won't return tuples */
626 if (portal->tupDesc == NULL)
627 return;
628 natts = portal->tupDesc->natts;
629 portal->formats = (int16 *)
631 natts * sizeof(int16));
632 if (nFormats > 1)
633 {
634 /* format specified for each column */
635 if (nFormats != natts)
638 errmsg("bind message has %d result formats but query has %d columns",
639 nFormats, natts)));
640 memcpy(portal->formats, formats, natts * sizeof(int16));
641 }
642 else if (nFormats > 0)
643 {
644 /* single format specified, use for all columns */
645 int16 format1 = formats[0];
646
647 for (i = 0; i < natts; i++)
648 portal->formats[i] = format1;
649 }
650 else
651 {
652 /* use default format for all columns */
653 for (i = 0; i < natts; i++)
654 portal->formats[i] = 0;
655 }
656}
int16_t int16
Definition c.h:619
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define ERRCODE_PROTOCOL_VIOLATION
Definition fe-connect.c:96
int i
Definition isn.c:77
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
int16 * formats
Definition portal.h:161
TupleDesc tupDesc
Definition portal.h:159

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

Referenced by exec_bind_message(), and exec_simple_query().

◆ PortalStart()

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

Definition at line 430 of file pquery.c.

432{
437 QueryDesc *queryDesc;
438 int myeflags;
439
440 Assert(PortalIsValid(portal));
441 Assert(portal->status == PORTAL_DEFINED);
442
443 /*
444 * Set up global portal context pointers.
445 */
449 PG_TRY();
450 {
451 ActivePortal = portal;
452 if (portal->resowner)
455
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 {
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. Since
484 * we don't do that, there's also no need to force a
485 * non-default nesting level for the snapshot.
486 */
487
488 /*
489 * Create QueryDesc in portal's context; for the moment, set
490 * the destination to DestNone.
491 */
492 queryDesc = CreateQueryDesc(linitial_node(PlannedStmt, portal->stmts),
493 portal->sourceText,
497 params,
498 portal->queryEnv,
499 0);
500
501 /*
502 * If it's a scrollable cursor, executor needs to support
503 * REWIND and backwards scan, as well as whatever the caller
504 * might've asked for.
505 */
506 if (portal->cursorOptions & CURSOR_OPT_SCROLL)
508 else
509 myeflags = eflags;
510
511 /*
512 * Call ExecutorStart to prepare the plan for execution
513 */
514 ExecutorStart(queryDesc, myeflags);
515
516 /*
517 * This tells PortalCleanup to shut down the executor
518 */
519 portal->queryDesc = queryDesc;
520
521 /*
522 * Remember tuple descriptor (computed by ExecutorStart)
523 */
524 portal->tupDesc = queryDesc->tupDesc;
525
526 /*
527 * Reset cursor position data to "start of query"
528 */
529 portal->atStart = true;
530 portal->atEnd = false; /* allow fetches */
531 portal->portalPos = 0;
532
534 break;
535
538
539 /*
540 * We don't start the executor until we are told to run the
541 * portal. We do need to set up the result tupdesc.
542 */
543 {
544 PlannedStmt *pstmt;
545
546 pstmt = PortalGetPrimaryStmt(portal);
547 portal->tupDesc =
549 }
550
551 /*
552 * Reset cursor position data to "start of query"
553 */
554 portal->atStart = true;
555 portal->atEnd = false; /* allow fetches */
556 portal->portalPos = 0;
557 break;
558
560
561 /*
562 * We don't set snapshot here, because PortalRunUtility will
563 * take care of it if needed.
564 */
565 {
566 PlannedStmt *pstmt = PortalGetPrimaryStmt(portal);
567
568 Assert(pstmt->commandType == CMD_UTILITY);
570 }
571
572 /*
573 * Reset cursor position data to "start of query"
574 */
575 portal->atStart = true;
576 portal->atEnd = false; /* allow fetches */
577 portal->portalPos = 0;
578 break;
579
581 /* Need do nothing now */
582 portal->tupDesc = NULL;
583 break;
584 }
585 }
586 PG_CATCH();
587 {
588 /* Uncaught error while executing portal: mark it dead */
589 MarkPortalFailed(portal);
590
591 /* Restore global vars and propagate error */
595
596 PG_RE_THROW();
597 }
598 PG_END_TRY();
599
601
605
606 portal->status = PORTAL_READY;
607}
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition execMain.c:124
TupleDesc ExecCleanTypeFromTL(List *targetList)
#define EXEC_FLAG_BACKWARD
Definition executor.h:70
#define EXEC_FLAG_REWIND
Definition executor.h:69
#define CURSOR_OPT_SCROLL
@ PORTAL_DEFINED
Definition portal.h:106
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition pquery.c:68
PortalStrategy ChoosePortalStrategy(List *stmts)
Definition pquery.c:206
#define InvalidSnapshot
Definition snapshot.h:119
TupleDesc UtilityTupleDescriptor(Node *parsetree)
Definition utility.c:2100

References ActivePortal, Assert, PortalData::atEnd, PortalData::atStart, ChoosePortalStrategy(), CMD_UTILITY, PlannedStmt::commandType, CreateQueryDesc(), CurrentResourceOwner, CURSOR_OPT_SCROLL, PortalData::cursorOptions, EXEC_FLAG_BACKWARD, EXEC_FLAG_REWIND, ExecCleanTypeFromTL(), ExecutorStart(), fb(), 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().

◆ ProcessQuery()

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

Definition at line 138 of file pquery.c.

144{
145 QueryDesc *queryDesc;
146
147 /*
148 * Create the QueryDesc object
149 */
150 queryDesc = CreateQueryDesc(plan, sourceText,
152 dest, params, queryEnv, 0);
153
154 /*
155 * Call ExecutorStart to prepare the plan for execution
156 */
157 ExecutorStart(queryDesc, 0);
158
159 /*
160 * Run the plan to completion.
161 */
162 ExecutorRun(queryDesc, ForwardScanDirection, 0);
163
164 /*
165 * Build command completion status data, if caller wants one.
166 */
167 if (qc)
168 {
169 CommandTag tag;
170
171 if (queryDesc->operation == CMD_SELECT)
172 tag = CMDTAG_SELECT;
173 else if (queryDesc->operation == CMD_INSERT)
174 tag = CMDTAG_INSERT;
175 else if (queryDesc->operation == CMD_UPDATE)
176 tag = CMDTAG_UPDATE;
177 else if (queryDesc->operation == CMD_DELETE)
178 tag = CMDTAG_DELETE;
179 else if (queryDesc->operation == CMD_MERGE)
180 tag = CMDTAG_MERGE;
181 else
182 tag = CMDTAG_UNKNOWN;
183
184 SetQueryCompletion(qc, tag, queryDesc->estate->es_processed);
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}
static void SetQueryCompletion(QueryCompletion *qc, CommandTag commandTag, uint64 nprocessed)
Definition cmdtag.h:37
CommandTag
Definition cmdtag.h:23
void ExecutorEnd(QueryDesc *queryDesc)
Definition execMain.c:477
void ExecutorFinish(QueryDesc *queryDesc)
Definition execMain.c:417
@ CMD_MERGE
Definition nodes.h:279
@ CMD_INSERT
Definition nodes.h:277
@ CMD_DELETE
Definition nodes.h:278
@ CMD_UPDATE
Definition nodes.h:276
#define plan(x)
Definition pg_regress.c:164
void FreeQueryDesc(QueryDesc *qdesc)
Definition pquery.c:107

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

Referenced by PortalRunMulti().

◆ RunFromStore()

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

Definition at line 1052 of file pquery.c.

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

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

Referenced by PortalRunSelect().

Variable Documentation

◆ ActivePortal