Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * portalmem.c
4 : : * backend portal memory management
5 : : *
6 : : * Portals are objects representing the execution state of a query.
7 : : * This module provides memory management services for portals, but it
8 : : * doesn't actually run the executor for them.
9 : : *
10 : : *
11 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
12 : : * Portions Copyright (c) 1994, Regents of the University of California
13 : : *
14 : : * IDENTIFICATION
15 : : * src/backend/utils/mmgr/portalmem.c
16 : : *
17 : : *-------------------------------------------------------------------------
18 : : */
19 : : #include "postgres.h"
20 : :
21 : : #include "access/xact.h"
22 : : #include "commands/portalcmds.h"
23 : : #include "funcapi.h"
24 : : #include "miscadmin.h"
25 : : #include "storage/ipc.h"
26 : : #include "utils/builtins.h"
27 : : #include "utils/hsearch.h"
28 : : #include "utils/memutils.h"
29 : : #include "utils/snapmgr.h"
30 : : #include "utils/timestamp.h"
31 : : #include "utils/tuplestore.h"
32 : :
33 : : /*
34 : : * Estimate of the maximum number of open portals a user would have,
35 : : * used in initially sizing the PortalHashTable in EnablePortalManager().
36 : : * Since the hash table can expand, there's no need to make this overly
37 : : * generous, and keeping it small avoids unnecessary overhead in the
38 : : * hash_seq_search() calls executed during transaction end.
39 : : */
40 : : #define PORTALS_PER_USER 16
41 : :
42 : :
43 : : /* ----------------
44 : : * Global state
45 : : * ----------------
46 : : */
47 : :
48 : : #define MAX_PORTALNAME_LEN NAMEDATALEN
49 : :
50 : : typedef struct portalhashent
51 : : {
52 : : char portalname[MAX_PORTALNAME_LEN];
53 : : Portal portal;
54 : : } PortalHashEnt;
55 : :
56 : : static HTAB *PortalHashTable = NULL;
57 : :
58 : : #define PortalHashTableLookup(NAME, PORTAL) \
59 : : do { \
60 : : PortalHashEnt *hentry; \
61 : : \
62 : : hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
63 : : (NAME), HASH_FIND, NULL); \
64 : : if (hentry) \
65 : : PORTAL = hentry->portal; \
66 : : else \
67 : : PORTAL = NULL; \
68 : : } while(0)
69 : :
70 : : #define PortalHashTableInsert(PORTAL, NAME) \
71 : : do { \
72 : : PortalHashEnt *hentry; bool found; \
73 : : \
74 : : hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
75 : : (NAME), HASH_ENTER, &found); \
76 : : if (found) \
77 : : elog(ERROR, "duplicate portal name"); \
78 : : hentry->portal = PORTAL; \
79 : : /* To avoid duplicate storage, make PORTAL->name point to htab entry */ \
80 : : PORTAL->name = hentry->portalname; \
81 : : } while(0)
82 : :
83 : : #define PortalHashTableDelete(PORTAL) \
84 : : do { \
85 : : PortalHashEnt *hentry; \
86 : : \
87 : : hentry = (PortalHashEnt *) hash_search(PortalHashTable, \
88 : : PORTAL->name, HASH_REMOVE, NULL); \
89 : : if (hentry == NULL) \
90 : : elog(WARNING, "trying to delete portal name that does not exist"); \
91 : : } while(0)
92 : :
93 : : static MemoryContext TopPortalContext = NULL;
94 : :
95 : :
96 : : /* ----------------------------------------------------------------
97 : : * public portal interface functions
98 : : * ----------------------------------------------------------------
99 : : */
100 : :
101 : : /*
102 : : * EnablePortalManager
103 : : * Enables the portal management module at backend startup.
104 : : */
105 : : void
106 : 22085 : EnablePortalManager(void)
107 : : {
108 : : HASHCTL ctl;
109 : :
110 : : Assert(TopPortalContext == NULL);
111 : :
112 : 22085 : TopPortalContext = AllocSetContextCreate(TopMemoryContext,
113 : : "TopPortalContext",
114 : : ALLOCSET_DEFAULT_SIZES);
115 : :
116 : 22085 : ctl.keysize = MAX_PORTALNAME_LEN;
117 : 22085 : ctl.entrysize = sizeof(PortalHashEnt);
118 : :
119 : : /*
120 : : * use PORTALS_PER_USER as a guess of how many hash table entries to
121 : : * create, initially
122 : : */
123 : 22085 : PortalHashTable = hash_create("Portal hash", PORTALS_PER_USER,
124 : : &ctl, HASH_ELEM | HASH_STRINGS);
125 : 22085 : }
126 : :
127 : : /*
128 : : * GetPortalByName
129 : : * Returns a portal given a portal name, or NULL if name not found.
130 : : */
131 : : Portal
132 : 555163 : GetPortalByName(const char *name)
133 : : {
134 : : Portal portal;
135 : :
136 [ + + ]: 555163 : if (name)
137 [ + + ]: 555162 : PortalHashTableLookup(name, portal);
138 : : else
139 : 1 : portal = NULL;
140 : :
141 : 555163 : return portal;
142 : : }
143 : :
144 : : /*
145 : : * PortalGetPrimaryStmt
146 : : * Get the "primary" stmt within a portal, ie, the one marked canSetTag.
147 : : *
148 : : * Returns NULL if no such stmt. If multiple PlannedStmt structs within the
149 : : * portal are marked canSetTag, returns the first one. Neither of these
150 : : * cases should occur in present usages of this function.
151 : : */
152 : : PlannedStmt *
153 : 239818 : PortalGetPrimaryStmt(Portal portal)
154 : : {
155 : : ListCell *lc;
156 : :
157 [ + - + - : 239818 : foreach(lc, portal->stmts)
+ - ]
158 : : {
159 : 239818 : PlannedStmt *stmt = lfirst_node(PlannedStmt, lc);
160 : :
161 [ + - ]: 239818 : if (stmt->canSetTag)
162 : 239818 : return stmt;
163 : : }
164 : 0 : return NULL;
165 : : }
166 : :
167 : : /*
168 : : * CreatePortal
169 : : * Returns a new portal given a name.
170 : : *
171 : : * allowDup: if true, automatically drop any pre-existing portal of the
172 : : * same name (if false, an error is raised).
173 : : *
174 : : * dupSilent: if true, don't even emit a WARNING.
175 : : */
176 : : Portal
177 : 489447 : CreatePortal(const char *name, bool allowDup, bool dupSilent)
178 : : {
179 : : Portal portal;
180 : :
181 : : Assert(name);
182 : :
183 : 489447 : portal = GetPortalByName(name);
184 [ + + ]: 489447 : if (PortalIsValid(portal))
185 : : {
186 [ - + ]: 7768 : if (!allowDup)
187 [ # # ]: 0 : ereport(ERROR,
188 : : (errcode(ERRCODE_DUPLICATE_CURSOR),
189 : : errmsg("cursor \"%s\" already exists", name)));
190 [ - + ]: 7768 : if (!dupSilent)
191 [ # # ]: 0 : ereport(WARNING,
192 : : (errcode(ERRCODE_DUPLICATE_CURSOR),
193 : : errmsg("closing existing cursor \"%s\"",
194 : : name)));
195 : 7768 : PortalDrop(portal, false);
196 : : }
197 : :
198 : : /* make new portal structure */
199 : 489447 : portal = (Portal) MemoryContextAllocZero(TopPortalContext, sizeof *portal);
200 : :
201 : : /* initialize portal context; typically it won't store much */
202 : 489447 : portal->portalContext = AllocSetContextCreate(TopPortalContext,
203 : : "PortalContext",
204 : : ALLOCSET_SMALL_SIZES);
205 : :
206 : : /* create a resource owner for the portal */
207 : 489447 : portal->resowner = ResourceOwnerCreate(CurTransactionResourceOwner,
208 : : "Portal");
209 : :
210 : : /* initialize portal fields that don't start off zero */
211 : 489447 : portal->status = PORTAL_NEW;
212 : 489447 : portal->cleanup = PortalCleanup;
213 : 489447 : portal->createSubid = GetCurrentSubTransactionId();
214 : 489447 : portal->activeSubid = portal->createSubid;
215 : 489447 : portal->createLevel = GetCurrentTransactionNestLevel();
216 : 489447 : portal->strategy = PORTAL_MULTI_QUERY;
217 : 489447 : portal->cursorOptions = CURSOR_OPT_NO_SCROLL;
218 : 489447 : portal->atStart = true;
219 : 489447 : portal->atEnd = true; /* disallow fetches until query is set */
220 : 489447 : portal->visible = true;
221 : 489447 : portal->creation_time = GetCurrentStatementStartTimestamp();
222 : :
223 : : /* put portal in table (sets portal->name) */
224 [ - + - - ]: 489447 : PortalHashTableInsert(portal, name);
225 : :
226 : : /* for named portals reuse portal->name copy */
227 [ + + ]: 489447 : MemoryContextSetIdentifier(portal->portalContext, portal->name[0] ? portal->name : "<unnamed>");
228 : :
229 : 489447 : return portal;
230 : : }
231 : :
232 : : /*
233 : : * CreateNewPortal
234 : : * Create a new portal, assigning it a random nonconflicting name.
235 : : */
236 : : Portal
237 : 16949 : CreateNewPortal(void)
238 : : {
239 : : static unsigned int unnamed_portal_count = 0;
240 : :
241 : : char portalname[MAX_PORTALNAME_LEN];
242 : :
243 : : /* Select a nonconflicting name */
244 : : for (;;)
245 : : {
246 : 16949 : unnamed_portal_count++;
247 : 16949 : sprintf(portalname, "<unnamed portal %u>", unnamed_portal_count);
248 [ + - ]: 16949 : if (GetPortalByName(portalname) == NULL)
249 : 16949 : break;
250 : : }
251 : :
252 : 16949 : return CreatePortal(portalname, false, false);
253 : : }
254 : :
255 : : /*
256 : : * PortalDefineQuery
257 : : * A simple subroutine to establish a portal's query.
258 : : *
259 : : * Notes: as of PG 8.4, caller MUST supply a sourceText string; it is not
260 : : * allowed anymore to pass NULL. (If you really don't have source text,
261 : : * you can pass a constant string, perhaps "(query not available)".)
262 : : *
263 : : * commandTag shall be NULL if and only if the original query string
264 : : * (before rewriting) was an empty string. Also, the passed commandTag must
265 : : * be a pointer to a constant string, since it is not copied.
266 : : *
267 : : * If cplan is provided, then it is a cached plan containing the stmts, and
268 : : * the caller must have done GetCachedPlan(), causing a refcount increment.
269 : : * The refcount will be released when the portal is destroyed.
270 : : *
271 : : * If cplan is NULL, then it is the caller's responsibility to ensure that
272 : : * the passed plan trees have adequate lifetime. Typically this is done by
273 : : * copying them into the portal's context.
274 : : *
275 : : * The caller is also responsible for ensuring that the passed prepStmtName
276 : : * (if not NULL) and sourceText have adequate lifetime.
277 : : *
278 : : * NB: this function mustn't do much beyond storing the passed values; in
279 : : * particular don't do anything that risks elog(ERROR). If that were to
280 : : * happen here before storing the cplan reference, we'd leak the plancache
281 : : * refcount that the caller is trying to hand off to us.
282 : : */
283 : : void
284 : 489417 : PortalDefineQuery(Portal portal,
285 : : const char *prepStmtName,
286 : : const char *sourceText,
287 : : CommandTag commandTag,
288 : : List *stmts,
289 : : CachedPlan *cplan)
290 : : {
291 : : Assert(PortalIsValid(portal));
292 : : Assert(portal->status == PORTAL_NEW);
293 : :
294 : : Assert(sourceText != NULL);
295 : : Assert(commandTag != CMDTAG_UNKNOWN || stmts == NIL);
296 : :
297 : 489417 : portal->prepStmtName = prepStmtName;
298 : 489417 : portal->sourceText = sourceText;
299 : 489417 : portal->commandTag = commandTag;
300 : 489417 : SetQueryCompletion(&portal->qc, commandTag, 0);
301 : 489417 : portal->stmts = stmts;
302 : 489417 : portal->cplan = cplan;
303 : 489417 : portal->status = PORTAL_DEFINED;
304 : 489417 : }
305 : :
306 : : /*
307 : : * PortalReleaseCachedPlan
308 : : * Release a portal's reference to its cached plan, if any.
309 : : */
310 : : static void
311 : 512660 : PortalReleaseCachedPlan(Portal portal)
312 : : {
313 [ + + ]: 512660 : if (portal->cplan)
314 : : {
315 : 23353 : ReleaseCachedPlan(portal->cplan, NULL);
316 : 23353 : portal->cplan = NULL;
317 : :
318 : : /*
319 : : * We must also clear portal->stmts which is now a dangling reference
320 : : * to the cached plan's plan list. This protects any code that might
321 : : * try to examine the Portal later.
322 : : */
323 : 23353 : portal->stmts = NIL;
324 : : }
325 : 512660 : }
326 : :
327 : : /*
328 : : * PortalCreateHoldStore
329 : : * Create the tuplestore for a portal.
330 : : */
331 : : void
332 : 33102 : PortalCreateHoldStore(Portal portal)
333 : : {
334 : : MemoryContext oldcxt;
335 : :
336 : : Assert(portal->holdContext == NULL);
337 : : Assert(portal->holdStore == NULL);
338 : : Assert(portal->holdSnapshot == NULL);
339 : :
340 : : /*
341 : : * Create the memory context that is used for storage of the tuple set.
342 : : * Note this is NOT a child of the portal's portalContext.
343 : : */
344 : 33102 : portal->holdContext =
345 : 33102 : AllocSetContextCreate(TopPortalContext,
346 : : "PortalHoldContext",
347 : : ALLOCSET_DEFAULT_SIZES);
348 : :
349 : : /*
350 : : * Create the tuple store, selecting cross-transaction temp files, and
351 : : * enabling random access only if cursor requires scrolling.
352 : : *
353 : : * XXX: Should maintenance_work_mem be used for the portal size?
354 : : */
355 : 33102 : oldcxt = MemoryContextSwitchTo(portal->holdContext);
356 : :
357 : 33102 : portal->holdStore =
358 : 33102 : tuplestore_begin_heap(portal->cursorOptions & CURSOR_OPT_SCROLL,
359 : : true, work_mem);
360 : :
361 : 33102 : MemoryContextSwitchTo(oldcxt);
362 : 33102 : }
363 : :
364 : : /*
365 : : * PinPortal
366 : : * Protect a portal from dropping.
367 : : *
368 : : * A pinned portal is still unpinned and dropped at transaction or
369 : : * subtransaction abort.
370 : : */
371 : : void
372 : 8116 : PinPortal(Portal portal)
373 : : {
374 [ - + ]: 8116 : if (portal->portalPinned)
375 [ # # ]: 0 : elog(ERROR, "portal already pinned");
376 : :
377 : 8116 : portal->portalPinned = true;
378 : 8116 : }
379 : :
380 : : void
381 : 8068 : UnpinPortal(Portal portal)
382 : : {
383 [ - + ]: 8068 : if (!portal->portalPinned)
384 [ # # ]: 0 : elog(ERROR, "portal not pinned");
385 : :
386 : 8068 : portal->portalPinned = false;
387 : 8068 : }
388 : :
389 : : /*
390 : : * MarkPortalActive
391 : : * Transition a portal from READY to ACTIVE state.
392 : : *
393 : : * NOTE: never set portal->status = PORTAL_ACTIVE directly; call this instead.
394 : : */
395 : : void
396 : 512495 : MarkPortalActive(Portal portal)
397 : : {
398 : : /* For safety, this is a runtime test not just an Assert */
399 [ + + ]: 512495 : if (portal->status != PORTAL_READY)
400 [ + - ]: 12 : ereport(ERROR,
401 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
402 : : errmsg("portal \"%s\" cannot be run", portal->name)));
403 : : /* Perform the state transition */
404 : 512483 : portal->status = PORTAL_ACTIVE;
405 : 512483 : portal->activeSubid = GetCurrentSubTransactionId();
406 : 512483 : }
407 : :
408 : : /*
409 : : * MarkPortalDone
410 : : * Transition a portal from ACTIVE to DONE state.
411 : : *
412 : : * NOTE: never set portal->status = PORTAL_DONE directly; call this instead.
413 : : */
414 : : void
415 : 250136 : MarkPortalDone(Portal portal)
416 : : {
417 : : /* Perform the state transition */
418 : : Assert(portal->status == PORTAL_ACTIVE);
419 : 250136 : portal->status = PORTAL_DONE;
420 : :
421 : : /*
422 : : * Allow portalcmds.c to clean up the state it knows about. We might as
423 : : * well do that now, since the portal can't be executed any more.
424 : : *
425 : : * In some cases involving execution of a ROLLBACK command in an already
426 : : * aborted transaction, this is necessary, or we'd reach AtCleanup_Portals
427 : : * with the cleanup hook still unexecuted.
428 : : */
429 [ + + ]: 250136 : if (portal->cleanup)
430 : : {
431 : 250095 : portal->cleanup(portal);
432 : 250095 : portal->cleanup = NULL;
433 : : }
434 : 250136 : }
435 : :
436 : : /*
437 : : * MarkPortalFailed
438 : : * Transition a portal into FAILED state.
439 : : *
440 : : * NOTE: never set portal->status = PORTAL_FAILED directly; call this instead.
441 : : */
442 : : void
443 : 22962 : MarkPortalFailed(Portal portal)
444 : : {
445 : : /* Perform the state transition */
446 : : Assert(portal->status != PORTAL_DONE);
447 : 22962 : portal->status = PORTAL_FAILED;
448 : :
449 : : /*
450 : : * Allow portalcmds.c to clean up the state it knows about. We might as
451 : : * well do that now, since the portal can't be executed any more.
452 : : *
453 : : * In some cases involving cleanup of an already aborted transaction, this
454 : : * is necessary, or we'd reach AtCleanup_Portals with the cleanup hook
455 : : * still unexecuted.
456 : : */
457 [ + + ]: 22962 : if (portal->cleanup)
458 : : {
459 : 22919 : portal->cleanup(portal);
460 : 22919 : portal->cleanup = NULL;
461 : : }
462 : 22962 : }
463 : :
464 : : /*
465 : : * PortalDrop
466 : : * Destroy the portal.
467 : : */
468 : : void
469 : 489412 : PortalDrop(Portal portal, bool isTopCommit)
470 : : {
471 : : Assert(PortalIsValid(portal));
472 : :
473 : : /*
474 : : * Don't allow dropping a pinned portal, it's still needed by whoever
475 : : * pinned it.
476 : : */
477 [ - + ]: 489412 : if (portal->portalPinned)
478 [ # # ]: 0 : ereport(ERROR,
479 : : (errcode(ERRCODE_INVALID_CURSOR_STATE),
480 : : errmsg("cannot drop pinned portal \"%s\"", portal->name)));
481 : :
482 : : /*
483 : : * Don't allow dropping a portal being set up.
484 : : */
485 [ + + + + ]: 489412 : if (portal->status == PORTAL_NEW || portal->status == PORTAL_DEFINED)
486 [ + - ]: 8 : ereport(ERROR,
487 : : (errcode(ERRCODE_INVALID_CURSOR_STATE),
488 : : errmsg("cannot drop portal \"%s\" while it is being set up",
489 : : portal->name)));
490 : :
491 : :
492 : : /*
493 : : * Not sure if the PORTAL_ACTIVE case can validly happen or not...
494 : : */
495 [ - + ]: 489404 : if (portal->status == PORTAL_ACTIVE)
496 [ # # ]: 0 : ereport(ERROR,
497 : : (errcode(ERRCODE_INVALID_CURSOR_STATE),
498 : : errmsg("cannot drop active portal \"%s\"", portal->name)));
499 : :
500 : : /*
501 : : * Allow portalcmds.c to clean up the state it knows about, in particular
502 : : * shutting down the executor if still active. This step potentially runs
503 : : * user-defined code so failure has to be expected. It's the cleanup
504 : : * hook's responsibility to not try to do that more than once, in the case
505 : : * that failure occurs and then we come back to drop the portal again
506 : : * during transaction abort.
507 : : *
508 : : * Note: in most paths of control, this will have been done already in
509 : : * MarkPortalDone or MarkPortalFailed. We're just making sure.
510 : : */
511 [ + + ]: 489404 : if (portal->cleanup)
512 : : {
513 : 216303 : portal->cleanup(portal);
514 : 216302 : portal->cleanup = NULL;
515 : : }
516 : :
517 : : /* There shouldn't be an active snapshot anymore, except after error */
518 : : Assert(portal->portalSnapshot == NULL || !isTopCommit);
519 : :
520 : : /*
521 : : * Remove portal from hash table. Because we do this here, we will not
522 : : * come back to try to remove the portal again if there's any error in the
523 : : * subsequent steps. Better to leak a little memory than to get into an
524 : : * infinite error-recovery loop.
525 : : */
526 [ - + - - ]: 489403 : PortalHashTableDelete(portal);
527 : :
528 : : /* drop cached plan reference, if any */
529 : 489403 : PortalReleaseCachedPlan(portal);
530 : :
531 : : /*
532 : : * If portal has a snapshot protecting its data, release that. This needs
533 : : * a little care since the registration will be attached to the portal's
534 : : * resowner; if the portal failed, we will already have released the
535 : : * resowner (and the snapshot) during transaction abort.
536 : : */
537 [ + + ]: 489403 : if (portal->holdSnapshot)
538 : : {
539 [ + + ]: 28581 : if (portal->resowner)
540 : 28120 : UnregisterSnapshotFromOwner(portal->holdSnapshot,
541 : : portal->resowner);
542 : 28581 : portal->holdSnapshot = NULL;
543 : : }
544 : :
545 : : /*
546 : : * Release any resources still attached to the portal. There are several
547 : : * cases being covered here:
548 : : *
549 : : * Top transaction commit (indicated by isTopCommit): normally we should
550 : : * do nothing here and let the regular end-of-transaction resource
551 : : * releasing mechanism handle these resources too. However, if we have a
552 : : * FAILED portal (eg, a cursor that got an error), we'd better clean up
553 : : * its resources to avoid resource-leakage warning messages.
554 : : *
555 : : * Sub transaction commit: never comes here at all, since we don't kill
556 : : * any portals in AtSubCommit_Portals().
557 : : *
558 : : * Main or sub transaction abort: we will do nothing here because
559 : : * portal->resowner was already set NULL; the resources were already
560 : : * cleaned up in transaction abort.
561 : : *
562 : : * Ordinary portal drop: must release resources. However, if the portal
563 : : * is not FAILED then we do not release its locks. The locks become the
564 : : * responsibility of the transaction's ResourceOwner (since it is the
565 : : * parent of the portal's owner) and will be released when the transaction
566 : : * eventually ends.
567 : : */
568 [ + + ]: 489403 : if (portal->resowner &&
569 [ + + - + ]: 459256 : (!isTopCommit || portal->status == PORTAL_FAILED))
570 : : {
571 : 453014 : bool isCommit = (portal->status != PORTAL_FAILED);
572 : :
573 : 453014 : ResourceOwnerRelease(portal->resowner,
574 : : RESOURCE_RELEASE_BEFORE_LOCKS,
575 : : isCommit, false);
576 : 453014 : ResourceOwnerRelease(portal->resowner,
577 : : RESOURCE_RELEASE_LOCKS,
578 : : isCommit, false);
579 : 453014 : ResourceOwnerRelease(portal->resowner,
580 : : RESOURCE_RELEASE_AFTER_LOCKS,
581 : : isCommit, false);
582 : 453014 : ResourceOwnerDelete(portal->resowner);
583 : : }
584 : 489403 : portal->resowner = NULL;
585 : :
586 : : /*
587 : : * Delete tuplestore if present. We should do this even under error
588 : : * conditions; since the tuplestore would have been using cross-
589 : : * transaction storage, its temp files need to be explicitly deleted.
590 : : */
591 [ + + ]: 489403 : if (portal->holdStore)
592 : : {
593 : : MemoryContext oldcontext;
594 : :
595 : 33058 : oldcontext = MemoryContextSwitchTo(portal->holdContext);
596 : 33058 : tuplestore_end(portal->holdStore);
597 : 33058 : MemoryContextSwitchTo(oldcontext);
598 : 33058 : portal->holdStore = NULL;
599 : : }
600 : :
601 : : /* delete tuplestore storage, if any */
602 [ + + ]: 489403 : if (portal->holdContext)
603 : 33058 : MemoryContextDelete(portal->holdContext);
604 : :
605 : : /* release subsidiary storage */
606 : 489403 : MemoryContextDelete(portal->portalContext);
607 : :
608 : : /* release portal struct (it's in TopPortalContext) */
609 : 489403 : pfree(portal);
610 : 489403 : }
611 : :
612 : : /*
613 : : * Delete all declared cursors.
614 : : *
615 : : * Used by commands: CLOSE ALL, DISCARD ALL
616 : : */
617 : : void
618 : 147 : PortalHashTableDeleteAll(void)
619 : : {
620 : : HASH_SEQ_STATUS status;
621 : : PortalHashEnt *hentry;
622 : :
623 [ - + ]: 147 : if (PortalHashTable == NULL)
624 : 0 : return;
625 : :
626 : 147 : hash_seq_init(&status, PortalHashTable);
627 [ + + ]: 345 : while ((hentry = hash_seq_search(&status)) != NULL)
628 : : {
629 : 198 : Portal portal = hentry->portal;
630 : :
631 : : /*
632 : : * Can't close the active portal (the one running the command), or
633 : : * portals being set up.
634 : : */
635 [ + + ]: 198 : if (portal->status == PORTAL_ACTIVE ||
636 [ + + ]: 53 : portal->status == PORTAL_NEW ||
637 [ + + ]: 33 : portal->status == PORTAL_DEFINED)
638 : 181 : continue;
639 : :
640 : 17 : PortalDrop(portal, false);
641 : :
642 : : /* Restart the iteration in case that led to other drops */
643 : 17 : hash_seq_term(&status);
644 : 17 : hash_seq_init(&status, PortalHashTable);
645 : : }
646 : : }
647 : :
648 : : /*
649 : : * Drop portals dependent on the given queryEnv.
650 : : */
651 : : void
652 : 375 : DropQueryEnvPortals(QueryEnvironment *queryEnv)
653 : : {
654 : : HASH_SEQ_STATUS status;
655 : : PortalHashEnt *hentry;
656 : :
657 [ - + ]: 375 : if (PortalHashTable == NULL)
658 : 0 : return;
659 : :
660 : 375 : hash_seq_init(&status, PortalHashTable);
661 [ + + ]: 750 : while ((hentry = hash_seq_search(&status)) != NULL)
662 : : {
663 : 375 : Portal portal = hentry->portal;
664 : :
665 [ + - ]: 375 : if (portal->queryEnv != queryEnv)
666 : 375 : continue;
667 : :
668 : : /*
669 : : * It's safe to unpin and close, because any reference preserved past
670 : : * SPI_finish() must be by name, not a raw pointer.
671 : : */
672 : 0 : portal->portalPinned = false;
673 : :
674 : 0 : PortalDrop(portal, false);
675 : :
676 : : /* Restart the iteration in case that led to other drops */
677 : 0 : hash_seq_term(&status);
678 : 0 : hash_seq_init(&status, PortalHashTable);
679 : : }
680 : : }
681 : :
682 : : /*
683 : : * "Hold" a portal. Prepare it for access by later transactions.
684 : : */
685 : : static void
686 : 118 : HoldPortal(Portal portal)
687 : : {
688 : : /*
689 : : * Note that PersistHoldablePortal() must release all resources used by
690 : : * the portal that are local to the creating transaction.
691 : : */
692 : 118 : PortalCreateHoldStore(portal);
693 : 118 : PersistHoldablePortal(portal);
694 : :
695 : : /* drop cached plan reference, if any */
696 : 116 : PortalReleaseCachedPlan(portal);
697 : :
698 : : /*
699 : : * Any resources belonging to the portal will be released in the upcoming
700 : : * transaction-wide cleanup; the portal will no longer have its own
701 : : * resources.
702 : : */
703 : 116 : portal->resowner = NULL;
704 : :
705 : : /*
706 : : * Having successfully exported the holdable cursor, mark it as not
707 : : * belonging to this transaction.
708 : : */
709 : 116 : portal->createSubid = InvalidSubTransactionId;
710 : 116 : portal->activeSubid = InvalidSubTransactionId;
711 : 116 : portal->createLevel = 0;
712 : 116 : }
713 : :
714 : : /*
715 : : * Pre-commit processing for portals.
716 : : *
717 : : * Holdable cursors created in this transaction need to be converted to
718 : : * materialized form, since we are going to close down the executor and
719 : : * release locks. Non-holdable portals created in this transaction are
720 : : * simply removed. Portals remaining from prior transactions should be
721 : : * left untouched.
722 : : *
723 : : * Returns true if any portals changed state (possibly causing user-defined
724 : : * code to be run), false if not.
725 : : */
726 : : bool
727 : 633137 : PreCommit_Portals(bool isPrepare)
728 : : {
729 : 633137 : bool result = false;
730 : : HASH_SEQ_STATUS status;
731 : : PortalHashEnt *hentry;
732 : :
733 : 633137 : hash_seq_init(&status, PortalHashTable);
734 : :
735 [ + + ]: 678890 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
736 : : {
737 : 45753 : Portal portal = hentry->portal;
738 : :
739 : : /*
740 : : * There should be no pinned portals anymore. Complain if someone
741 : : * leaked one. Auto-held portals are allowed; we assume that whoever
742 : : * pinned them is managing them.
743 : : */
744 [ + + - + ]: 45753 : if (portal->portalPinned && !portal->autoHeld)
745 [ # # ]: 0 : elog(ERROR, "cannot commit while a portal is pinned");
746 : :
747 : : /*
748 : : * Do not touch active portals --- this can only happen in the case of
749 : : * a multi-transaction utility command, such as VACUUM, or a commit in
750 : : * a procedure.
751 : : *
752 : : * Note however that any resource owner attached to such a portal is
753 : : * still going to go away, so don't leave a dangling pointer. Also
754 : : * unregister any snapshots held by the portal, mainly to avoid
755 : : * snapshot leak warnings from ResourceOwnerRelease().
756 : : */
757 [ + + ]: 45753 : if (portal->status == PORTAL_ACTIVE)
758 : : {
759 [ + + ]: 37819 : if (portal->holdSnapshot)
760 : : {
761 [ + - ]: 1 : if (portal->resowner)
762 : 1 : UnregisterSnapshotFromOwner(portal->holdSnapshot,
763 : : portal->resowner);
764 : 1 : portal->holdSnapshot = NULL;
765 : : }
766 : 37819 : portal->resowner = NULL;
767 : : /* Clear portalSnapshot too, for cleanliness */
768 : 37819 : portal->portalSnapshot = NULL;
769 : 37819 : continue;
770 : : }
771 : :
772 : : /* Is it a holdable portal created in the current xact? */
773 [ + + ]: 7934 : if ((portal->cursorOptions & CURSOR_OPT_HOLD) &&
774 [ + + ]: 1607 : portal->createSubid != InvalidSubTransactionId &&
775 [ + - ]: 84 : portal->status == PORTAL_READY)
776 : : {
777 : : /*
778 : : * We are exiting the transaction that created a holdable cursor.
779 : : * Instead of dropping the portal, prepare it for access by later
780 : : * transactions.
781 : : *
782 : : * However, if this is PREPARE TRANSACTION rather than COMMIT,
783 : : * refuse PREPARE, because the semantics seem pretty unclear.
784 : : */
785 [ - + ]: 84 : if (isPrepare)
786 [ # # ]: 0 : ereport(ERROR,
787 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
788 : : errmsg("cannot PREPARE a transaction that has created a cursor WITH HOLD")));
789 : :
790 : 84 : HoldPortal(portal);
791 : :
792 : : /* Report we changed state */
793 : 84 : result = true;
794 : : }
795 [ + + ]: 7850 : else if (portal->createSubid == InvalidSubTransactionId)
796 : : {
797 : : /*
798 : : * Do nothing to cursors held over from a previous transaction
799 : : * (including ones we just froze in a previous cycle of this loop)
800 : : */
801 : 1573 : continue;
802 : : }
803 : : else
804 : : {
805 : : /* Zap all non-holdable portals */
806 : 6277 : PortalDrop(portal, true);
807 : :
808 : : /* Report we changed state */
809 : 6277 : result = true;
810 : : }
811 : :
812 : : /*
813 : : * After either freezing or dropping a portal, we have to restart the
814 : : * iteration, because we could have invoked user-defined code that
815 : : * caused a drop of the next portal in the hash chain.
816 : : */
817 : 6361 : hash_seq_term(&status);
818 : 6361 : hash_seq_init(&status, PortalHashTable);
819 : : }
820 : :
821 : 633137 : return result;
822 : : }
823 : :
824 : : /*
825 : : * Abort processing for portals.
826 : : *
827 : : * At this point we run the cleanup hook if present, but we can't release the
828 : : * portal's memory until the cleanup call.
829 : : */
830 : : void
831 : 37752 : AtAbort_Portals(void)
832 : : {
833 : : HASH_SEQ_STATUS status;
834 : : PortalHashEnt *hentry;
835 : :
836 : 37752 : hash_seq_init(&status, PortalHashTable);
837 : :
838 [ + + ]: 60215 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
839 : : {
840 : 22463 : Portal portal = hentry->portal;
841 : :
842 : : /*
843 : : * When elog(FATAL) is progress, we need to set the active portal to
844 : : * failed, so that PortalCleanup() doesn't run the executor shutdown.
845 : : */
846 [ + + + + ]: 22463 : if (portal->status == PORTAL_ACTIVE && shmem_exit_inprogress)
847 : 5 : MarkPortalFailed(portal);
848 : :
849 : : /*
850 : : * Do nothing else to cursors held over from a previous transaction.
851 : : */
852 [ + + ]: 22463 : if (portal->createSubid == InvalidSubTransactionId)
853 : 252 : continue;
854 : :
855 : : /*
856 : : * Do nothing to auto-held cursors. This is similar to the case of a
857 : : * cursor from a previous transaction, but it could also be that the
858 : : * cursor was auto-held in this transaction, so it wants to live on.
859 : : */
860 [ - + ]: 22211 : if (portal->autoHeld)
861 : 0 : continue;
862 : :
863 : : /*
864 : : * If it was created in the current transaction, we can't do normal
865 : : * shutdown on a READY portal either; it might refer to objects
866 : : * created in the failed transaction. See comments in
867 : : * AtSubAbort_Portals.
868 : : *
869 : : * A portal that was still being set up is also failed here, so that
870 : : * PortalDrop() accepts it later.
871 : : */
872 [ + + ]: 22211 : if (portal->status == PORTAL_NEW ||
873 [ + + ]: 22183 : portal->status == PORTAL_DEFINED ||
874 [ + + ]: 22177 : portal->status == PORTAL_READY)
875 : 706 : MarkPortalFailed(portal);
876 : :
877 : : /*
878 : : * Allow portalcmds.c to clean up the state it knows about, if we
879 : : * haven't already.
880 : : */
881 [ + + ]: 22211 : if (portal->cleanup)
882 : : {
883 : 87 : portal->cleanup(portal);
884 : 87 : portal->cleanup = NULL;
885 : : }
886 : :
887 : : /* drop cached plan reference, if any */
888 : 22211 : PortalReleaseCachedPlan(portal);
889 : :
890 : : /*
891 : : * Any resources belonging to the portal will be released in the
892 : : * upcoming transaction-wide cleanup; they will be gone before we run
893 : : * PortalDrop.
894 : : */
895 : 22211 : portal->resowner = NULL;
896 : :
897 : : /*
898 : : * Although we can't delete the portal data structure proper, we can
899 : : * release any memory in subsidiary contexts, such as executor state.
900 : : * The cleanup hook was the last thing that might have needed data
901 : : * there. But leave active portals alone.
902 : : */
903 [ + + ]: 22211 : if (portal->status != PORTAL_ACTIVE)
904 : 22067 : MemoryContextDeleteChildren(portal->portalContext);
905 : : }
906 : 37752 : }
907 : :
908 : : /*
909 : : * Post-abort cleanup for portals.
910 : : *
911 : : * Delete all portals not held over from prior transactions.
912 : : */
913 : : void
914 : 37733 : AtCleanup_Portals(void)
915 : : {
916 : : HASH_SEQ_STATUS status;
917 : : PortalHashEnt *hentry;
918 : :
919 : 37733 : hash_seq_init(&status, PortalHashTable);
920 : :
921 [ + + ]: 59291 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
922 : : {
923 : 21558 : Portal portal = hentry->portal;
924 : :
925 : : /*
926 : : * Do not touch active portals --- this can only happen in the case of
927 : : * a multi-transaction command.
928 : : */
929 [ + + ]: 21558 : if (portal->status == PORTAL_ACTIVE)
930 : 144 : continue;
931 : :
932 : : /*
933 : : * Do nothing to cursors held over from a previous transaction or
934 : : * auto-held ones.
935 : : */
936 [ + + - + ]: 21414 : if (portal->createSubid == InvalidSubTransactionId || portal->autoHeld)
937 : : {
938 : : Assert(portal->status != PORTAL_ACTIVE);
939 : : Assert(portal->resowner == NULL);
940 : 248 : continue;
941 : : }
942 : :
943 : : /*
944 : : * If a portal is still pinned, forcibly unpin it. PortalDrop will not
945 : : * let us drop the portal otherwise. Whoever pinned the portal was
946 : : * interrupted by the abort too and won't try to use it anymore.
947 : : */
948 [ + + ]: 21166 : if (portal->portalPinned)
949 : 27 : portal->portalPinned = false;
950 : :
951 : : /*
952 : : * We had better not call any user-defined code during cleanup, so if
953 : : * the cleanup hook hasn't been run yet, too bad; we'll just skip it.
954 : : */
955 [ - + ]: 21166 : if (portal->cleanup)
956 : : {
957 [ # # ]: 0 : elog(WARNING, "skipping cleanup for portal \"%s\"", portal->name);
958 : 0 : portal->cleanup = NULL;
959 : : }
960 : :
961 : : /* Zap it. */
962 : 21166 : PortalDrop(portal, false);
963 : : }
964 : 37733 : }
965 : :
966 : : /*
967 : : * Portal-related cleanup when we return to the main loop on error.
968 : : *
969 : : * This is different from the cleanup at transaction abort. Auto-held portals
970 : : * are cleaned up on error but not on transaction abort.
971 : : *
972 : : * If an error happened while a portal was being set up and the transaction
973 : : * is already aborted, whoever was setting up the portal is gone, so mark it
974 : : * as droppable.
975 : : */
976 : : void
977 : 32134 : PortalErrorCleanup(void)
978 : : {
979 : : HASH_SEQ_STATUS status;
980 : : PortalHashEnt *hentry;
981 : :
982 : 32134 : hash_seq_init(&status, PortalHashTable);
983 : :
984 [ + + ]: 34562 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
985 : : {
986 : 2428 : Portal portal = hentry->portal;
987 : :
988 [ + + ]: 2428 : if (portal->autoHeld)
989 : : {
990 : 18 : portal->portalPinned = false;
991 : 18 : PortalDrop(portal, false);
992 : : }
993 [ + + ]: 2410 : else if (portal->status == PORTAL_NEW ||
994 [ + + ]: 2408 : portal->status == PORTAL_DEFINED)
995 : : {
996 : 4 : portal->portalPinned = false;
997 : 4 : MarkPortalFailed(portal);
998 : : }
999 : : }
1000 : 32134 : }
1001 : :
1002 : : /*
1003 : : * Pre-subcommit processing for portals.
1004 : : *
1005 : : * Reassign portals created or used in the current subtransaction to the
1006 : : * parent subtransaction.
1007 : : */
1008 : : void
1009 : 17465 : AtSubCommit_Portals(SubTransactionId mySubid,
1010 : : SubTransactionId parentSubid,
1011 : : int parentLevel,
1012 : : ResourceOwner parentXactOwner)
1013 : : {
1014 : : HASH_SEQ_STATUS status;
1015 : : PortalHashEnt *hentry;
1016 : :
1017 : 17465 : hash_seq_init(&status, PortalHashTable);
1018 : :
1019 [ + + ]: 51622 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1020 : : {
1021 : 16692 : Portal portal = hentry->portal;
1022 : :
1023 [ + + ]: 16692 : if (portal->createSubid == mySubid)
1024 : : {
1025 : 30 : portal->createSubid = parentSubid;
1026 : 30 : portal->createLevel = parentLevel;
1027 [ + - ]: 30 : if (portal->resowner)
1028 : 30 : ResourceOwnerNewParent(portal->resowner, parentXactOwner);
1029 : : }
1030 [ + + ]: 16692 : if (portal->activeSubid == mySubid)
1031 : 111 : portal->activeSubid = parentSubid;
1032 : : }
1033 : 17465 : }
1034 : :
1035 : : /*
1036 : : * Subtransaction abort handling for portals.
1037 : : *
1038 : : * Deactivate portals created or used during the failed subtransaction.
1039 : : * Note that per AtSubCommit_Portals, this will catch portals created/used
1040 : : * in descendants of the subtransaction too.
1041 : : *
1042 : : * We don't destroy any portals here; that's done in AtSubCleanup_Portals.
1043 : : */
1044 : : void
1045 : 5713 : AtSubAbort_Portals(SubTransactionId mySubid,
1046 : : SubTransactionId parentSubid,
1047 : : ResourceOwner myXactOwner,
1048 : : ResourceOwner parentXactOwner)
1049 : : {
1050 : : HASH_SEQ_STATUS status;
1051 : : PortalHashEnt *hentry;
1052 : :
1053 : 5713 : hash_seq_init(&status, PortalHashTable);
1054 : :
1055 [ + + ]: 14251 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1056 : : {
1057 : 8538 : Portal portal = hentry->portal;
1058 : :
1059 : : /* Was it created in this subtransaction? */
1060 [ + + ]: 8538 : if (portal->createSubid != mySubid)
1061 : : {
1062 : : /* No, but maybe it was used in this subtransaction? */
1063 [ + + ]: 7608 : if (portal->activeSubid == mySubid)
1064 : : {
1065 : : /* Maintain activeSubid until the portal is removed */
1066 : 57 : portal->activeSubid = parentSubid;
1067 : :
1068 : : /*
1069 : : * A MarkPortalActive() caller ran an upper-level portal in
1070 : : * this subtransaction and left the portal ACTIVE. This can't
1071 : : * happen, but force the portal into FAILED state for the same
1072 : : * reasons discussed below.
1073 : : *
1074 : : * We assume we can get away without forcing upper-level READY
1075 : : * portals to fail, even if they were run and then suspended.
1076 : : * In theory a suspended upper-level portal could have
1077 : : * acquired some references to objects that are about to be
1078 : : * destroyed, but there should be sufficient defenses against
1079 : : * such cases: the portal's original query cannot contain such
1080 : : * references, and any references within, say, cached plans of
1081 : : * PL/pgSQL functions are not from active queries and should
1082 : : * be protected by revalidation logic.
1083 : : */
1084 [ - + ]: 57 : if (portal->status == PORTAL_ACTIVE)
1085 : 0 : MarkPortalFailed(portal);
1086 : :
1087 : : /*
1088 : : * Also, if we failed it during the current subtransaction
1089 : : * (either just above, or earlier), reattach its resource
1090 : : * owner to the current subtransaction's resource owner, so
1091 : : * that any resources it still holds will be released while
1092 : : * cleaning up this subtransaction. This prevents some corner
1093 : : * cases wherein we might get Asserts or worse while cleaning
1094 : : * up objects created during the current subtransaction
1095 : : * (because they're still referenced within this portal).
1096 : : */
1097 [ + + + - ]: 57 : if (portal->status == PORTAL_FAILED && portal->resowner)
1098 : : {
1099 : 9 : ResourceOwnerNewParent(portal->resowner, myXactOwner);
1100 : 9 : portal->resowner = NULL;
1101 : : }
1102 : : }
1103 : : /* Done if it wasn't created in this subtransaction */
1104 : 7608 : continue;
1105 : : }
1106 : :
1107 : : /*
1108 : : * Force any live portals of my own subtransaction into FAILED state.
1109 : : * We have to do this because they might refer to objects created or
1110 : : * changed in the failed subtransaction, leading to crashes within
1111 : : * ExecutorEnd when portalcmds.c tries to close down the portal.
1112 : : * Currently, every MarkPortalActive() caller ensures it updates the
1113 : : * portal status again before relinquishing control, so ACTIVE can't
1114 : : * happen here. If it does happen, dispose the portal like existing
1115 : : * MarkPortalActive() callers would.
1116 : : */
1117 [ + - ]: 930 : if (portal->status == PORTAL_NEW ||
1118 [ + + ]: 930 : portal->status == PORTAL_DEFINED ||
1119 [ + + ]: 926 : portal->status == PORTAL_READY ||
1120 [ - + ]: 243 : portal->status == PORTAL_ACTIVE)
1121 : 687 : MarkPortalFailed(portal);
1122 : :
1123 : : /*
1124 : : * Allow portalcmds.c to clean up the state it knows about, if we
1125 : : * haven't already.
1126 : : */
1127 [ - + ]: 930 : if (portal->cleanup)
1128 : : {
1129 : 0 : portal->cleanup(portal);
1130 : 0 : portal->cleanup = NULL;
1131 : : }
1132 : :
1133 : : /* drop cached plan reference, if any */
1134 : 930 : PortalReleaseCachedPlan(portal);
1135 : :
1136 : : /*
1137 : : * Any resources belonging to the portal will be released in the
1138 : : * upcoming transaction-wide cleanup; they will be gone before we run
1139 : : * PortalDrop.
1140 : : */
1141 : 930 : portal->resowner = NULL;
1142 : :
1143 : : /*
1144 : : * Although we can't delete the portal data structure proper, we can
1145 : : * release any memory in subsidiary contexts, such as executor state.
1146 : : * The cleanup hook was the last thing that might have needed data
1147 : : * there.
1148 : : */
1149 : 930 : MemoryContextDeleteChildren(portal->portalContext);
1150 : : }
1151 : 5713 : }
1152 : :
1153 : : /*
1154 : : * Post-subabort cleanup for portals.
1155 : : *
1156 : : * Drop all portals created in the failed subtransaction (but note that
1157 : : * we will not drop any that were reassigned to the parent above).
1158 : : */
1159 : : void
1160 : 5713 : AtSubCleanup_Portals(SubTransactionId mySubid)
1161 : : {
1162 : : HASH_SEQ_STATUS status;
1163 : : PortalHashEnt *hentry;
1164 : :
1165 : 5713 : hash_seq_init(&status, PortalHashTable);
1166 : :
1167 [ + + ]: 14017 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1168 : : {
1169 : 8304 : Portal portal = hentry->portal;
1170 : :
1171 [ + + ]: 8304 : if (portal->createSubid != mySubid)
1172 : 7608 : continue;
1173 : :
1174 : : /*
1175 : : * If a portal is still pinned, forcibly unpin it. PortalDrop will not
1176 : : * let us drop the portal otherwise. Whoever pinned the portal was
1177 : : * interrupted by the abort too and won't try to use it anymore.
1178 : : */
1179 [ + + ]: 696 : if (portal->portalPinned)
1180 : 3 : portal->portalPinned = false;
1181 : :
1182 : : /*
1183 : : * We had better not call any user-defined code during cleanup, so if
1184 : : * the cleanup hook hasn't been run yet, too bad; we'll just skip it.
1185 : : */
1186 [ - + ]: 696 : if (portal->cleanup)
1187 : : {
1188 [ # # ]: 0 : elog(WARNING, "skipping cleanup for portal \"%s\"", portal->name);
1189 : 0 : portal->cleanup = NULL;
1190 : : }
1191 : :
1192 : : /* Zap it. */
1193 : 696 : PortalDrop(portal, false);
1194 : : }
1195 : 5713 : }
1196 : :
1197 : : /* Find all available cursors */
1198 : : Datum
1199 : 169 : pg_cursor(PG_FUNCTION_ARGS)
1200 : : {
1201 : 169 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1202 : : HASH_SEQ_STATUS hash_seq;
1203 : : PortalHashEnt *hentry;
1204 : :
1205 : : /*
1206 : : * We put all the tuples into a tuplestore in one scan of the hashtable.
1207 : : * This avoids any issue of the hashtable possibly changing between calls.
1208 : : */
1209 : 169 : InitMaterializedSRF(fcinfo, 0);
1210 : :
1211 : 169 : hash_seq_init(&hash_seq, PortalHashTable);
1212 [ + + ]: 458 : while ((hentry = hash_seq_search(&hash_seq)) != NULL)
1213 : : {
1214 : 289 : Portal portal = hentry->portal;
1215 : : Datum values[6];
1216 : 289 : bool nulls[6] = {0};
1217 : :
1218 : : /* report only "visible" entries */
1219 [ + + ]: 289 : if (!portal->visible)
1220 : 149 : continue;
1221 : : /* also ignore it if PortalDefineQuery hasn't been called yet */
1222 [ + + ]: 170 : if (!portal->sourceText)
1223 : 30 : continue;
1224 : :
1225 : 140 : values[0] = CStringGetTextDatum(portal->name);
1226 : 140 : values[1] = CStringGetTextDatum(portal->sourceText);
1227 : 140 : values[2] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_HOLD);
1228 : 140 : values[3] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_BINARY);
1229 : 140 : values[4] = BoolGetDatum(portal->cursorOptions & CURSOR_OPT_SCROLL);
1230 : 140 : values[5] = TimestampTzGetDatum(portal->creation_time);
1231 : :
1232 : 140 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
1233 : : }
1234 : :
1235 : 169 : return (Datum) 0;
1236 : : }
1237 : :
1238 : : bool
1239 : 38 : ThereAreNoReadyPortals(void)
1240 : : {
1241 : : HASH_SEQ_STATUS status;
1242 : : PortalHashEnt *hentry;
1243 : :
1244 : 38 : hash_seq_init(&status, PortalHashTable);
1245 : :
1246 [ + + ]: 76 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1247 : : {
1248 : 38 : Portal portal = hentry->portal;
1249 : :
1250 [ - + ]: 38 : if (portal->status == PORTAL_READY)
1251 : : {
1252 : 0 : hash_seq_term(&status);
1253 : 0 : return false;
1254 : : }
1255 : : }
1256 : :
1257 : 38 : return true;
1258 : : }
1259 : :
1260 : : /*
1261 : : * Hold all pinned portals.
1262 : : *
1263 : : * When initiating a COMMIT or ROLLBACK inside a procedure, this must be
1264 : : * called to protect internally-generated cursors from being dropped during
1265 : : * the transaction shutdown. Currently, SPI calls this automatically; PLs
1266 : : * that initiate COMMIT or ROLLBACK some other way are on the hook to do it
1267 : : * themselves. (Note that we couldn't do this in, say, AtAbort_Portals
1268 : : * because we need to run user-defined code while persisting a portal.
1269 : : * It's too late to do that once transaction abort has started.)
1270 : : *
1271 : : * We protect such portals by converting them to held cursors. We mark them
1272 : : * as "auto-held" so that exception exit knows to clean them up. (In normal,
1273 : : * non-exception code paths, the PL needs to clean such portals itself, since
1274 : : * transaction end won't do it anymore; but that should be normal practice
1275 : : * anyway.)
1276 : : */
1277 : : void
1278 : 2340 : HoldPinnedPortals(void)
1279 : : {
1280 : : HASH_SEQ_STATUS status;
1281 : : PortalHashEnt *hentry;
1282 : :
1283 : 2340 : hash_seq_init(&status, PortalHashTable);
1284 : :
1285 [ + + ]: 4756 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1286 : : {
1287 : 2419 : Portal portal = hentry->portal;
1288 : :
1289 [ + + + + ]: 2419 : if (portal->portalPinned && !portal->autoHeld)
1290 : : {
1291 : : /*
1292 : : * Doing transaction control, especially abort, inside a cursor
1293 : : * loop that is not read-only, for example using UPDATE ...
1294 : : * RETURNING, has weird semantics issues. Also, this
1295 : : * implementation wouldn't work, because such portals cannot be
1296 : : * held. (The core grammar enforces that only SELECT statements
1297 : : * can drive a cursor, but for example PL/pgSQL does not restrict
1298 : : * it.)
1299 : : */
1300 [ + + ]: 35 : if (portal->strategy != PORTAL_ONE_SELECT)
1301 [ + - ]: 1 : ereport(ERROR,
1302 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1303 : : errmsg("cannot perform transaction commands inside a cursor loop that is not read-only")));
1304 : :
1305 : : /* Verify it's in a suitable state to be held */
1306 [ - + ]: 34 : if (portal->status != PORTAL_READY)
1307 [ # # ]: 0 : elog(ERROR, "pinned portal is not ready to be auto-held");
1308 : :
1309 : 34 : HoldPortal(portal);
1310 : 32 : portal->autoHeld = true;
1311 : : }
1312 : : }
1313 : 2337 : }
1314 : :
1315 : : /*
1316 : : * Drop the outer active snapshots for all portals, so that no snapshots
1317 : : * remain active.
1318 : : *
1319 : : * Like HoldPinnedPortals, this must be called when initiating a COMMIT or
1320 : : * ROLLBACK inside a procedure. This has to be separate from that since it
1321 : : * should not be run until we're done with steps that are likely to fail.
1322 : : *
1323 : : * It's tempting to fold this into PreCommit_Portals, but to do so, we'd
1324 : : * need to clean up snapshot management in VACUUM and perhaps other places.
1325 : : */
1326 : : void
1327 : 2337 : ForgetPortalSnapshots(void)
1328 : : {
1329 : : HASH_SEQ_STATUS status;
1330 : : PortalHashEnt *hentry;
1331 : 2337 : int numPortalSnaps = 0;
1332 : 2337 : int numActiveSnaps = 0;
1333 : :
1334 : : /* First, scan PortalHashTable and clear portalSnapshot fields */
1335 : 2337 : hash_seq_init(&status, PortalHashTable);
1336 : :
1337 [ + + ]: 7090 : while ((hentry = (PortalHashEnt *) hash_seq_search(&status)) != NULL)
1338 : : {
1339 : 2416 : Portal portal = hentry->portal;
1340 : :
1341 [ + + ]: 2416 : if (portal->portalSnapshot != NULL)
1342 : : {
1343 : 2337 : portal->portalSnapshot = NULL;
1344 : 2337 : numPortalSnaps++;
1345 : : }
1346 : : /* portal->holdSnapshot will be cleaned up in PreCommit_Portals */
1347 : : }
1348 : :
1349 : : /*
1350 : : * Now, pop all the active snapshots, which should be just those that were
1351 : : * portal snapshots. Ideally we'd drive this directly off the portal
1352 : : * scan, but there's no good way to visit the portals in the correct
1353 : : * order. So just cross-check after the fact.
1354 : : */
1355 [ + + ]: 4674 : while (ActiveSnapshotSet())
1356 : : {
1357 : 2337 : PopActiveSnapshot();
1358 : 2337 : numActiveSnaps++;
1359 : : }
1360 : :
1361 [ - + ]: 2337 : if (numPortalSnaps != numActiveSnaps)
1362 [ # # ]: 0 : elog(ERROR, "portal snapshots (%d) did not account for all active snapshots (%d)",
1363 : : numPortalSnaps, numActiveSnaps);
1364 : 2337 : }
|