Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * xact.c
4 : : * top level transaction system support routines
5 : : *
6 : : * See src/backend/access/transam/README for more information.
7 : : *
8 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
9 : : * Portions Copyright (c) 1994, Regents of the University of California
10 : : *
11 : : *
12 : : * IDENTIFICATION
13 : : * src/backend/access/transam/xact.c
14 : : *
15 : : *-------------------------------------------------------------------------
16 : : */
17 : :
18 : : #include "postgres.h"
19 : :
20 : : #include <time.h>
21 : : #include <unistd.h>
22 : :
23 : : #include "access/commit_ts.h"
24 : : #include "access/multixact.h"
25 : : #include "access/parallel.h"
26 : : #include "access/subtrans.h"
27 : : #include "access/transam.h"
28 : : #include "access/twophase.h"
29 : : #include "access/xact.h"
30 : : #include "access/xlog.h"
31 : : #include "access/xloginsert.h"
32 : : #include "access/xlogrecovery.h"
33 : : #include "access/xlogutils.h"
34 : : #include "access/xlogwait.h"
35 : : #include "catalog/index.h"
36 : : #include "catalog/namespace.h"
37 : : #include "catalog/pg_enum.h"
38 : : #include "catalog/storage.h"
39 : : #include "commands/async.h"
40 : : #include "commands/tablecmds.h"
41 : : #include "commands/trigger.h"
42 : : #include "common/pg_prng.h"
43 : : #include "executor/spi.h"
44 : : #include "libpq/be-fsstubs.h"
45 : : #include "libpq/pqsignal.h"
46 : : #include "miscadmin.h"
47 : : #include "pg_trace.h"
48 : : #include "pgstat.h"
49 : : #include "replication/logical.h"
50 : : #include "replication/logicallauncher.h"
51 : : #include "replication/logicalworker.h"
52 : : #include "replication/origin.h"
53 : : #include "replication/snapbuild.h"
54 : : #include "replication/syncrep.h"
55 : : #include "storage/aio_subsys.h"
56 : : #include "storage/condition_variable.h"
57 : : #include "storage/fd.h"
58 : : #include "storage/lmgr.h"
59 : : #include "storage/md.h"
60 : : #include "storage/predicate.h"
61 : : #include "storage/proc.h"
62 : : #include "storage/procarray.h"
63 : : #include "storage/sinvaladt.h"
64 : : #include "storage/smgr.h"
65 : : #include "utils/builtins.h"
66 : : #include "utils/combocid.h"
67 : : #include "utils/guc.h"
68 : : #include "utils/injection_point.h"
69 : : #include "utils/inval.h"
70 : : #include "utils/memutils.h"
71 : : #include "utils/relmapper.h"
72 : : #include "utils/snapmgr.h"
73 : : #include "utils/timeout.h"
74 : : #include "utils/timestamp.h"
75 : : #include "utils/typcache.h"
76 : : #include "utils/wait_event.h"
77 : :
78 : : /*
79 : : * User-tweakable parameters
80 : : */
81 : : int DefaultXactIsoLevel = XACT_READ_COMMITTED;
82 : : int XactIsoLevel = XACT_READ_COMMITTED;
83 : :
84 : : bool DefaultXactReadOnly = false;
85 : : bool XactReadOnly;
86 : :
87 : : bool DefaultXactDeferrable = false;
88 : : bool XactDeferrable;
89 : :
90 : : int synchronous_commit = SYNCHRONOUS_COMMIT_ON;
91 : :
92 : : /*
93 : : * CheckXidAlive is a xid value pointing to a possibly ongoing (sub)
94 : : * transaction. Currently, it is used in logical decoding. It's possible
95 : : * that such transactions can get aborted while the decoding is ongoing in
96 : : * which case we skip decoding that particular transaction. To ensure that we
97 : : * check whether the CheckXidAlive is aborted after fetching the tuple from
98 : : * system tables. We also ensure that during logical decoding we never
99 : : * directly access the tableam or heap APIs because we are checking for the
100 : : * concurrent aborts only in systable_* APIs.
101 : : */
102 : : TransactionId CheckXidAlive = InvalidTransactionId;
103 : : bool bsysscan = false;
104 : :
105 : : /*
106 : : * When running as a parallel worker, we place only a single
107 : : * TransactionStateData on the parallel worker's state stack, and the XID
108 : : * reflected there will be that of the *innermost* currently-active
109 : : * subtransaction in the backend that initiated parallelism. However,
110 : : * GetTopTransactionId() and TransactionIdIsCurrentTransactionId()
111 : : * need to return the same answers in the parallel worker as they would have
112 : : * in the user backend, so we need some additional bookkeeping.
113 : : *
114 : : * XactTopFullTransactionId stores the XID of our toplevel transaction, which
115 : : * will be the same as TopTransactionStateData.fullTransactionId in an
116 : : * ordinary backend; but in a parallel backend, which does not have the entire
117 : : * transaction state, it will instead be copied from the backend that started
118 : : * the parallel operation.
119 : : *
120 : : * nParallelCurrentXids will be 0 and ParallelCurrentXids NULL in an ordinary
121 : : * backend, but in a parallel backend, nParallelCurrentXids will contain the
122 : : * number of XIDs that need to be considered current, and ParallelCurrentXids
123 : : * will contain the XIDs themselves. This includes all XIDs that were current
124 : : * or sub-committed in the parent at the time the parallel operation began.
125 : : * The XIDs are stored sorted in numerical order (not logical order) to make
126 : : * lookups as fast as possible.
127 : : */
128 : : static FullTransactionId XactTopFullTransactionId = {InvalidTransactionId};
129 : : static int nParallelCurrentXids = 0;
130 : : static TransactionId *ParallelCurrentXids;
131 : :
132 : : /*
133 : : * Miscellaneous flag bits to record events which occur on the top level
134 : : * transaction. These flags are only persisted in MyXactFlags and are intended
135 : : * so we remember to do certain things later on in the transaction. This is
136 : : * globally accessible, so can be set from anywhere in the code that requires
137 : : * recording flags.
138 : : */
139 : : int MyXactFlags;
140 : :
141 : : /*
142 : : * transaction states - transaction state from server perspective
143 : : */
144 : : typedef enum TransState
145 : : {
146 : : TRANS_DEFAULT, /* idle */
147 : : TRANS_START, /* transaction starting */
148 : : TRANS_INPROGRESS, /* inside a valid transaction */
149 : : TRANS_COMMIT, /* commit in progress */
150 : : TRANS_ABORT, /* abort in progress */
151 : : TRANS_PREPARE, /* prepare in progress */
152 : : } TransState;
153 : :
154 : : /*
155 : : * transaction block states - transaction state of client queries
156 : : *
157 : : * Note: the subtransaction states are used only for non-topmost
158 : : * transactions; the others appear only in the topmost transaction.
159 : : */
160 : : typedef enum TBlockState
161 : : {
162 : : /* not-in-transaction-block states */
163 : : TBLOCK_DEFAULT, /* idle */
164 : : TBLOCK_STARTED, /* running single-query transaction */
165 : :
166 : : /* transaction block states */
167 : : TBLOCK_BEGIN, /* starting transaction block */
168 : : TBLOCK_INPROGRESS, /* live transaction */
169 : : TBLOCK_IMPLICIT_INPROGRESS, /* live transaction after implicit BEGIN */
170 : : TBLOCK_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
171 : : TBLOCK_END, /* COMMIT received */
172 : : TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
173 : : TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
174 : : TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
175 : : TBLOCK_PREPARE, /* live xact, PREPARE received */
176 : :
177 : : /* subtransaction states */
178 : : TBLOCK_SUBBEGIN, /* starting a subtransaction */
179 : : TBLOCK_SUBINPROGRESS, /* live subtransaction */
180 : : TBLOCK_SUBRELEASE, /* RELEASE received */
181 : : TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
182 : : TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
183 : : TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
184 : : TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
185 : : TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
186 : : TBLOCK_SUBABORT_RESTART, /* failed subxact, ROLLBACK TO received */
187 : : } TBlockState;
188 : :
189 : : /*
190 : : * transaction state structure
191 : : *
192 : : * Note: parallelModeLevel counts the number of unmatched EnterParallelMode
193 : : * calls done at this transaction level. parallelChildXact is true if any
194 : : * upper transaction level has nonzero parallelModeLevel.
195 : : */
196 : : typedef struct TransactionStateData
197 : : {
198 : : FullTransactionId fullTransactionId; /* my FullTransactionId */
199 : : SubTransactionId subTransactionId; /* my subxact ID */
200 : : char *name; /* savepoint name, if any */
201 : : int savepointLevel; /* savepoint level */
202 : : TransState state; /* low-level state */
203 : : TBlockState blockState; /* high-level state */
204 : : int nestingLevel; /* transaction nesting depth */
205 : : int gucNestLevel; /* GUC context nesting depth */
206 : : MemoryContext curTransactionContext; /* my xact-lifetime context */
207 : : ResourceOwner curTransactionOwner; /* my query resources */
208 : : MemoryContext priorContext; /* CurrentMemoryContext before xact started */
209 : : TransactionId *childXids; /* subcommitted child XIDs, in XID order */
210 : : int nChildXids; /* # of subcommitted child XIDs */
211 : : int maxChildXids; /* allocated size of childXids[] */
212 : : Oid prevUser; /* previous CurrentUserId setting */
213 : : int prevSecContext; /* previous SecurityRestrictionContext */
214 : : bool prevXactReadOnly; /* entry-time xact r/o state */
215 : : bool startedInRecovery; /* did we start in recovery? */
216 : : bool didLogXid; /* has xid been included in WAL record? */
217 : : int parallelModeLevel; /* Enter/ExitParallelMode counter */
218 : : bool parallelChildXact; /* is any parent transaction parallel? */
219 : : bool chain; /* start a new block after this one */
220 : : bool topXidLogged; /* for a subxact: is top-level XID logged? */
221 : : struct TransactionStateData *parent; /* back link to parent */
222 : : } TransactionStateData;
223 : :
224 : : typedef TransactionStateData *TransactionState;
225 : :
226 : : /*
227 : : * Serialized representation used to transmit transaction state to parallel
228 : : * workers through shared memory.
229 : : */
230 : : typedef struct SerializedTransactionState
231 : : {
232 : : int xactIsoLevel;
233 : : bool xactDeferrable;
234 : : FullTransactionId topFullTransactionId;
235 : : FullTransactionId currentFullTransactionId;
236 : : CommandId currentCommandId;
237 : : int nParallelCurrentXids;
238 : : pg_attribute_counted_by(nParallelCurrentXids) TransactionId parallelCurrentXids[FLEXIBLE_ARRAY_MEMBER];
239 : : } SerializedTransactionState;
240 : :
241 : : /* The size of SerializedTransactionState, not including the final array. */
242 : : #define SerializedTransactionStateHeaderSize \
243 : : offsetof(SerializedTransactionState, parallelCurrentXids)
244 : :
245 : : /*
246 : : * CurrentTransactionState always points to the current transaction state
247 : : * block. It will point to TopTransactionStateData when not in a
248 : : * transaction at all, or when in a top-level transaction.
249 : : */
250 : : static TransactionStateData TopTransactionStateData = {
251 : : .state = TRANS_DEFAULT,
252 : : .blockState = TBLOCK_DEFAULT,
253 : : .topXidLogged = false,
254 : : };
255 : :
256 : : /*
257 : : * unreportedXids holds XIDs of all subtransactions that have not yet been
258 : : * reported in an XLOG_XACT_ASSIGNMENT record.
259 : : */
260 : : static int nUnreportedXids;
261 : : static TransactionId unreportedXids[PGPROC_MAX_CACHED_SUBXIDS];
262 : :
263 : : static TransactionState CurrentTransactionState = &TopTransactionStateData;
264 : :
265 : : /*
266 : : * The subtransaction ID and command ID assignment counters are global
267 : : * to a whole transaction, so we do not keep them in the state stack.
268 : : */
269 : : static SubTransactionId currentSubTransactionId;
270 : : static CommandId currentCommandId;
271 : : static bool currentCommandIdUsed;
272 : :
273 : : /*
274 : : * xactStartTimestamp is the value of transaction_timestamp().
275 : : * stmtStartTimestamp is the value of statement_timestamp().
276 : : * xactStopTimestamp is the time at which we log a commit / abort WAL record,
277 : : * or if that was skipped, the time of the first subsequent
278 : : * GetCurrentTransactionStopTimestamp() call.
279 : : *
280 : : * These do not change as we enter and exit subtransactions, so we don't
281 : : * keep them inside the TransactionState stack.
282 : : */
283 : : static TimestampTz xactStartTimestamp;
284 : : static TimestampTz stmtStartTimestamp;
285 : : static TimestampTz xactStopTimestamp;
286 : :
287 : : /*
288 : : * GID to be used for preparing the current transaction. This is also
289 : : * global to a whole transaction, so we don't keep it in the state stack.
290 : : */
291 : : static char *prepareGID;
292 : :
293 : : /*
294 : : * Some commands want to force synchronous commit.
295 : : */
296 : : static bool forceSyncCommit = false;
297 : :
298 : : /* Flag for logging statements in a transaction. */
299 : : bool xact_is_sampled = false;
300 : :
301 : : /*
302 : : * Private context for transaction-abort work --- we reserve space for this
303 : : * at startup to ensure that AbortTransaction and AbortSubTransaction can work
304 : : * when we've run out of memory.
305 : : */
306 : : static MemoryContext TransactionAbortContext = NULL;
307 : :
308 : : /*
309 : : * List of add-on start- and end-of-xact callbacks
310 : : */
311 : : typedef struct XactCallbackItem
312 : : {
313 : : struct XactCallbackItem *next;
314 : : XactCallback callback;
315 : : void *arg;
316 : : } XactCallbackItem;
317 : :
318 : : static XactCallbackItem *Xact_callbacks = NULL;
319 : :
320 : : /*
321 : : * List of add-on start- and end-of-subxact callbacks
322 : : */
323 : : typedef struct SubXactCallbackItem
324 : : {
325 : : struct SubXactCallbackItem *next;
326 : : SubXactCallback callback;
327 : : void *arg;
328 : : } SubXactCallbackItem;
329 : :
330 : : static SubXactCallbackItem *SubXact_callbacks = NULL;
331 : :
332 : :
333 : : /* local function prototypes */
334 : : static void AssignTransactionId(TransactionState s);
335 : : static void AbortTransaction(void);
336 : : static void AtAbort_Memory(void);
337 : : static void AtCleanup_Memory(void);
338 : : static void AtAbort_ResourceOwner(void);
339 : : static void AtCCI_LocalCache(void);
340 : : static void AtCommit_Memory(void);
341 : : static void AtStart_Cache(void);
342 : : static void AtStart_Memory(void);
343 : : static void AtStart_ResourceOwner(void);
344 : : static void CallXactCallbacks(XactEvent event);
345 : : static void CallSubXactCallbacks(SubXactEvent event,
346 : : SubTransactionId mySubid,
347 : : SubTransactionId parentSubid);
348 : : static void CleanupTransaction(void);
349 : : static void CheckTransactionBlock(bool isTopLevel, bool throwError,
350 : : const char *stmtType);
351 : : static void CommitTransaction(void);
352 : : static TransactionId RecordTransactionAbort(bool isSubXact);
353 : : static void StartTransaction(void);
354 : :
355 : : static bool CommitTransactionCommandInternal(void);
356 : : static bool AbortCurrentTransactionInternal(void);
357 : :
358 : : static void StartSubTransaction(void);
359 : : static void CommitSubTransaction(void);
360 : : static void AbortSubTransaction(void);
361 : : static void CleanupSubTransaction(void);
362 : : static void PushTransaction(void);
363 : : static void PopTransaction(void);
364 : :
365 : : static void AtSubAbort_Memory(void);
366 : : static void AtSubCleanup_Memory(void);
367 : : static void AtSubAbort_ResourceOwner(void);
368 : : static void AtSubCommit_Memory(void);
369 : : static void AtSubStart_Memory(void);
370 : : static void AtSubStart_ResourceOwner(void);
371 : :
372 : : static void ShowTransactionState(const char *str);
373 : : static void ShowTransactionStateRec(const char *str, TransactionState s);
374 : : static const char *BlockStateAsString(TBlockState blockState);
375 : : static const char *TransStateAsString(TransState state);
376 : :
377 : :
378 : : /* ----------------------------------------------------------------
379 : : * transaction state accessors
380 : : * ----------------------------------------------------------------
381 : : */
382 : :
383 : : /*
384 : : * IsTransactionState
385 : : *
386 : : * This returns true if we are inside a valid transaction; that is,
387 : : * it is safe to initiate database access, take heavyweight locks, etc.
388 : : */
389 : : bool
390 : 1281489 : IsTransactionState(void)
391 : : {
392 : 1281489 : TransactionState s = CurrentTransactionState;
393 : :
394 : : /*
395 : : * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
396 : : * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
397 : : * TRANS_PREPARE since it might be too soon or too late within those
398 : : * transition states to do anything interesting. Hence, the only "valid"
399 : : * state is TRANS_INPROGRESS.
400 : : */
401 : 1281489 : return (s->state == TRANS_INPROGRESS);
402 : : }
403 : :
404 : : /*
405 : : * IsAbortedTransactionBlockState
406 : : *
407 : : * This returns true if we are within an aborted transaction block.
408 : : */
409 : : bool
410 : 987512 : IsAbortedTransactionBlockState(void)
411 : : {
412 : 987512 : TransactionState s = CurrentTransactionState;
413 : :
414 [ + + ]: 987512 : if (s->blockState == TBLOCK_ABORT ||
415 [ + + ]: 985432 : s->blockState == TBLOCK_SUBABORT)
416 : 2632 : return true;
417 : :
418 : 984880 : return false;
419 : : }
420 : :
421 : :
422 : : /*
423 : : * GetTopTransactionId
424 : : *
425 : : * This will return the XID of the main transaction, assigning one if
426 : : * it's not yet set. Be careful to call this only inside a valid xact.
427 : : */
428 : : TransactionId
429 : 37002 : GetTopTransactionId(void)
430 : : {
431 [ + + ]: 37002 : if (!FullTransactionIdIsValid(XactTopFullTransactionId))
432 : 599 : AssignTransactionId(&TopTransactionStateData);
433 : 37002 : return XidFromFullTransactionId(XactTopFullTransactionId);
434 : : }
435 : :
436 : : /*
437 : : * GetTopTransactionIdIfAny
438 : : *
439 : : * This will return the XID of the main transaction, if one is assigned.
440 : : * It will return InvalidTransactionId if we are not currently inside a
441 : : * transaction, or inside a transaction that hasn't yet been assigned an XID.
442 : : */
443 : : TransactionId
444 : 67131548 : GetTopTransactionIdIfAny(void)
445 : : {
446 : 67131548 : return XidFromFullTransactionId(XactTopFullTransactionId);
447 : : }
448 : :
449 : : /*
450 : : * GetCurrentTransactionId
451 : : *
452 : : * This will return the XID of the current transaction (main or sub
453 : : * transaction), assigning one if it's not yet set. Be careful to call this
454 : : * only inside a valid xact.
455 : : */
456 : : TransactionId
457 : 17532263 : GetCurrentTransactionId(void)
458 : : {
459 : 17532263 : TransactionState s = CurrentTransactionState;
460 : :
461 [ + + ]: 17532263 : if (!FullTransactionIdIsValid(s->fullTransactionId))
462 : 185540 : AssignTransactionId(s);
463 : 17532256 : return XidFromFullTransactionId(s->fullTransactionId);
464 : : }
465 : :
466 : : /*
467 : : * GetCurrentTransactionIdIfAny
468 : : *
469 : : * This will return the XID of the current sub xact, if one is assigned.
470 : : * It will return InvalidTransactionId if we are not currently inside a
471 : : * transaction, or inside a transaction that hasn't been assigned an XID yet.
472 : : */
473 : : TransactionId
474 : 25632738 : GetCurrentTransactionIdIfAny(void)
475 : : {
476 : 25632738 : return XidFromFullTransactionId(CurrentTransactionState->fullTransactionId);
477 : : }
478 : :
479 : : /*
480 : : * GetTopFullTransactionId
481 : : *
482 : : * This will return the FullTransactionId of the main transaction, assigning
483 : : * one if it's not yet set. Be careful to call this only inside a valid xact.
484 : : */
485 : : FullTransactionId
486 : 3316 : GetTopFullTransactionId(void)
487 : : {
488 [ + + ]: 3316 : if (!FullTransactionIdIsValid(XactTopFullTransactionId))
489 : 2227 : AssignTransactionId(&TopTransactionStateData);
490 : 3316 : return XactTopFullTransactionId;
491 : : }
492 : :
493 : : /*
494 : : * GetTopFullTransactionIdIfAny
495 : : *
496 : : * This will return the FullTransactionId of the main transaction, if one is
497 : : * assigned. It will return InvalidFullTransactionId if we are not currently
498 : : * inside a transaction, or inside a transaction that hasn't yet been assigned
499 : : * one.
500 : : */
501 : : FullTransactionId
502 : 126 : GetTopFullTransactionIdIfAny(void)
503 : : {
504 : 126 : return XactTopFullTransactionId;
505 : : }
506 : :
507 : : /*
508 : : * GetCurrentFullTransactionId
509 : : *
510 : : * This will return the FullTransactionId of the current transaction (main or
511 : : * sub transaction), assigning one if it's not yet set. Be careful to call
512 : : * this only inside a valid xact.
513 : : */
514 : : FullTransactionId
515 : 385 : GetCurrentFullTransactionId(void)
516 : : {
517 : 385 : TransactionState s = CurrentTransactionState;
518 : :
519 [ + + ]: 385 : if (!FullTransactionIdIsValid(s->fullTransactionId))
520 : 14 : AssignTransactionId(s);
521 : 385 : return s->fullTransactionId;
522 : : }
523 : :
524 : : /*
525 : : * GetCurrentFullTransactionIdIfAny
526 : : *
527 : : * This will return the FullTransactionId of the current sub xact, if one is
528 : : * assigned. It will return InvalidFullTransactionId if we are not currently
529 : : * inside a transaction, or inside a transaction that hasn't been assigned one
530 : : * yet.
531 : : */
532 : : FullTransactionId
533 : 0 : GetCurrentFullTransactionIdIfAny(void)
534 : : {
535 : 0 : return CurrentTransactionState->fullTransactionId;
536 : : }
537 : :
538 : : /*
539 : : * MarkCurrentTransactionIdLoggedIfAny
540 : : *
541 : : * Remember that the current xid - if it is assigned - now has been wal logged.
542 : : */
543 : : void
544 : 25576842 : MarkCurrentTransactionIdLoggedIfAny(void)
545 : : {
546 [ + + ]: 25576842 : if (FullTransactionIdIsValid(CurrentTransactionState->fullTransactionId))
547 : 25200193 : CurrentTransactionState->didLogXid = true;
548 : 25576842 : }
549 : :
550 : : /*
551 : : * IsSubxactTopXidLogPending
552 : : *
553 : : * This is used to decide whether we need to WAL log the top-level XID for
554 : : * operation in a subtransaction. We require that for logical decoding, see
555 : : * LogicalDecodingProcessRecord.
556 : : *
557 : : * This returns true if effective_wal_level is logical and we are inside
558 : : * a valid subtransaction, for which the assignment was not yet written to
559 : : * any WAL record.
560 : : */
561 : : bool
562 : 25586396 : IsSubxactTopXidLogPending(void)
563 : : {
564 : : /* check whether it is already logged */
565 [ + + ]: 25586396 : if (CurrentTransactionState->topXidLogged)
566 : 102149 : return false;
567 : :
568 : : /* effective_wal_level has to be logical */
569 [ + + + + ]: 25484247 : if (!XLogLogicalInfoActive())
570 : 24872916 : return false;
571 : :
572 : : /* we need to be in a transaction state */
573 [ + + ]: 611331 : if (!IsTransactionState())
574 : 4496 : return false;
575 : :
576 : : /* it has to be a subtransaction */
577 [ + + ]: 606835 : if (!IsSubTransaction())
578 : 606595 : return false;
579 : :
580 : : /* the subtransaction has to have a XID assigned */
581 [ + + ]: 240 : if (!TransactionIdIsValid(GetCurrentTransactionIdIfAny()))
582 : 8 : return false;
583 : :
584 : 232 : return true;
585 : : }
586 : :
587 : : /*
588 : : * MarkSubxactTopXidLogged
589 : : *
590 : : * Remember that the top transaction id for the current subtransaction is WAL
591 : : * logged now.
592 : : */
593 : : void
594 : 230 : MarkSubxactTopXidLogged(void)
595 : : {
596 : : Assert(IsSubxactTopXidLogPending());
597 : :
598 : 230 : CurrentTransactionState->topXidLogged = true;
599 : 230 : }
600 : :
601 : : /*
602 : : * GetStableLatestTransactionId
603 : : *
604 : : * Get the transaction's XID if it has one, else read the next-to-be-assigned
605 : : * XID. Once we have a value, return that same value for the remainder of the
606 : : * current transaction. This is meant to provide the reference point for the
607 : : * age(xid) function, but might be useful for other maintenance tasks as well.
608 : : */
609 : : TransactionId
610 : 156 : GetStableLatestTransactionId(void)
611 : : {
612 : : static LocalTransactionId lxid = InvalidLocalTransactionId;
613 : : static TransactionId stablexid = InvalidTransactionId;
614 : :
615 [ + + ]: 156 : if (lxid != MyProc->vxid.lxid)
616 : : {
617 : 15 : lxid = MyProc->vxid.lxid;
618 : 15 : stablexid = GetTopTransactionIdIfAny();
619 [ + - ]: 15 : if (!TransactionIdIsValid(stablexid))
620 : 15 : stablexid = ReadNextTransactionId();
621 : : }
622 : :
623 : : Assert(TransactionIdIsValid(stablexid));
624 : :
625 : 156 : return stablexid;
626 : : }
627 : :
628 : : /*
629 : : * AssignTransactionId
630 : : *
631 : : * Assigns a new permanent FullTransactionId to the given TransactionState.
632 : : * We do not assign XIDs to transactions until/unless this is called.
633 : : * Also, any parent TransactionStates that don't yet have XIDs are assigned
634 : : * one; this maintains the invariant that a child transaction has an XID
635 : : * following its parent's.
636 : : */
637 : : static void
638 : 189619 : AssignTransactionId(TransactionState s)
639 : : {
640 : 189619 : bool isSubXact = (s->parent != NULL);
641 : : ResourceOwner currentOwner;
642 : 189619 : bool log_unknown_top = false;
643 : :
644 : : /* Assert that caller didn't screw up */
645 : : Assert(!FullTransactionIdIsValid(s->fullTransactionId));
646 : : Assert(s->state == TRANS_INPROGRESS);
647 : :
648 : : /*
649 : : * Workers synchronize transaction state at the beginning of each parallel
650 : : * operation, so we can't account for new XIDs at this point.
651 : : */
652 [ + - - + ]: 189619 : if (IsInParallelMode() || IsParallelWorker())
653 [ # # ]: 0 : ereport(ERROR,
654 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
655 : : errmsg("cannot assign transaction IDs during a parallel operation")));
656 : :
657 : : /*
658 : : * Ensure parent(s) have XIDs, so that a child always has an XID later
659 : : * than its parent. Mustn't recurse here, or we might get a stack
660 : : * overflow if we're at the bottom of a huge stack of subtransactions none
661 : : * of which have XIDs yet.
662 : : */
663 [ + + + + ]: 189619 : if (isSubXact && !FullTransactionIdIsValid(s->parent->fullTransactionId))
664 : : {
665 : 646 : TransactionState p = s->parent;
666 : : TransactionState *parents;
667 : 646 : size_t parentOffset = 0;
668 : :
669 : 646 : parents = palloc_array(TransactionState, s->nestingLevel);
670 [ + + + + ]: 1885 : while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
671 : : {
672 : 1239 : parents[parentOffset++] = p;
673 : 1239 : p = p->parent;
674 : : }
675 : :
676 : : /*
677 : : * This is technically a recursive call, but the recursion will never
678 : : * be more than one layer deep.
679 : : */
680 [ + + ]: 1885 : while (parentOffset != 0)
681 : 1239 : AssignTransactionId(parents[--parentOffset]);
682 : :
683 : 646 : pfree(parents);
684 : : }
685 : :
686 : : /*
687 : : * When effective_wal_level is logical, guarantee that a subtransaction's
688 : : * xid can only be seen in the WAL stream if its toplevel xid has been
689 : : * logged before. If necessary we log an xact_assignment record with fewer
690 : : * than PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't
691 : : * set for a transaction even though it appears in a WAL record, we just
692 : : * might superfluously log something. That can happen when an xid is
693 : : * included somewhere inside a wal record, but not in XLogRecord->xl_xid,
694 : : * like in xl_standby_locks.
695 : : */
696 [ + + + + : 189619 : if (isSubXact && XLogLogicalInfoActive() &&
+ + ]
697 [ + + ]: 312 : !TopTransactionStateData.didLogXid)
698 : 28 : log_unknown_top = true;
699 : :
700 : : /*
701 : : * Generate a new FullTransactionId and record its xid in PGPROC and
702 : : * pg_subtrans.
703 : : *
704 : : * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
705 : : * shared storage other than PGPROC; because if there's no room for it in
706 : : * PGPROC, the subtrans entry is needed to ensure that other backends see
707 : : * the Xid as "running". See GetNewTransactionId.
708 : : */
709 : 189619 : s->fullTransactionId = GetNewTransactionId(isSubXact);
710 [ + + ]: 189612 : if (!isSubXact)
711 : 173110 : XactTopFullTransactionId = s->fullTransactionId;
712 : :
713 [ + + ]: 189612 : if (isSubXact)
714 : 16502 : SubTransSetParent(XidFromFullTransactionId(s->fullTransactionId),
715 : 16502 : XidFromFullTransactionId(s->parent->fullTransactionId));
716 : :
717 : : /*
718 : : * If it's a top-level transaction, the predicate locking system needs to
719 : : * be told about it too.
720 : : */
721 [ + + ]: 189612 : if (!isSubXact)
722 : 173110 : RegisterPredicateLockingXid(XidFromFullTransactionId(s->fullTransactionId));
723 : :
724 : : /*
725 : : * Acquire lock on the transaction XID. (We assume this cannot block.) We
726 : : * have to ensure that the lock is assigned to the transaction's own
727 : : * ResourceOwner.
728 : : */
729 : 189612 : currentOwner = CurrentResourceOwner;
730 : 189612 : CurrentResourceOwner = s->curTransactionOwner;
731 : :
732 : 189612 : XactLockTableInsert(XidFromFullTransactionId(s->fullTransactionId));
733 : :
734 : 189612 : CurrentResourceOwner = currentOwner;
735 : :
736 : : /*
737 : : * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
738 : : * top-level transaction we issue a WAL record for the assignment. We
739 : : * include the top-level xid and all the subxids that have not yet been
740 : : * reported using XLOG_XACT_ASSIGNMENT records.
741 : : *
742 : : * This is required to limit the amount of shared memory required in a hot
743 : : * standby server to keep track of in-progress XIDs. See notes for
744 : : * RecordKnownAssignedTransactionIds().
745 : : *
746 : : * We don't keep track of the immediate parent of each subxid, only the
747 : : * top-level transaction that each subxact belongs to. This is correct in
748 : : * recovery only because aborted subtransactions are separately WAL
749 : : * logged.
750 : : *
751 : : * This is correct even for the case where several levels above us didn't
752 : : * have an xid assigned as we recursed up to them beforehand.
753 : : */
754 [ + + + + ]: 189612 : if (isSubXact && XLogStandbyInfoActive())
755 : : {
756 : 16249 : unreportedXids[nUnreportedXids] = XidFromFullTransactionId(s->fullTransactionId);
757 : 16249 : nUnreportedXids++;
758 : :
759 : : /*
760 : : * ensure this test matches similar one in
761 : : * RecoverPreparedTransactions()
762 : : */
763 [ + + + + ]: 16249 : if (nUnreportedXids >= PGPROC_MAX_CACHED_SUBXIDS ||
764 : : log_unknown_top)
765 : : {
766 : : xl_xact_assignment xlrec;
767 : :
768 : : /*
769 : : * xtop is always set by now because we recurse up transaction
770 : : * stack to the highest unassigned xid and then come back down
771 : : */
772 : 254 : xlrec.xtop = GetTopTransactionId();
773 : : Assert(TransactionIdIsValid(xlrec.xtop));
774 : 254 : xlrec.nsubxacts = nUnreportedXids;
775 : :
776 : 254 : XLogBeginInsert();
777 : 254 : XLogRegisterData(&xlrec, MinSizeOfXactAssignment);
778 : 254 : XLogRegisterData(unreportedXids,
779 : : nUnreportedXids * sizeof(TransactionId));
780 : :
781 : 254 : (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
782 : :
783 : 254 : nUnreportedXids = 0;
784 : : /* mark top, not current xact as having been logged */
785 : 254 : TopTransactionStateData.didLogXid = true;
786 : : }
787 : : }
788 : 189612 : }
789 : :
790 : : /*
791 : : * GetCurrentSubTransactionId
792 : : */
793 : : SubTransactionId
794 : 9450519 : GetCurrentSubTransactionId(void)
795 : : {
796 : 9450519 : TransactionState s = CurrentTransactionState;
797 : :
798 : 9450519 : return s->subTransactionId;
799 : : }
800 : :
801 : : /*
802 : : * SubTransactionIsActive
803 : : *
804 : : * Test if the specified subxact ID is still active. Note caller is
805 : : * responsible for checking whether this ID is relevant to the current xact.
806 : : */
807 : : bool
808 : 0 : SubTransactionIsActive(SubTransactionId subxid)
809 : : {
810 : : TransactionState s;
811 : :
812 [ # # ]: 0 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
813 : : {
814 [ # # ]: 0 : if (s->state == TRANS_ABORT)
815 : 0 : continue;
816 [ # # ]: 0 : if (s->subTransactionId == subxid)
817 : 0 : return true;
818 : : }
819 : 0 : return false;
820 : : }
821 : :
822 : :
823 : : /*
824 : : * GetCurrentCommandId
825 : : *
826 : : * "used" must be true if the caller intends to use the command ID to mark
827 : : * inserted/updated/deleted tuples. false means the ID is being fetched
828 : : * for read-only purposes (ie, as a snapshot validity cutoff). See
829 : : * CommandCounterIncrement() for discussion.
830 : : */
831 : : CommandId
832 : 8260312 : GetCurrentCommandId(bool used)
833 : : {
834 : : /* this is global to a transaction, not subtransaction-local */
835 [ + + ]: 8260312 : if (used)
836 : : {
837 : : /*
838 : : * Forbid setting currentCommandIdUsed in a parallel worker, because
839 : : * we have no provision for communicating this back to the leader. We
840 : : * could relax this restriction when currentCommandIdUsed was already
841 : : * true at the start of the parallel operation.
842 : : */
843 [ - + ]: 4555541 : if (IsParallelWorker())
844 [ # # ]: 0 : ereport(ERROR,
845 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
846 : : errmsg("cannot modify data in a parallel worker")));
847 : :
848 : 4555541 : currentCommandIdUsed = true;
849 : : }
850 : 8260312 : return currentCommandId;
851 : : }
852 : :
853 : : /*
854 : : * SetParallelStartTimestamps
855 : : *
856 : : * In a parallel worker, we should inherit the parent transaction's
857 : : * timestamps rather than setting our own. The parallel worker
858 : : * infrastructure must call this to provide those values before
859 : : * calling StartTransaction() or SetCurrentStatementStartTimestamp().
860 : : */
861 : : void
862 : 2048 : SetParallelStartTimestamps(TimestampTz xact_ts, TimestampTz stmt_ts)
863 : : {
864 : : Assert(IsParallelWorker());
865 : 2048 : xactStartTimestamp = xact_ts;
866 : 2048 : stmtStartTimestamp = stmt_ts;
867 : 2048 : }
868 : :
869 : : /*
870 : : * GetCurrentTransactionStartTimestamp
871 : : */
872 : : TimestampTz
873 : 45315 : GetCurrentTransactionStartTimestamp(void)
874 : : {
875 : 45315 : return xactStartTimestamp;
876 : : }
877 : :
878 : : /*
879 : : * GetCurrentStatementStartTimestamp
880 : : */
881 : : TimestampTz
882 : 1573361 : GetCurrentStatementStartTimestamp(void)
883 : : {
884 : 1573361 : return stmtStartTimestamp;
885 : : }
886 : :
887 : : /*
888 : : * GetCurrentTransactionStopTimestamp
889 : : *
890 : : * If the transaction stop time hasn't already been set, which can happen if
891 : : * we decided we don't need to log an XLOG record, set xactStopTimestamp.
892 : : */
893 : : TimestampTz
894 : 1329835 : GetCurrentTransactionStopTimestamp(void)
895 : : {
896 : 1329835 : TransactionState s PG_USED_FOR_ASSERTS_ONLY = CurrentTransactionState;
897 : :
898 : : /* should only be called after commit / abort processing */
899 : : Assert(s->state == TRANS_DEFAULT ||
900 : : s->state == TRANS_COMMIT ||
901 : : s->state == TRANS_ABORT ||
902 : : s->state == TRANS_PREPARE);
903 : :
904 [ + + ]: 1329835 : if (xactStopTimestamp == 0)
905 : 389806 : xactStopTimestamp = GetCurrentTimestamp();
906 : :
907 : 1329835 : return xactStopTimestamp;
908 : : }
909 : :
910 : : /*
911 : : * SetCurrentStatementStartTimestamp
912 : : *
913 : : * In a parallel worker, this should already have been provided by a call
914 : : * to SetParallelStartTimestamps().
915 : : */
916 : : void
917 : 785025 : SetCurrentStatementStartTimestamp(void)
918 : : {
919 [ + + ]: 785025 : if (!IsParallelWorker())
920 : 782977 : stmtStartTimestamp = GetCurrentTimestamp();
921 : : else
922 : : Assert(stmtStartTimestamp != 0);
923 : 785025 : }
924 : :
925 : : /*
926 : : * GetCurrentTransactionNestLevel
927 : : *
928 : : * Note: this will return zero when not inside any transaction, one when
929 : : * inside a top-level transaction, etc.
930 : : */
931 : : int
932 : 27209873 : GetCurrentTransactionNestLevel(void)
933 : : {
934 : 27209873 : TransactionState s = CurrentTransactionState;
935 : :
936 : 27209873 : return s->nestingLevel;
937 : : }
938 : :
939 : :
940 : : /*
941 : : * TransactionIdIsCurrentTransactionId
942 : : */
943 : : bool
944 : 67126261 : TransactionIdIsCurrentTransactionId(TransactionId xid)
945 : : {
946 : : TransactionState s;
947 : :
948 : : /*
949 : : * We always say that BootstrapTransactionId is "not my transaction ID"
950 : : * even when it is (ie, during bootstrap). Along with the fact that
951 : : * transam.c always treats BootstrapTransactionId as already committed,
952 : : * this causes the heapam_visibility.c routines to see all tuples as
953 : : * committed, which is what we need during bootstrap. (Bootstrap mode
954 : : * only inserts tuples, it never updates or deletes them, so all tuples
955 : : * can be presumed good immediately.)
956 : : *
957 : : * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
958 : : * not my transaction ID, so we can just return "false" immediately for
959 : : * any non-normal XID.
960 : : */
961 [ + + ]: 67126261 : if (!TransactionIdIsNormal(xid))
962 : 783873 : return false;
963 : :
964 [ + + ]: 66342388 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
965 : 38920455 : return true;
966 : :
967 : : /*
968 : : * In parallel workers, the XIDs we must consider as current are stored in
969 : : * ParallelCurrentXids rather than the transaction-state stack. Note that
970 : : * the XIDs in this array are sorted numerically rather than according to
971 : : * transactionIdPrecedes order.
972 : : */
973 [ + + ]: 27421933 : if (nParallelCurrentXids > 0)
974 : : {
975 : : int low,
976 : : high;
977 : :
978 : 2503343 : low = 0;
979 : 2503343 : high = nParallelCurrentXids - 1;
980 [ + + ]: 9753760 : while (low <= high)
981 : : {
982 : : int middle;
983 : : TransactionId probe;
984 : :
985 : 9624012 : middle = low + (high - low) / 2;
986 : 9624012 : probe = ParallelCurrentXids[middle];
987 [ + + ]: 9624012 : if (probe == xid)
988 : 2373595 : return true;
989 [ + + ]: 7250417 : else if (probe < xid)
990 : 7120674 : low = middle + 1;
991 : : else
992 : 129743 : high = middle - 1;
993 : : }
994 : 129748 : return false;
995 : : }
996 : :
997 : : /*
998 : : * We will return true for the Xid of the current subtransaction, any of
999 : : * its subcommitted children, any of its parents, or any of their
1000 : : * previously subcommitted children. However, a transaction being aborted
1001 : : * is no longer "current", even though it may still have an entry on the
1002 : : * state stack.
1003 : : */
1004 [ + + ]: 49795022 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
1005 : : {
1006 : : int low,
1007 : : high;
1008 : :
1009 [ - + ]: 25000363 : if (s->state == TRANS_ABORT)
1010 : 0 : continue;
1011 [ + + ]: 25000363 : if (!FullTransactionIdIsValid(s->fullTransactionId))
1012 : 11800860 : continue; /* it can't have any child XIDs either */
1013 [ + + ]: 13199503 : if (TransactionIdEquals(xid, XidFromFullTransactionId(s->fullTransactionId)))
1014 : 122356 : return true;
1015 : : /* As the childXids array is ordered, we can use binary search */
1016 : 13077147 : low = 0;
1017 : 13077147 : high = s->nChildXids - 1;
1018 [ + + ]: 13078058 : while (low <= high)
1019 : : {
1020 : : int middle;
1021 : : TransactionId probe;
1022 : :
1023 : 2486 : middle = low + (high - low) / 2;
1024 : 2486 : probe = s->childXids[middle];
1025 [ + + ]: 2486 : if (TransactionIdEquals(probe, xid))
1026 : 1575 : return true;
1027 [ + + ]: 911 : else if (TransactionIdPrecedes(probe, xid))
1028 : 803 : low = middle + 1;
1029 : : else
1030 : 108 : high = middle - 1;
1031 : : }
1032 : : }
1033 : :
1034 : 24794659 : return false;
1035 : : }
1036 : :
1037 : : /*
1038 : : * TransactionStartedDuringRecovery
1039 : : *
1040 : : * Returns true if the current transaction started while recovery was still
1041 : : * in progress. Recovery might have ended since so RecoveryInProgress() might
1042 : : * return false already.
1043 : : */
1044 : : bool
1045 : 10521652 : TransactionStartedDuringRecovery(void)
1046 : : {
1047 : 10521652 : return CurrentTransactionState->startedInRecovery;
1048 : : }
1049 : :
1050 : : /*
1051 : : * GetTopReadOnlyTransactionNestLevel
1052 : : *
1053 : : * Note: this will return zero when not inside any transaction or when neither
1054 : : * a top-level transaction nor subtransactions are read-only, one when the
1055 : : * top-level transaction is read-only, two when one level of subtransaction is
1056 : : * read-only, etc.
1057 : : *
1058 : : * Note: subtransactions of the topmost read-only transaction are also
1059 : : * read-only, because they inherit read-only mode from the transaction, and
1060 : : * thus can't change to read-write mode (see check_transaction_read_only).
1061 : : */
1062 : : int
1063 : 9 : GetTopReadOnlyTransactionNestLevel(void)
1064 : : {
1065 : 9 : TransactionState s = CurrentTransactionState;
1066 : :
1067 [ - + ]: 9 : if (!XactReadOnly)
1068 : 0 : return 0;
1069 [ + + ]: 10 : while (s->nestingLevel > 1)
1070 : : {
1071 [ + + ]: 4 : if (!s->prevXactReadOnly)
1072 : 3 : return s->nestingLevel;
1073 : 1 : s = s->parent;
1074 : : }
1075 : 6 : return s->nestingLevel;
1076 : : }
1077 : :
1078 : : /*
1079 : : * EnterParallelMode
1080 : : */
1081 : : void
1082 : 4745 : EnterParallelMode(void)
1083 : : {
1084 : 4745 : TransactionState s = CurrentTransactionState;
1085 : :
1086 : : Assert(s->parallelModeLevel >= 0);
1087 : :
1088 : 4745 : ++s->parallelModeLevel;
1089 : 4745 : }
1090 : :
1091 : : /*
1092 : : * ExitParallelMode
1093 : : */
1094 : : void
1095 : 2683 : ExitParallelMode(void)
1096 : : {
1097 : 2683 : TransactionState s = CurrentTransactionState;
1098 : :
1099 : : Assert(s->parallelModeLevel > 0);
1100 : : Assert(s->parallelModeLevel > 1 || s->parallelChildXact ||
1101 : : !ParallelContextActive());
1102 : :
1103 : 2683 : --s->parallelModeLevel;
1104 : 2683 : }
1105 : :
1106 : : /*
1107 : : * IsInParallelMode
1108 : : *
1109 : : * Are we in a parallel operation, as either the leader or a worker? Check
1110 : : * this to prohibit operations that change backend-local state expected to
1111 : : * match across all workers. Mere caches usually don't require such a
1112 : : * restriction. State modified in a strict push/pop fashion, such as the
1113 : : * active snapshot stack, is often fine.
1114 : : *
1115 : : * We say we are in parallel mode if we are in a subxact of a transaction
1116 : : * that's initiated a parallel operation; for most purposes that context
1117 : : * has all the same restrictions.
1118 : : */
1119 : : bool
1120 : 32541380 : IsInParallelMode(void)
1121 : : {
1122 : 32541380 : TransactionState s = CurrentTransactionState;
1123 : :
1124 [ + + + + ]: 32541380 : return s->parallelModeLevel != 0 || s->parallelChildXact;
1125 : : }
1126 : :
1127 : : /*
1128 : : * CommandCounterIncrement
1129 : : */
1130 : : void
1131 : 2015821 : CommandCounterIncrement(void)
1132 : : {
1133 : : /*
1134 : : * If the current value of the command counter hasn't been "used" to mark
1135 : : * tuples, we need not increment it, since there's no need to distinguish
1136 : : * a read-only command from others. This helps postpone command counter
1137 : : * overflow, and keeps no-op CommandCounterIncrement operations cheap.
1138 : : */
1139 [ + + ]: 2015821 : if (currentCommandIdUsed)
1140 : : {
1141 : : /*
1142 : : * Workers synchronize transaction state at the beginning of each
1143 : : * parallel operation, so we can't account for new commands after that
1144 : : * point.
1145 : : */
1146 [ + - - + ]: 750917 : if (IsInParallelMode() || IsParallelWorker())
1147 [ # # ]: 0 : ereport(ERROR,
1148 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1149 : : errmsg("cannot start commands during a parallel operation")));
1150 : :
1151 : 750917 : currentCommandId += 1;
1152 [ - + ]: 750917 : if (currentCommandId == InvalidCommandId)
1153 : : {
1154 : 0 : currentCommandId -= 1;
1155 [ # # ]: 0 : ereport(ERROR,
1156 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1157 : : errmsg("cannot have more than 2^32-2 commands in a transaction")));
1158 : : }
1159 : 750917 : currentCommandIdUsed = false;
1160 : :
1161 : : /* Propagate new command ID into static snapshots */
1162 : 750917 : SnapshotSetCommandId(currentCommandId);
1163 : :
1164 : : /*
1165 : : * Make any catalog changes done by the just-completed command visible
1166 : : * in the local syscache. We obviously don't need to do this after a
1167 : : * read-only command. (But see hacks in inval.c to make real sure we
1168 : : * don't think a command that queued inval messages was read-only.)
1169 : : */
1170 : 750917 : AtCCI_LocalCache();
1171 : : }
1172 : 2015817 : }
1173 : :
1174 : : /*
1175 : : * ForceSyncCommit
1176 : : *
1177 : : * Interface routine to allow commands to force a synchronous commit of the
1178 : : * current top-level transaction. Currently, two-phase commit does not
1179 : : * persist and restore this variable. So long as all callers use
1180 : : * PreventInTransactionBlock(), that omission has no consequences.
1181 : : */
1182 : : void
1183 : 627 : ForceSyncCommit(void)
1184 : : {
1185 : 627 : forceSyncCommit = true;
1186 : 627 : }
1187 : :
1188 : :
1189 : : /* ----------------------------------------------------------------
1190 : : * StartTransaction stuff
1191 : : * ----------------------------------------------------------------
1192 : : */
1193 : :
1194 : : /*
1195 : : * AtStart_Cache
1196 : : */
1197 : : static void
1198 : 661244 : AtStart_Cache(void)
1199 : : {
1200 : 661244 : AcceptInvalidationMessages();
1201 : 661244 : }
1202 : :
1203 : : /*
1204 : : * AtStart_Memory
1205 : : */
1206 : : static void
1207 : 661244 : AtStart_Memory(void)
1208 : : {
1209 : 661244 : TransactionState s = CurrentTransactionState;
1210 : :
1211 : : /*
1212 : : * Remember the memory context that was active prior to transaction start.
1213 : : */
1214 : 661244 : s->priorContext = CurrentMemoryContext;
1215 : :
1216 : : /*
1217 : : * If this is the first time through, create a private context for
1218 : : * AbortTransaction to work in. By reserving some space now, we can
1219 : : * insulate AbortTransaction from out-of-memory scenarios. Like
1220 : : * ErrorContext, we set it up with slow growth rate and a nonzero minimum
1221 : : * size, so that space will be reserved immediately.
1222 : : */
1223 [ + + ]: 661244 : if (TransactionAbortContext == NULL)
1224 : 21737 : TransactionAbortContext =
1225 : 21737 : AllocSetContextCreate(TopMemoryContext,
1226 : : "TransactionAbortContext",
1227 : : 32 * 1024,
1228 : : 32 * 1024,
1229 : : 32 * 1024);
1230 : :
1231 : : /*
1232 : : * Likewise, if this is the first time through, create a top-level context
1233 : : * for transaction-local data. This context will be reset at transaction
1234 : : * end, and then re-used in later transactions.
1235 : : */
1236 [ + + ]: 661244 : if (TopTransactionContext == NULL)
1237 : 21737 : TopTransactionContext =
1238 : 21737 : AllocSetContextCreate(TopMemoryContext,
1239 : : "TopTransactionContext",
1240 : : ALLOCSET_DEFAULT_SIZES);
1241 : :
1242 : : /*
1243 : : * In a top-level transaction, CurTransactionContext is the same as
1244 : : * TopTransactionContext.
1245 : : */
1246 : 661244 : CurTransactionContext = TopTransactionContext;
1247 : 661244 : s->curTransactionContext = CurTransactionContext;
1248 : :
1249 : : /* Make the CurTransactionContext active. */
1250 : 661244 : MemoryContextSwitchTo(CurTransactionContext);
1251 : 661244 : }
1252 : :
1253 : : /*
1254 : : * AtStart_ResourceOwner
1255 : : */
1256 : : static void
1257 : 661244 : AtStart_ResourceOwner(void)
1258 : : {
1259 : 661244 : TransactionState s = CurrentTransactionState;
1260 : :
1261 : : /*
1262 : : * We shouldn't have a transaction resource owner already.
1263 : : */
1264 : : Assert(TopTransactionResourceOwner == NULL);
1265 : :
1266 : : /*
1267 : : * Create a toplevel resource owner for the transaction.
1268 : : */
1269 : 661244 : s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1270 : :
1271 : 661244 : TopTransactionResourceOwner = s->curTransactionOwner;
1272 : 661244 : CurTransactionResourceOwner = s->curTransactionOwner;
1273 : 661244 : CurrentResourceOwner = s->curTransactionOwner;
1274 : 661244 : }
1275 : :
1276 : : /* ----------------------------------------------------------------
1277 : : * StartSubTransaction stuff
1278 : : * ----------------------------------------------------------------
1279 : : */
1280 : :
1281 : : /*
1282 : : * AtSubStart_Memory
1283 : : */
1284 : : static void
1285 : 23110 : AtSubStart_Memory(void)
1286 : : {
1287 : 23110 : TransactionState s = CurrentTransactionState;
1288 : :
1289 : : Assert(CurTransactionContext != NULL);
1290 : :
1291 : : /*
1292 : : * Remember the context that was active prior to subtransaction start.
1293 : : */
1294 : 23110 : s->priorContext = CurrentMemoryContext;
1295 : :
1296 : : /*
1297 : : * Create a CurTransactionContext, which will be used to hold data that
1298 : : * survives subtransaction commit but disappears on subtransaction abort.
1299 : : * We make it a child of the immediate parent's CurTransactionContext.
1300 : : */
1301 : 23110 : CurTransactionContext = AllocSetContextCreate(CurTransactionContext,
1302 : : "CurTransactionContext",
1303 : : ALLOCSET_DEFAULT_SIZES);
1304 : 23110 : s->curTransactionContext = CurTransactionContext;
1305 : :
1306 : : /* Make the CurTransactionContext active. */
1307 : 23110 : MemoryContextSwitchTo(CurTransactionContext);
1308 : 23110 : }
1309 : :
1310 : : /*
1311 : : * AtSubStart_ResourceOwner
1312 : : */
1313 : : static void
1314 : 23110 : AtSubStart_ResourceOwner(void)
1315 : : {
1316 : 23110 : TransactionState s = CurrentTransactionState;
1317 : :
1318 : : Assert(s->parent != NULL);
1319 : :
1320 : : /*
1321 : : * Create a resource owner for the subtransaction. We make it a child of
1322 : : * the immediate parent's resource owner.
1323 : : */
1324 : 23110 : s->curTransactionOwner =
1325 : 23110 : ResourceOwnerCreate(s->parent->curTransactionOwner,
1326 : : "SubTransaction");
1327 : :
1328 : 23110 : CurTransactionResourceOwner = s->curTransactionOwner;
1329 : 23110 : CurrentResourceOwner = s->curTransactionOwner;
1330 : 23110 : }
1331 : :
1332 : : /* ----------------------------------------------------------------
1333 : : * CommitTransaction stuff
1334 : : * ----------------------------------------------------------------
1335 : : */
1336 : :
1337 : : /*
1338 : : * RecordTransactionCommit
1339 : : *
1340 : : * Returns latest XID among xact and its children, or InvalidTransactionId
1341 : : * if the xact has no XID. (We compute that here just because it's easier.)
1342 : : *
1343 : : * If you change this function, see RecordTransactionCommitPrepared also.
1344 : : */
1345 : : static TransactionId
1346 : 621696 : RecordTransactionCommit(void)
1347 : : {
1348 : 621696 : TransactionId xid = GetTopTransactionIdIfAny();
1349 : 621696 : bool markXidCommitted = TransactionIdIsValid(xid);
1350 : 621696 : TransactionId latestXid = InvalidTransactionId;
1351 : : int nrels;
1352 : : RelFileLocator *rels;
1353 : : int nchildren;
1354 : : TransactionId *children;
1355 : 621696 : int ndroppedstats = 0;
1356 : 621696 : xl_xact_stats_item *droppedstats = NULL;
1357 : 621696 : int nmsgs = 0;
1358 : 621696 : SharedInvalidationMessage *invalMessages = NULL;
1359 : 621696 : bool RelcacheInitFileInval = false;
1360 : : bool wrote_xlog;
1361 : :
1362 : : /*
1363 : : * Log pending invalidations for logical decoding of in-progress
1364 : : * transactions. Normally for DDLs, we log this at each command end,
1365 : : * however, for certain cases where we directly update the system table
1366 : : * without a transaction block, the invalidations are not logged till this
1367 : : * time.
1368 : : */
1369 [ + + + + ]: 621696 : if (XLogLogicalInfoActive())
1370 : 15521 : LogLogicalInvalidations();
1371 : :
1372 : : /* Get data needed for commit record */
1373 : 621696 : nrels = smgrGetPendingDeletes(true, &rels);
1374 : 621696 : nchildren = xactGetCommittedChildren(&children);
1375 : 621696 : ndroppedstats = pgstat_get_transactional_drops(true, &droppedstats);
1376 [ + + ]: 621696 : if (XLogStandbyInfoActive())
1377 : 336759 : nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
1378 : : &RelcacheInitFileInval);
1379 : 621696 : wrote_xlog = (XactLastRecEnd != 0);
1380 : :
1381 : : /* Load the injection point before entering the critical section */
1382 : 621696 : INJECTION_POINT_LOAD("commit-before-clog-update");
1383 : :
1384 : : /*
1385 : : * If we haven't been assigned an XID yet, we neither can, nor do we want
1386 : : * to write a COMMIT record.
1387 : : */
1388 [ + + ]: 621696 : if (!markXidCommitted)
1389 : : {
1390 : : /*
1391 : : * We expect that every RelationDropStorage is followed by a catalog
1392 : : * update, and hence XID assignment, so we shouldn't get here with any
1393 : : * pending deletes. Same is true for dropping stats.
1394 : : *
1395 : : * Use a real test not just an Assert to check this, since it's a bit
1396 : : * fragile.
1397 : : */
1398 [ + - - + ]: 457941 : if (nrels != 0 || ndroppedstats != 0)
1399 [ # # ]: 0 : elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
1400 : :
1401 : : /* Can't have child XIDs either; AssignTransactionId enforces this */
1402 : : Assert(nchildren == 0);
1403 : :
1404 : : /*
1405 : : * Transactions without an assigned xid can contain invalidation
1406 : : * messages. While inplace updates do this, this is not known to be
1407 : : * necessary; see comment at inplace CacheInvalidateHeapTuple().
1408 : : * Extensions might still rely on this capability, and standbys may
1409 : : * need to process those invals. We can't emit a commit record
1410 : : * without an xid, and we don't want to force assigning an xid,
1411 : : * because that'd be problematic for e.g. vacuum. Hence we emit a
1412 : : * bespoke record for the invalidations. We don't want to use that in
1413 : : * case a commit record is emitted, so they happen synchronously with
1414 : : * commits (besides not wanting to emit more WAL records).
1415 : : *
1416 : : * XXX Every known use of this capability is a defect. Since an XID
1417 : : * isn't controlling visibility of the change that prompted invals,
1418 : : * other sessions need the inval even if this transactions aborts.
1419 : : *
1420 : : * ON COMMIT DELETE ROWS does a nontransactional index_build(), which
1421 : : * queues a relcache inval, including in transactions without an xid
1422 : : * that had read the (empty) table. Standbys don't need any ON COMMIT
1423 : : * DELETE ROWS invals, but we've not done the work to withhold them.
1424 : : */
1425 [ + + ]: 457941 : if (nmsgs != 0)
1426 : : {
1427 : 11634 : LogStandbyInvalidations(nmsgs, invalMessages,
1428 : : RelcacheInitFileInval);
1429 : 11634 : wrote_xlog = true; /* not strictly necessary */
1430 : : }
1431 : :
1432 : : /*
1433 : : * If we didn't create XLOG entries, we're done here; otherwise we
1434 : : * should trigger flushing those entries the same as a commit record
1435 : : * would. This will primarily happen for HOT pruning and the like; we
1436 : : * want these to be flushed to disk in due time.
1437 : : */
1438 [ + + ]: 457941 : if (!wrote_xlog)
1439 : 410781 : goto cleanup;
1440 : : }
1441 : : else
1442 : : {
1443 : : bool replorigin;
1444 : :
1445 : : /*
1446 : : * Are we using the replication origins feature? Or, in other words,
1447 : : * are we replaying remote actions?
1448 : : */
1449 [ + + ]: 164858 : replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
1450 [ + - ]: 1103 : replorigin_xact_state.origin != DoNotReplicateId);
1451 : :
1452 : : /*
1453 : : * Mark ourselves as within our "commit critical section". This
1454 : : * forces any concurrent checkpoint to wait until we've updated
1455 : : * pg_xact. Without this, it is possible for the checkpoint to set
1456 : : * REDO after the XLOG record but fail to flush the pg_xact update to
1457 : : * disk, leading to loss of the transaction commit if the system
1458 : : * crashes a little later.
1459 : : *
1460 : : * Note: we could, but don't bother to, set this flag in
1461 : : * RecordTransactionAbort. That's because loss of a transaction abort
1462 : : * is noncritical; the presumption would be that it aborted, anyway.
1463 : : *
1464 : : * It's safe to change the delayChkptFlags flag of our own backend
1465 : : * without holding the ProcArrayLock, since we're the only one
1466 : : * modifying it. This makes checkpoint's determination of which xacts
1467 : : * are delaying the checkpoint a bit fuzzy, but it doesn't matter.
1468 : : *
1469 : : * Note, it is important to get the commit timestamp after marking the
1470 : : * transaction in the commit critical section. See
1471 : : * RecordTransactionCommitPrepared.
1472 : : */
1473 : : Assert((MyProc->delayChkptFlags & DELAY_CHKPT_IN_COMMIT) == 0);
1474 : 163755 : START_CRIT_SECTION();
1475 : 163755 : MyProc->delayChkptFlags |= DELAY_CHKPT_IN_COMMIT;
1476 : :
1477 : : Assert(xactStopTimestamp == 0);
1478 : :
1479 : : /*
1480 : : * Ensures the DELAY_CHKPT_IN_COMMIT flag write is globally visible
1481 : : * before commit time is written.
1482 : : */
1483 : 163755 : pg_write_barrier();
1484 : :
1485 : : /*
1486 : : * Insert the commit XLOG record.
1487 : : */
1488 : 163755 : XactLogCommitRecord(GetCurrentTransactionStopTimestamp(),
1489 : : nchildren, children, nrels, rels,
1490 : : ndroppedstats, droppedstats,
1491 : : nmsgs, invalMessages,
1492 : : RelcacheInitFileInval,
1493 : : MyXactFlags,
1494 : : InvalidTransactionId, NULL /* plain commit */ );
1495 : :
1496 [ + + ]: 163755 : if (replorigin)
1497 : : /* Move LSNs forward for this replication origin */
1498 : 1103 : replorigin_session_advance(replorigin_xact_state.origin_lsn,
1499 : : XactLastRecEnd);
1500 : :
1501 : : /*
1502 : : * Record commit timestamp. The value comes from plain commit
1503 : : * timestamp if there's no replication origin; otherwise, the
1504 : : * timestamp was already set in replorigin_xact_state.origin_timestamp
1505 : : * by replication.
1506 : : *
1507 : : * We don't need to WAL-log anything here, as the commit record
1508 : : * written above already contains the data.
1509 : : */
1510 : :
1511 [ + + + + ]: 163755 : if (!replorigin || replorigin_xact_state.origin_timestamp == 0)
1512 : 162768 : replorigin_xact_state.origin_timestamp = GetCurrentTransactionStopTimestamp();
1513 : :
1514 : 163755 : TransactionTreeSetCommitTsData(xid, nchildren, children,
1515 : : replorigin_xact_state.origin_timestamp,
1516 : 163755 : replorigin_xact_state.origin);
1517 : : }
1518 : :
1519 : : /*
1520 : : * Check if we want to commit asynchronously. We can allow the XLOG flush
1521 : : * to happen asynchronously if synchronous_commit=off, or if the current
1522 : : * transaction has not performed any WAL-logged operation or didn't assign
1523 : : * an xid. The transaction can end up not writing any WAL, even if it has
1524 : : * an xid, if it only wrote to temporary and/or unlogged tables. It can
1525 : : * end up having written WAL without an xid if it did HOT pruning. In
1526 : : * case of a crash, the loss of such a transaction will be irrelevant;
1527 : : * temp tables will be lost anyway, unlogged tables will be truncated and
1528 : : * HOT pruning will be done again later. (Given the foregoing, you might
1529 : : * think that it would be unnecessary to emit the XLOG record at all in
1530 : : * this case, but we don't currently try to do that. It would certainly
1531 : : * cause problems at least in Hot Standby mode, where the
1532 : : * KnownAssignedXids machinery requires tracking every XID assignment. It
1533 : : * might be OK to skip it only when wal_level < replica, but for now we
1534 : : * don't.)
1535 : : *
1536 : : * However, if we're doing cleanup of any non-temp rels or committing any
1537 : : * command that wanted to force sync commit, then we must flush XLOG
1538 : : * immediately. (We must not allow asynchronous commit if there are any
1539 : : * non-temp tables to be deleted, because we might delete the files before
1540 : : * the COMMIT record is flushed to disk. We do allow asynchronous commit
1541 : : * if all to-be-deleted tables are temporary though, since they are lost
1542 : : * anyway if we crash.)
1543 : : */
1544 [ + + + + ]: 210915 : if ((wrote_xlog && markXidCommitted &&
1545 [ + + + + ]: 210915 : synchronous_commit > SYNCHRONOUS_COMMIT_OFF) ||
1546 [ + + ]: 54566 : forceSyncCommit || nrels > 0)
1547 : : {
1548 : 156370 : XLogFlush(XactLastRecEnd);
1549 : :
1550 : : /*
1551 : : * The commit record is on disk, but not in CLOG yet. A test can stop
1552 : : * here to see what others make of the transaction meanwhile.
1553 : : */
1554 : 156370 : INJECTION_POINT_CACHED("commit-before-clog-update", NULL);
1555 : :
1556 : : /*
1557 : : * Now we may update the CLOG, if we wrote a COMMIT record above
1558 : : */
1559 [ + - ]: 156370 : if (markXidCommitted)
1560 : 156370 : TransactionIdCommitTree(xid, nchildren, children);
1561 : : }
1562 : : else
1563 : : {
1564 : : /*
1565 : : * Asynchronous commit case:
1566 : : *
1567 : : * This enables possible committed transaction loss in the case of a
1568 : : * postmaster crash because WAL buffers are left unwritten. Ideally we
1569 : : * could issue the WAL write without the fsync, but some
1570 : : * wal_sync_methods do not allow separate write/fsync.
1571 : : *
1572 : : * Report the latest async commit LSN, so that the WAL writer knows to
1573 : : * flush this commit.
1574 : : */
1575 : 54545 : XLogSetAsyncXactLSN(XactLastRecEnd);
1576 : :
1577 : : /*
1578 : : * We must not immediately update the CLOG, since we didn't flush the
1579 : : * XLOG. Instead, we store the LSN up to which the XLOG must be
1580 : : * flushed before the CLOG may be updated.
1581 : : */
1582 [ + + ]: 54545 : if (markXidCommitted)
1583 : 7385 : TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1584 : : }
1585 : :
1586 : : /*
1587 : : * If we entered a commit critical section, leave it now, and let
1588 : : * checkpoints proceed.
1589 : : */
1590 [ + + ]: 210915 : if (markXidCommitted)
1591 : : {
1592 : 163755 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_IN_COMMIT;
1593 : 163755 : END_CRIT_SECTION();
1594 : : }
1595 : :
1596 : : /* Compute latestXid while we have the child XIDs handy */
1597 : 210915 : latestXid = TransactionIdLatest(xid, nchildren, children);
1598 : :
1599 : : /*
1600 : : * Wait for synchronous replication, if required. Similar to the decision
1601 : : * above about using committing asynchronously we only want to wait if
1602 : : * this backend assigned an xid and wrote WAL. No need to wait if an xid
1603 : : * was assigned due to temporary/unlogged tables or due to HOT pruning.
1604 : : *
1605 : : * Note that at this stage we have marked clog, but still show as running
1606 : : * in the procarray and continue to hold locks.
1607 : : */
1608 [ + + + + ]: 210915 : if (wrote_xlog && markXidCommitted)
1609 : 158988 : SyncRepWaitForLSN(XactLastRecEnd, true);
1610 : :
1611 : : /* remember end of last commit record */
1612 : 210915 : XactLastCommitEnd = XactLastRecEnd;
1613 : :
1614 : : /* Reset XactLastRecEnd until the next transaction writes something */
1615 : 210915 : XactLastRecEnd = 0;
1616 : 621696 : cleanup:
1617 : : /* Clean up local data */
1618 [ + + ]: 621696 : if (rels)
1619 : 13027 : pfree(rels);
1620 [ + + ]: 621696 : if (ndroppedstats)
1621 : 16098 : pfree(droppedstats);
1622 : :
1623 : 621696 : return latestXid;
1624 : : }
1625 : :
1626 : :
1627 : : /*
1628 : : * AtCCI_LocalCache
1629 : : */
1630 : : static void
1631 : 750917 : AtCCI_LocalCache(void)
1632 : : {
1633 : : /*
1634 : : * Make any pending relation map changes visible. We must do this before
1635 : : * processing local sinval messages, so that the map changes will get
1636 : : * reflected into the relcache when relcache invals are processed.
1637 : : */
1638 : 750917 : AtCCI_RelationMap();
1639 : :
1640 : : /*
1641 : : * Make catalog changes visible to me for the next command.
1642 : : */
1643 : 750917 : CommandEndInvalidationMessages();
1644 : 750913 : }
1645 : :
1646 : : /*
1647 : : * AtCommit_Memory
1648 : : */
1649 : : static void
1650 : 624048 : AtCommit_Memory(void)
1651 : : {
1652 : 624048 : TransactionState s = CurrentTransactionState;
1653 : :
1654 : : /*
1655 : : * Return to the memory context that was current before we started the
1656 : : * transaction. (In principle, this could not be any of the contexts we
1657 : : * are about to delete. If it somehow is, assertions in mcxt.c will
1658 : : * complain.)
1659 : : */
1660 : 624048 : MemoryContextSwitchTo(s->priorContext);
1661 : :
1662 : : /*
1663 : : * Release all transaction-local memory. TopTransactionContext survives
1664 : : * but becomes empty; any sub-contexts go away.
1665 : : */
1666 : : Assert(TopTransactionContext != NULL);
1667 : 624048 : MemoryContextReset(TopTransactionContext);
1668 : :
1669 : : /*
1670 : : * Clear these pointers as a pro-forma matter. (Notionally, while
1671 : : * TopTransactionContext still exists, it's currently not associated with
1672 : : * this TransactionState struct.)
1673 : : */
1674 : 624048 : CurTransactionContext = NULL;
1675 : 624048 : s->curTransactionContext = NULL;
1676 : 624048 : }
1677 : :
1678 : : /* ----------------------------------------------------------------
1679 : : * CommitSubTransaction stuff
1680 : : * ----------------------------------------------------------------
1681 : : */
1682 : :
1683 : : /*
1684 : : * AtSubCommit_Memory
1685 : : */
1686 : : static void
1687 : 17407 : AtSubCommit_Memory(void)
1688 : : {
1689 : 17407 : TransactionState s = CurrentTransactionState;
1690 : :
1691 : : Assert(s->parent != NULL);
1692 : :
1693 : : /* Return to parent transaction level's memory context. */
1694 : 17407 : CurTransactionContext = s->parent->curTransactionContext;
1695 : 17407 : MemoryContextSwitchTo(CurTransactionContext);
1696 : :
1697 : : /*
1698 : : * Ordinarily we cannot throw away the child's CurTransactionContext,
1699 : : * since the data it contains will be needed at upper commit. However, if
1700 : : * there isn't actually anything in it, we can throw it away. This avoids
1701 : : * a small memory leak in the common case of "trivial" subxacts.
1702 : : */
1703 [ + + ]: 17407 : if (MemoryContextIsEmpty(s->curTransactionContext))
1704 : : {
1705 : 17380 : MemoryContextDelete(s->curTransactionContext);
1706 : 17380 : s->curTransactionContext = NULL;
1707 : : }
1708 : 17407 : }
1709 : :
1710 : : /*
1711 : : * AtSubCommit_childXids
1712 : : *
1713 : : * Pass my own XID and my child XIDs up to my parent as committed children.
1714 : : */
1715 : : static void
1716 : 15466 : AtSubCommit_childXids(void)
1717 : : {
1718 : 15466 : TransactionState s = CurrentTransactionState;
1719 : : int new_nChildXids;
1720 : :
1721 : : Assert(s->parent != NULL);
1722 : :
1723 : : /*
1724 : : * The parent childXids array will need to hold my XID and all my
1725 : : * childXids, in addition to the XIDs already there.
1726 : : */
1727 : 15466 : new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1728 : :
1729 : : /* Allocate or enlarge the parent array if necessary */
1730 [ + + ]: 15466 : if (s->parent->maxChildXids < new_nChildXids)
1731 : : {
1732 : : int new_maxChildXids;
1733 : : TransactionId *new_childXids;
1734 : :
1735 : : /*
1736 : : * Make it 2x what's needed right now, to avoid having to enlarge it
1737 : : * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1738 : : * is what ensures that we don't need to worry about integer overflow
1739 : : * here or in the calculation of new_nChildXids.)
1740 : : */
1741 : 1722 : new_maxChildXids = Min(new_nChildXids * 2,
1742 : : (int) (MaxAllocSize / sizeof(TransactionId)));
1743 : :
1744 [ - + ]: 1722 : if (new_maxChildXids < new_nChildXids)
1745 [ # # ]: 0 : ereport(ERROR,
1746 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1747 : : errmsg("maximum number of committed subtransactions (%d) exceeded",
1748 : : (int) (MaxAllocSize / sizeof(TransactionId)))));
1749 : :
1750 : : /*
1751 : : * We keep the child-XID arrays in TopTransactionContext; this avoids
1752 : : * setting up child-transaction contexts for what might be just a few
1753 : : * bytes of grandchild XIDs.
1754 : : */
1755 [ + + ]: 1722 : if (s->parent->childXids == NULL)
1756 : : new_childXids =
1757 : 1645 : MemoryContextAlloc(TopTransactionContext,
1758 : : new_maxChildXids * sizeof(TransactionId));
1759 : : else
1760 : 77 : new_childXids = repalloc_array(s->parent->childXids, TransactionId, new_maxChildXids);
1761 : :
1762 : 1722 : s->parent->childXids = new_childXids;
1763 : 1722 : s->parent->maxChildXids = new_maxChildXids;
1764 : : }
1765 : :
1766 : : /*
1767 : : * Copy all my XIDs to parent's array.
1768 : : *
1769 : : * Note: We rely on the fact that the XID of a child always follows that
1770 : : * of its parent. By copying the XID of this subtransaction before the
1771 : : * XIDs of its children, we ensure that the array stays ordered. Likewise,
1772 : : * all XIDs already in the array belong to subtransactions started and
1773 : : * subcommitted before us, so their XIDs must precede ours.
1774 : : */
1775 : 15466 : s->parent->childXids[s->parent->nChildXids] = XidFromFullTransactionId(s->fullTransactionId);
1776 : :
1777 [ + + ]: 15466 : if (s->nChildXids > 0)
1778 : 1022 : memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1779 : 1022 : s->childXids,
1780 : 1022 : s->nChildXids * sizeof(TransactionId));
1781 : :
1782 : 15466 : s->parent->nChildXids = new_nChildXids;
1783 : :
1784 : : /* Release child's array to avoid leakage */
1785 [ + + ]: 15466 : if (s->childXids != NULL)
1786 : 1022 : pfree(s->childXids);
1787 : : /* We must reset these to avoid double-free if fail later in commit */
1788 : 15466 : s->childXids = NULL;
1789 : 15466 : s->nChildXids = 0;
1790 : 15466 : s->maxChildXids = 0;
1791 : 15466 : }
1792 : :
1793 : : /* ----------------------------------------------------------------
1794 : : * AbortTransaction stuff
1795 : : * ----------------------------------------------------------------
1796 : : */
1797 : :
1798 : : /*
1799 : : * RecordTransactionAbort
1800 : : *
1801 : : * Returns latest XID among xact and its children, or InvalidTransactionId
1802 : : * if the xact has no XID. (We compute that here just because it's easier.)
1803 : : */
1804 : : static TransactionId
1805 : 42884 : RecordTransactionAbort(bool isSubXact)
1806 : : {
1807 : 42884 : TransactionId xid = GetCurrentTransactionIdIfAny();
1808 : : TransactionId latestXid;
1809 : : int nrels;
1810 : : RelFileLocator *rels;
1811 : 42884 : int ndroppedstats = 0;
1812 : 42884 : xl_xact_stats_item *droppedstats = NULL;
1813 : : int nchildren;
1814 : : TransactionId *children;
1815 : : TimestampTz xact_time;
1816 : : bool replorigin;
1817 : :
1818 : : /*
1819 : : * If we haven't been assigned an XID, nobody will care whether we aborted
1820 : : * or not. Hence, we're done in that case. It does not matter if we have
1821 : : * rels to delete (note that this routine is not responsible for actually
1822 : : * deleting 'em). We cannot have any child XIDs, either.
1823 : : */
1824 [ + + ]: 42884 : if (!TransactionIdIsValid(xid))
1825 : : {
1826 : : /* Reset XactLastRecEnd until the next transaction writes something */
1827 [ + + ]: 32812 : if (!isSubXact)
1828 : 28145 : XactLastRecEnd = 0;
1829 : 32812 : return InvalidTransactionId;
1830 : : }
1831 : :
1832 : : /*
1833 : : * We have a valid XID, so we should write an ABORT record for it.
1834 : : *
1835 : : * We do not flush XLOG to disk here, since the default assumption after a
1836 : : * crash would be that we aborted, anyway. For the same reason, we don't
1837 : : * need to worry about interlocking against checkpoint start.
1838 : : */
1839 : :
1840 : : /*
1841 : : * Check that we haven't aborted halfway through RecordTransactionCommit.
1842 : : */
1843 [ - + ]: 10072 : if (TransactionIdDidCommit(xid))
1844 [ # # ]: 0 : elog(PANIC, "cannot abort transaction %u, it was already committed",
1845 : : xid);
1846 : :
1847 : : /*
1848 : : * Are we using the replication origins feature? Or, in other words, are
1849 : : * we replaying remote actions?
1850 : : */
1851 [ + + ]: 10095 : replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
1852 [ + - ]: 23 : replorigin_xact_state.origin != DoNotReplicateId);
1853 : :
1854 : : /* Fetch the data we need for the abort record */
1855 : 10072 : nrels = smgrGetPendingDeletes(false, &rels);
1856 : 10072 : nchildren = xactGetCommittedChildren(&children);
1857 : 10072 : ndroppedstats = pgstat_get_transactional_drops(false, &droppedstats);
1858 : :
1859 : : /* XXX do we really need a critical section here? */
1860 : 10072 : START_CRIT_SECTION();
1861 : :
1862 : : /* Write the ABORT record */
1863 [ + + ]: 10072 : if (isSubXact)
1864 : 1036 : xact_time = GetCurrentTimestamp();
1865 : : else
1866 : : {
1867 : 9036 : xact_time = GetCurrentTransactionStopTimestamp();
1868 : : }
1869 : :
1870 : 10072 : XactLogAbortRecord(xact_time,
1871 : : nchildren, children,
1872 : : nrels, rels,
1873 : : ndroppedstats, droppedstats,
1874 : : MyXactFlags, InvalidTransactionId,
1875 : : NULL);
1876 : :
1877 [ + + ]: 10072 : if (replorigin)
1878 : : /* Move LSNs forward for this replication origin */
1879 : 23 : replorigin_session_advance(replorigin_xact_state.origin_lsn,
1880 : : XactLastRecEnd);
1881 : :
1882 : : /*
1883 : : * Report the latest async abort LSN, so that the WAL writer knows to
1884 : : * flush this abort. There's nothing to be gained by delaying this, since
1885 : : * WALWriter may as well do this when it can. This is important with
1886 : : * streaming replication because if we don't flush WAL regularly we will
1887 : : * find that large aborts leave us with a long backlog for when commits
1888 : : * occur after the abort, increasing our window of data loss should
1889 : : * problems occur at that point.
1890 : : */
1891 [ + + ]: 10072 : if (!isSubXact)
1892 : 9036 : XLogSetAsyncXactLSN(XactLastRecEnd);
1893 : :
1894 : : /*
1895 : : * Mark the transaction aborted in clog. This is not absolutely necessary
1896 : : * but we may as well do it while we are here; also, in the subxact case
1897 : : * it is helpful because XactLockTableWait makes use of it to avoid
1898 : : * waiting for already-aborted subtransactions. It is OK to do it without
1899 : : * having flushed the ABORT record to disk, because in event of a crash
1900 : : * we'd be assumed to have aborted anyway.
1901 : : */
1902 : 10072 : TransactionIdAbortTree(xid, nchildren, children);
1903 : :
1904 : 10072 : END_CRIT_SECTION();
1905 : :
1906 : : /* Compute latestXid while we have the child XIDs handy */
1907 : 10072 : latestXid = TransactionIdLatest(xid, nchildren, children);
1908 : :
1909 : : /*
1910 : : * If we're aborting a subtransaction, we can immediately remove failed
1911 : : * XIDs from PGPROC's cache of running child XIDs. We do that here for
1912 : : * subxacts, because we already have the child XID array at hand. For
1913 : : * main xacts, the equivalent happens just after this function returns.
1914 : : */
1915 [ + + ]: 10072 : if (isSubXact)
1916 : 1036 : XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1917 : :
1918 : : /* Reset XactLastRecEnd until the next transaction writes something */
1919 [ + + ]: 10072 : if (!isSubXact)
1920 : 9036 : XactLastRecEnd = 0;
1921 : :
1922 : : /* And clean up local data */
1923 [ + + ]: 10072 : if (rels)
1924 : 1568 : pfree(rels);
1925 [ + + ]: 10072 : if (ndroppedstats)
1926 : 2148 : pfree(droppedstats);
1927 : :
1928 : : /*
1929 : : * Test the window where the transaction is aborted in pg_xact but still
1930 : : * present in ProcArray.
1931 : : */
1932 : 10072 : INJECTION_POINT("transaction-abort-after-clog", NULL);
1933 : :
1934 : 10072 : return latestXid;
1935 : : }
1936 : :
1937 : : /*
1938 : : * AtAbort_Memory
1939 : : */
1940 : : static void
1941 : 59534 : AtAbort_Memory(void)
1942 : : {
1943 : : /*
1944 : : * Switch into TransactionAbortContext, which should have some free space
1945 : : * even if nothing else does. We'll work in this context until we've
1946 : : * finished cleaning up.
1947 : : *
1948 : : * It is barely possible to get here when we've not been able to create
1949 : : * TransactionAbortContext yet; if so use TopMemoryContext.
1950 : : */
1951 [ + - ]: 59534 : if (TransactionAbortContext != NULL)
1952 : 59534 : MemoryContextSwitchTo(TransactionAbortContext);
1953 : : else
1954 : 0 : MemoryContextSwitchTo(TopMemoryContext);
1955 : 59534 : }
1956 : :
1957 : : /*
1958 : : * AtSubAbort_Memory
1959 : : */
1960 : : static void
1961 : 5703 : AtSubAbort_Memory(void)
1962 : : {
1963 : : Assert(TransactionAbortContext != NULL);
1964 : :
1965 : 5703 : MemoryContextSwitchTo(TransactionAbortContext);
1966 : 5703 : }
1967 : :
1968 : :
1969 : : /*
1970 : : * AtAbort_ResourceOwner
1971 : : */
1972 : : static void
1973 : 37196 : AtAbort_ResourceOwner(void)
1974 : : {
1975 : : /*
1976 : : * Make sure we have a valid ResourceOwner, if possible (else it will be
1977 : : * NULL, which is OK)
1978 : : */
1979 : 37196 : CurrentResourceOwner = TopTransactionResourceOwner;
1980 : 37196 : }
1981 : :
1982 : : /*
1983 : : * AtSubAbort_ResourceOwner
1984 : : */
1985 : : static void
1986 : 5703 : AtSubAbort_ResourceOwner(void)
1987 : : {
1988 : 5703 : TransactionState s = CurrentTransactionState;
1989 : :
1990 : : /* Make sure we have a valid ResourceOwner */
1991 : 5703 : CurrentResourceOwner = s->curTransactionOwner;
1992 : 5703 : }
1993 : :
1994 : :
1995 : : /*
1996 : : * AtSubAbort_childXids
1997 : : */
1998 : : static void
1999 : 1036 : AtSubAbort_childXids(void)
2000 : : {
2001 : 1036 : TransactionState s = CurrentTransactionState;
2002 : :
2003 : : /*
2004 : : * We keep the child-XID arrays in TopTransactionContext (see
2005 : : * AtSubCommit_childXids). This means we'd better free the array
2006 : : * explicitly at abort to avoid leakage.
2007 : : */
2008 [ + + ]: 1036 : if (s->childXids != NULL)
2009 : 27 : pfree(s->childXids);
2010 : 1036 : s->childXids = NULL;
2011 : 1036 : s->nChildXids = 0;
2012 : 1036 : s->maxChildXids = 0;
2013 : :
2014 : : /*
2015 : : * We could prune the unreportedXids array here. But we don't bother. That
2016 : : * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
2017 : : * would likely introduce more CPU time into the more common paths, so we
2018 : : * choose not to do that.
2019 : : */
2020 : 1036 : }
2021 : :
2022 : : /* ----------------------------------------------------------------
2023 : : * CleanupTransaction stuff
2024 : : * ----------------------------------------------------------------
2025 : : */
2026 : :
2027 : : /*
2028 : : * AtCleanup_Memory
2029 : : */
2030 : : static void
2031 : 37196 : AtCleanup_Memory(void)
2032 : : {
2033 : 37196 : TransactionState s = CurrentTransactionState;
2034 : :
2035 : : /* Should be at top level */
2036 : : Assert(s->parent == NULL);
2037 : :
2038 : : /*
2039 : : * Return to the memory context that was current before we started the
2040 : : * transaction. (In principle, this could not be any of the contexts we
2041 : : * are about to delete. If it somehow is, assertions in mcxt.c will
2042 : : * complain.)
2043 : : */
2044 : 37196 : MemoryContextSwitchTo(s->priorContext);
2045 : :
2046 : : /*
2047 : : * Clear the special abort context for next time.
2048 : : */
2049 [ + - ]: 37196 : if (TransactionAbortContext != NULL)
2050 : 37196 : MemoryContextReset(TransactionAbortContext);
2051 : :
2052 : : /*
2053 : : * Release all transaction-local memory, the same as in AtCommit_Memory,
2054 : : * except we must cope with the possibility that we didn't get as far as
2055 : : * creating TopTransactionContext.
2056 : : */
2057 [ + - ]: 37196 : if (TopTransactionContext != NULL)
2058 : 37196 : MemoryContextReset(TopTransactionContext);
2059 : :
2060 : : /*
2061 : : * Clear these pointers as a pro-forma matter. (Notionally, while
2062 : : * TopTransactionContext still exists, it's currently not associated with
2063 : : * this TransactionState struct.)
2064 : : */
2065 : 37196 : CurTransactionContext = NULL;
2066 : 37196 : s->curTransactionContext = NULL;
2067 : 37196 : }
2068 : :
2069 : :
2070 : : /* ----------------------------------------------------------------
2071 : : * CleanupSubTransaction stuff
2072 : : * ----------------------------------------------------------------
2073 : : */
2074 : :
2075 : : /*
2076 : : * AtSubCleanup_Memory
2077 : : */
2078 : : static void
2079 : 5703 : AtSubCleanup_Memory(void)
2080 : : {
2081 : 5703 : TransactionState s = CurrentTransactionState;
2082 : :
2083 : : Assert(s->parent != NULL);
2084 : :
2085 : : /*
2086 : : * Return to the memory context that was current before we started the
2087 : : * subtransaction. (In principle, this could not be any of the contexts
2088 : : * we are about to delete. If it somehow is, assertions in mcxt.c will
2089 : : * complain.)
2090 : : */
2091 : 5703 : MemoryContextSwitchTo(s->priorContext);
2092 : :
2093 : : /* Update CurTransactionContext (might not be same as priorContext) */
2094 : 5703 : CurTransactionContext = s->parent->curTransactionContext;
2095 : :
2096 : : /*
2097 : : * Clear the special abort context for next time.
2098 : : */
2099 [ + - ]: 5703 : if (TransactionAbortContext != NULL)
2100 : 5703 : MemoryContextReset(TransactionAbortContext);
2101 : :
2102 : : /*
2103 : : * Delete the subxact local memory contexts. Its CurTransactionContext can
2104 : : * go too (note this also kills CurTransactionContexts from any children
2105 : : * of the subxact).
2106 : : */
2107 [ + - ]: 5703 : if (s->curTransactionContext)
2108 : 5703 : MemoryContextDelete(s->curTransactionContext);
2109 : 5703 : s->curTransactionContext = NULL;
2110 : 5703 : }
2111 : :
2112 : : /* ----------------------------------------------------------------
2113 : : * interface routines
2114 : : * ----------------------------------------------------------------
2115 : : */
2116 : :
2117 : : /*
2118 : : * StartTransaction
2119 : : */
2120 : : static void
2121 : 661244 : StartTransaction(void)
2122 : : {
2123 : : TransactionState s;
2124 : : VirtualTransactionId vxid;
2125 : :
2126 : : /*
2127 : : * Let's just make sure the state stack is empty
2128 : : */
2129 : 661244 : s = &TopTransactionStateData;
2130 : 661244 : CurrentTransactionState = s;
2131 : :
2132 : : Assert(!FullTransactionIdIsValid(XactTopFullTransactionId));
2133 : :
2134 : : /* check the current transaction state */
2135 : : Assert(s->state == TRANS_DEFAULT);
2136 : :
2137 : : /*
2138 : : * Set the current transaction state information appropriately during
2139 : : * start processing. Note that once the transaction status is switched
2140 : : * this process cannot fail until the user ID and the security context
2141 : : * flags are fetched below.
2142 : : */
2143 : 661244 : s->state = TRANS_START;
2144 : 661244 : s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
2145 : :
2146 : : /* Determine if statements are logged in this transaction */
2147 [ - + ]: 661244 : xact_is_sampled = log_xact_sample_rate != 0 &&
2148 [ # # ]: 0 : (log_xact_sample_rate == 1 ||
2149 [ # # ]: 0 : pg_prng_double(&pg_global_prng_state) <= log_xact_sample_rate);
2150 : :
2151 : : /*
2152 : : * initialize current transaction state fields
2153 : : *
2154 : : * note: prevXactReadOnly is not used at the outermost level
2155 : : */
2156 : 661244 : s->nestingLevel = 1;
2157 : 661244 : s->gucNestLevel = 1;
2158 : 661244 : s->childXids = NULL;
2159 : 661244 : s->nChildXids = 0;
2160 : 661244 : s->maxChildXids = 0;
2161 : :
2162 : : /*
2163 : : * Once the current user ID and the security context flags are fetched,
2164 : : * both will be properly reset even if transaction startup fails.
2165 : : */
2166 : 661244 : GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
2167 : :
2168 : : /* SecurityRestrictionContext should never be set outside a transaction */
2169 : : Assert(s->prevSecContext == 0);
2170 : :
2171 : : /*
2172 : : * Make sure we've reset xact state variables
2173 : : *
2174 : : * If recovery is still in progress, mark this transaction as read-only.
2175 : : * We have lower level defences in XLogInsert and elsewhere to stop us
2176 : : * from modifying data during recovery, but this gives the normal
2177 : : * indication to the user that the transaction is read-only.
2178 : : */
2179 [ + + ]: 661244 : if (RecoveryInProgress())
2180 : : {
2181 : 2626 : s->startedInRecovery = true;
2182 : 2626 : XactReadOnly = true;
2183 : : }
2184 : : else
2185 : : {
2186 : 658618 : s->startedInRecovery = false;
2187 : 658618 : XactReadOnly = DefaultXactReadOnly;
2188 : : }
2189 : 661244 : XactDeferrable = DefaultXactDeferrable;
2190 : 661244 : XactIsoLevel = DefaultXactIsoLevel;
2191 : 661244 : forceSyncCommit = false;
2192 : 661244 : MyXactFlags = 0;
2193 : :
2194 : : /*
2195 : : * reinitialize within-transaction counters
2196 : : */
2197 : 661244 : s->subTransactionId = TopSubTransactionId;
2198 : 661244 : currentSubTransactionId = TopSubTransactionId;
2199 : 661244 : currentCommandId = FirstCommandId;
2200 : 661244 : currentCommandIdUsed = false;
2201 : :
2202 : : /*
2203 : : * initialize reported xid accounting
2204 : : */
2205 : 661244 : nUnreportedXids = 0;
2206 : 661244 : s->didLogXid = false;
2207 : :
2208 : : /*
2209 : : * must initialize resource-management stuff first
2210 : : */
2211 : 661244 : AtStart_Memory();
2212 : 661244 : AtStart_ResourceOwner();
2213 : :
2214 : : /*
2215 : : * Assign a new LocalTransactionId, and combine it with the proc number to
2216 : : * form a virtual transaction id.
2217 : : */
2218 : 661244 : vxid.procNumber = MyProcNumber;
2219 : 661244 : vxid.localTransactionId = GetNextLocalTransactionId();
2220 : :
2221 : : /*
2222 : : * Lock the virtual transaction id before we announce it in the proc array
2223 : : */
2224 : 661244 : VirtualXactLockTableInsert(vxid);
2225 : :
2226 : : /*
2227 : : * Advertise it in the proc array. We assume assignment of
2228 : : * localTransactionId is atomic, and the proc number should be set
2229 : : * already.
2230 : : */
2231 : : Assert(MyProc->vxid.procNumber == vxid.procNumber);
2232 : 661244 : MyProc->vxid.lxid = vxid.localTransactionId;
2233 : :
2234 : : TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
2235 : :
2236 : : /*
2237 : : * set transaction_timestamp() (a/k/a now()). Normally, we want this to
2238 : : * be the same as the first command's statement_timestamp(), so don't do a
2239 : : * fresh GetCurrentTimestamp() call (which'd be expensive anyway). But
2240 : : * for transactions started inside procedures (i.e., nonatomic SPI
2241 : : * contexts), we do need to advance the timestamp. Also, in a parallel
2242 : : * worker, the timestamp should already have been provided by a call to
2243 : : * SetParallelStartTimestamps().
2244 : : */
2245 [ + + ]: 661244 : if (!IsParallelWorker())
2246 : : {
2247 [ + + ]: 655100 : if (!SPI_inside_nonatomic_context())
2248 : 652760 : xactStartTimestamp = stmtStartTimestamp;
2249 : : else
2250 : 2340 : xactStartTimestamp = GetCurrentTimestamp();
2251 : : }
2252 : : else
2253 : : Assert(xactStartTimestamp != 0);
2254 : 661244 : pgstat_report_xact_timestamp(xactStartTimestamp);
2255 : : /* Mark xactStopTimestamp as unset. */
2256 : 661244 : xactStopTimestamp = 0;
2257 : :
2258 : : /*
2259 : : * initialize other subsystems for new transaction
2260 : : */
2261 : 661244 : AtStart_GUC();
2262 : 661244 : AtStart_Cache();
2263 : 661244 : AfterTriggerBeginXact();
2264 : :
2265 : : /*
2266 : : * done with start processing, set current transaction state to "in
2267 : : * progress"
2268 : : */
2269 : 661244 : s->state = TRANS_INPROGRESS;
2270 : :
2271 : : /* Schedule transaction timeout */
2272 [ + + ]: 661244 : if (TransactionTimeout > 0)
2273 : 1 : enable_timeout_after(TRANSACTION_TIMEOUT, TransactionTimeout);
2274 : :
2275 : 661244 : ShowTransactionState("StartTransaction");
2276 : 661244 : }
2277 : :
2278 : :
2279 : : /*
2280 : : * CommitTransaction
2281 : : *
2282 : : * NB: if you change this routine, better look at PrepareTransaction too!
2283 : : */
2284 : : static void
2285 : 624043 : CommitTransaction(void)
2286 : : {
2287 : 624043 : TransactionState s = CurrentTransactionState;
2288 : : TransactionId latestXid;
2289 : : bool is_parallel_worker;
2290 : :
2291 : 624043 : is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2292 : :
2293 : : /* Enforce parallel mode restrictions during parallel worker commit. */
2294 [ + + ]: 624043 : if (is_parallel_worker)
2295 : 2033 : EnterParallelMode();
2296 : :
2297 : 624043 : ShowTransactionState("CommitTransaction");
2298 : :
2299 : : /*
2300 : : * check the current transaction state
2301 : : */
2302 [ - + ]: 624043 : if (s->state != TRANS_INPROGRESS)
2303 [ # # ]: 0 : elog(WARNING, "CommitTransaction while in %s state",
2304 : : TransStateAsString(s->state));
2305 : : Assert(s->parent == NULL);
2306 : :
2307 : : /*
2308 : : * Do pre-commit processing that involves calling user-defined code, such
2309 : : * as triggers. SECURITY_RESTRICTED_OPERATION contexts must not queue an
2310 : : * action that would run here, because that would bypass the sandbox.
2311 : : * Since closing cursors could queue trigger actions, triggers could open
2312 : : * cursors, etc, we have to keep looping until there's nothing left to do.
2313 : : */
2314 : : for (;;)
2315 : : {
2316 : : /*
2317 : : * Fire all currently pending deferred triggers.
2318 : : */
2319 : 630321 : AfterTriggerFireDeferred();
2320 : :
2321 : : /*
2322 : : * Close open portals (converting holdable ones into static portals).
2323 : : * If there weren't any, we are done ... otherwise loop back to check
2324 : : * if they queued deferred triggers. Lather, rinse, repeat.
2325 : : */
2326 [ + + ]: 630172 : if (!PreCommit_Portals(false))
2327 : 623894 : break;
2328 : : }
2329 : :
2330 : : /*
2331 : : * The remaining actions cannot call any user-defined code, so it's safe
2332 : : * to start shutting down within-transaction services. But note that most
2333 : : * of this stuff could still throw an error, which would switch us into
2334 : : * the transaction-abort path.
2335 : : */
2336 : :
2337 [ + + ]: 623894 : CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_PRE_COMMIT
2338 : : : XACT_EVENT_PRE_COMMIT);
2339 : :
2340 : : /*
2341 : : * If this xact has started any unfinished parallel operation, clean up
2342 : : * its workers, warning about leaked resources. (But we don't actually
2343 : : * reset parallelModeLevel till entering TRANS_COMMIT, a bit below. This
2344 : : * keeps parallel mode restrictions active as long as possible in a
2345 : : * parallel worker.)
2346 : : */
2347 : 623893 : AtEOXact_Parallel(true);
2348 [ + + ]: 623893 : if (is_parallel_worker)
2349 : : {
2350 [ - + ]: 2033 : if (s->parallelModeLevel != 1)
2351 [ # # ]: 0 : elog(WARNING, "parallelModeLevel is %d not 1 at end of parallel worker transaction",
2352 : : s->parallelModeLevel);
2353 : : }
2354 : : else
2355 : : {
2356 [ - + ]: 621860 : if (s->parallelModeLevel != 0)
2357 [ # # ]: 0 : elog(WARNING, "parallelModeLevel is %d not 0 at end of transaction",
2358 : : s->parallelModeLevel);
2359 : : }
2360 : :
2361 : : /* Shut down the deferred-trigger manager */
2362 : 623893 : AfterTriggerEndXact(true);
2363 : :
2364 : : /*
2365 : : * Let ON COMMIT management do its thing (must happen after closing
2366 : : * cursors, to avoid dangling-reference problems)
2367 : : */
2368 : 623893 : PreCommit_on_commit_actions();
2369 : :
2370 : : /*
2371 : : * Synchronize files that are created and not WAL-logged during this
2372 : : * transaction. This must happen before AtEOXact_RelationMap(), so that we
2373 : : * don't see committed-but-broken files after a crash.
2374 : : */
2375 : 623889 : smgrDoPendingSyncs(true, is_parallel_worker);
2376 : :
2377 : : /* close large objects before lower-level cleanup */
2378 : 623889 : AtEOXact_LargeObject(true);
2379 : :
2380 : : /*
2381 : : * Insert notifications sent by NOTIFY commands into the queue. This
2382 : : * should be late in the pre-commit sequence to minimize time spent
2383 : : * holding the notify-insertion lock. However, this could result in
2384 : : * creating a snapshot, so we must do it before serializable cleanup.
2385 : : */
2386 : 623889 : PreCommit_Notify();
2387 : :
2388 : : /*
2389 : : * Mark serializable transaction as complete for predicate locking
2390 : : * purposes. This should be done as late as we can put it and still allow
2391 : : * errors to be raised for failure patterns found at commit. This is not
2392 : : * appropriate in a parallel worker however, because we aren't committing
2393 : : * the leader's transaction and its serializable state will live on.
2394 : : */
2395 [ + + ]: 623889 : if (!is_parallel_worker)
2396 : 621856 : PreCommit_CheckForSerializationFailure();
2397 : :
2398 : : /* Prevent cancel/die interrupt while cleaning up */
2399 : 623729 : HOLD_INTERRUPTS();
2400 : :
2401 : : /* Commit updates to the relation map --- do this as late as possible */
2402 : 623729 : AtEOXact_RelationMap(true, is_parallel_worker);
2403 : :
2404 : : /*
2405 : : * set the current transaction state information appropriately during
2406 : : * commit processing
2407 : : */
2408 : 623729 : s->state = TRANS_COMMIT;
2409 : 623729 : s->parallelModeLevel = 0;
2410 : 623729 : s->parallelChildXact = false; /* should be false already */
2411 : :
2412 : : /* Disable transaction timeout */
2413 [ + + ]: 623729 : if (TransactionTimeout > 0)
2414 : 1 : disable_timeout(TRANSACTION_TIMEOUT, false);
2415 : :
2416 [ + + ]: 623729 : if (!is_parallel_worker)
2417 : : {
2418 : : /*
2419 : : * We need to mark our XIDs as committed in pg_xact. This is where we
2420 : : * durably commit.
2421 : : */
2422 : 621696 : latestXid = RecordTransactionCommit();
2423 : : }
2424 : : else
2425 : : {
2426 : : /*
2427 : : * We must not mark our XID committed; the parallel leader is
2428 : : * responsible for that.
2429 : : */
2430 : 2033 : latestXid = InvalidTransactionId;
2431 : :
2432 : : /*
2433 : : * Make sure the leader will know about any WAL we wrote before it
2434 : : * commits.
2435 : : */
2436 : 2033 : ParallelWorkerReportLastRecEnd(XactLastRecEnd);
2437 : : }
2438 : :
2439 : : TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->vxid.lxid);
2440 : :
2441 : : /*
2442 : : * Let others know about no transaction in progress by me. Note that this
2443 : : * must be done _before_ releasing locks we hold and _after_
2444 : : * RecordTransactionCommit.
2445 : : */
2446 : 623729 : ProcArrayEndTransaction(MyProc, latestXid);
2447 : :
2448 : : /*
2449 : : * This is all post-commit cleanup. Note that if an error is raised here,
2450 : : * it's too late to abort the transaction. This should be just
2451 : : * noncritical resource releasing.
2452 : : *
2453 : : * The ordering of operations is not entirely random. The idea is:
2454 : : * release resources visible to other backends (eg, files, buffer pins);
2455 : : * then release locks; then release backend-local resources. We want to
2456 : : * release locks at the point where any backend waiting for us will see
2457 : : * our transaction as being fully cleaned up.
2458 : : *
2459 : : * Resources that can be associated with individual queries are handled by
2460 : : * the ResourceOwner mechanism. The other calls here are for backend-wide
2461 : : * state.
2462 : : */
2463 : :
2464 : 623729 : CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2465 : : : XACT_EVENT_COMMIT);
2466 : :
2467 : 623729 : CurrentResourceOwner = NULL;
2468 : 623729 : ResourceOwnerRelease(TopTransactionResourceOwner,
2469 : : RESOURCE_RELEASE_BEFORE_LOCKS,
2470 : : true, true);
2471 : :
2472 : 623729 : AtEOXact_Aio(true);
2473 : :
2474 : : /* Check we've released all buffer pins */
2475 : 623729 : AtEOXact_Buffers(true);
2476 : :
2477 : : /* Clean up the relation cache */
2478 : 623729 : AtEOXact_RelationCache(true);
2479 : :
2480 : : /* Clean up the type cache */
2481 : 623729 : AtEOXact_TypeCache();
2482 : :
2483 : : /*
2484 : : * Make catalog changes visible to all backends. This has to happen after
2485 : : * relcache references are dropped (see comments for
2486 : : * AtEOXact_RelationCache), but before locks are released (if anyone is
2487 : : * waiting for lock on a relation we've modified, we want them to know
2488 : : * about the catalog change before they start using the relation).
2489 : : */
2490 : 623729 : AtEOXact_Inval(true);
2491 : :
2492 : 623729 : AtEOXact_MultiXact();
2493 : :
2494 : 623729 : ResourceOwnerRelease(TopTransactionResourceOwner,
2495 : : RESOURCE_RELEASE_LOCKS,
2496 : : true, true);
2497 : 623729 : ResourceOwnerRelease(TopTransactionResourceOwner,
2498 : : RESOURCE_RELEASE_AFTER_LOCKS,
2499 : : true, true);
2500 : :
2501 : : /*
2502 : : * Likewise, dropping of files deleted during the transaction is best done
2503 : : * after releasing relcache and buffer pins. (This is not strictly
2504 : : * necessary during commit, since such pins should have been released
2505 : : * already, but this ordering is definitely critical during abort.) Since
2506 : : * this may take many seconds, also delay until after releasing locks.
2507 : : * Other backends will observe the attendant catalog changes and not
2508 : : * attempt to access affected files.
2509 : : */
2510 : 623729 : smgrDoPendingDeletes(true);
2511 : :
2512 : : /*
2513 : : * Send out notification signals to other backends (and do other
2514 : : * post-commit NOTIFY cleanup). This must not happen until after our
2515 : : * transaction is fully done from the viewpoint of other backends.
2516 : : */
2517 : 623729 : AtCommit_Notify();
2518 : :
2519 : : /*
2520 : : * Everything after this should be purely internal-to-this-backend
2521 : : * cleanup.
2522 : : */
2523 : 623729 : AtEOXact_GUC(true, 1);
2524 : 623729 : AtEOXact_SPI(true);
2525 : 623729 : AtEOXact_Enum();
2526 : 623729 : AtEOXact_on_commit_actions(true);
2527 : 623729 : AtEOXact_Namespace(true, is_parallel_worker);
2528 : 623729 : AtEOXact_SMgr();
2529 : 623729 : AtEOXact_Files(true);
2530 : 623729 : AtEOXact_ComboCid();
2531 : 623729 : AtEOXact_HashTables(true);
2532 : 623729 : AtEOXact_RI(true);
2533 : 623729 : AtEOXact_PgStat(true, is_parallel_worker);
2534 : 623729 : AtEOXact_Snapshot(true, false);
2535 : 623729 : AtEOXact_ApplyLauncher(true);
2536 : 623729 : AtEOXact_LogicalRepWorkers(true);
2537 : 623729 : AtEOXact_LogicalCtl();
2538 : 623729 : pgstat_report_xact_timestamp(0);
2539 : :
2540 : 623729 : ResourceOwnerDelete(TopTransactionResourceOwner);
2541 : 623729 : s->curTransactionOwner = NULL;
2542 : 623729 : CurTransactionResourceOwner = NULL;
2543 : 623729 : TopTransactionResourceOwner = NULL;
2544 : :
2545 : 623729 : AtCommit_Memory();
2546 : :
2547 : 623729 : s->fullTransactionId = InvalidFullTransactionId;
2548 : 623729 : s->subTransactionId = InvalidSubTransactionId;
2549 : 623729 : s->nestingLevel = 0;
2550 : 623729 : s->gucNestLevel = 0;
2551 : 623729 : s->childXids = NULL;
2552 : 623729 : s->nChildXids = 0;
2553 : 623729 : s->maxChildXids = 0;
2554 : :
2555 : 623729 : XactTopFullTransactionId = InvalidFullTransactionId;
2556 : 623729 : nParallelCurrentXids = 0;
2557 : :
2558 : : /*
2559 : : * done with commit processing, set current transaction state back to
2560 : : * default
2561 : : */
2562 : 623729 : s->state = TRANS_DEFAULT;
2563 : :
2564 : 623729 : RESUME_INTERRUPTS();
2565 : 623729 : }
2566 : :
2567 : :
2568 : : /*
2569 : : * PrepareTransaction
2570 : : *
2571 : : * NB: if you change this routine, better look at CommitTransaction too!
2572 : : */
2573 : : static void
2574 : 385 : PrepareTransaction(void)
2575 : : {
2576 : 385 : TransactionState s = CurrentTransactionState;
2577 : 385 : FullTransactionId fxid = GetCurrentFullTransactionId();
2578 : : GlobalTransaction gxact;
2579 : : TimestampTz prepared_at;
2580 : :
2581 : : Assert(!IsInParallelMode());
2582 : :
2583 : 385 : ShowTransactionState("PrepareTransaction");
2584 : :
2585 : : /*
2586 : : * check the current transaction state
2587 : : */
2588 [ - + ]: 385 : if (s->state != TRANS_INPROGRESS)
2589 [ # # ]: 0 : elog(WARNING, "PrepareTransaction while in %s state",
2590 : : TransStateAsString(s->state));
2591 : : Assert(s->parent == NULL);
2592 : :
2593 : : /*
2594 : : * Do pre-commit processing that involves calling user-defined code, such
2595 : : * as triggers. Since closing cursors could queue trigger actions,
2596 : : * triggers could open cursors, etc, we have to keep looping until there's
2597 : : * nothing left to do.
2598 : : */
2599 : : for (;;)
2600 : : {
2601 : : /*
2602 : : * Fire all currently pending deferred triggers.
2603 : : */
2604 : 387 : AfterTriggerFireDeferred();
2605 : :
2606 : : /*
2607 : : * Close open portals (converting holdable ones into static portals).
2608 : : * If there weren't any, we are done ... otherwise loop back to check
2609 : : * if they queued deferred triggers. Lather, rinse, repeat.
2610 : : */
2611 [ + + ]: 387 : if (!PreCommit_Portals(true))
2612 : 385 : break;
2613 : : }
2614 : :
2615 : 385 : CallXactCallbacks(XACT_EVENT_PRE_PREPARE);
2616 : :
2617 : : /*
2618 : : * The remaining actions cannot call any user-defined code, so it's safe
2619 : : * to start shutting down within-transaction services. But note that most
2620 : : * of this stuff could still throw an error, which would switch us into
2621 : : * the transaction-abort path.
2622 : : */
2623 : :
2624 : : /* Shut down the deferred-trigger manager */
2625 : 384 : AfterTriggerEndXact(true);
2626 : :
2627 : : /*
2628 : : * Let ON COMMIT management do its thing (must happen after closing
2629 : : * cursors, to avoid dangling-reference problems)
2630 : : */
2631 : 384 : PreCommit_on_commit_actions();
2632 : :
2633 : : /*
2634 : : * Synchronize files that are created and not WAL-logged during this
2635 : : * transaction. This must happen before EndPrepare(), so that we don't see
2636 : : * committed-but-broken files after a crash and COMMIT PREPARED.
2637 : : */
2638 : 384 : smgrDoPendingSyncs(true, false);
2639 : :
2640 : : /* close large objects before lower-level cleanup */
2641 : 384 : AtEOXact_LargeObject(true);
2642 : :
2643 : : /* NOTIFY requires no work at this point */
2644 : :
2645 : : /*
2646 : : * Mark serializable transaction as complete for predicate locking
2647 : : * purposes. This should be done as late as we can put it and still allow
2648 : : * errors to be raised for failure patterns found at commit.
2649 : : */
2650 : 384 : PreCommit_CheckForSerializationFailure();
2651 : :
2652 : : /*
2653 : : * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2654 : : * this transaction. Having the prepared xact hold locks on another
2655 : : * backend's temp table seems a bad idea --- for instance it would prevent
2656 : : * the backend from exiting. There are other problems too, such as how to
2657 : : * clean up the source backend's local buffers and ON COMMIT state if the
2658 : : * prepared xact includes a DROP of a temp table.
2659 : : *
2660 : : * Other objects types, like functions, operators or extensions, share the
2661 : : * same restriction as they should not be created, locked or dropped as
2662 : : * this can mess up with this session or even a follow-up session trying
2663 : : * to use the same temporary namespace.
2664 : : *
2665 : : * We must check this after executing any ON COMMIT actions, because they
2666 : : * might still access a temp relation.
2667 : : *
2668 : : * XXX In principle this could be relaxed to allow some useful special
2669 : : * cases, such as a temp table created and dropped all within the
2670 : : * transaction. That seems to require much more bookkeeping though.
2671 : : */
2672 [ + + ]: 384 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
2673 [ + - ]: 44 : ereport(ERROR,
2674 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2675 : : errmsg("cannot PREPARE a transaction that has operated on temporary objects")));
2676 : :
2677 : : /*
2678 : : * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2679 : : * supported if we added cleanup logic to twophase.c, but for now it
2680 : : * doesn't seem worth the trouble.
2681 : : */
2682 [ - + ]: 340 : if (XactHasExportedSnapshots())
2683 [ # # ]: 0 : ereport(ERROR,
2684 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2685 : : errmsg("cannot PREPARE a transaction that has exported snapshots")));
2686 : :
2687 : : /* Prevent cancel/die interrupt while cleaning up */
2688 : 340 : HOLD_INTERRUPTS();
2689 : :
2690 : : /*
2691 : : * set the current transaction state information appropriately during
2692 : : * prepare processing
2693 : : */
2694 : 340 : s->state = TRANS_PREPARE;
2695 : :
2696 : : /* Disable transaction timeout */
2697 [ - + ]: 340 : if (TransactionTimeout > 0)
2698 : 0 : disable_timeout(TRANSACTION_TIMEOUT, false);
2699 : :
2700 : 340 : prepared_at = GetCurrentTimestamp();
2701 : :
2702 : : /*
2703 : : * Reserve the GID for this transaction. This could fail if the requested
2704 : : * GID is invalid or already in use.
2705 : : */
2706 : 340 : gxact = MarkAsPreparing(fxid, prepareGID, prepared_at,
2707 : : GetUserId(), MyDatabaseId);
2708 : 321 : prepareGID = NULL;
2709 : :
2710 : : /*
2711 : : * Collect data for the 2PC state file. Note that in general, no actual
2712 : : * state change should happen in the called modules during this step,
2713 : : * since it's still possible to fail before commit, and in that case we
2714 : : * want transaction abort to be able to clean up. (In particular, the
2715 : : * AtPrepare routines may error out if they find cases they cannot
2716 : : * handle.) State cleanup should happen in the PostPrepare routines
2717 : : * below. However, some modules can go ahead and clear state here because
2718 : : * they wouldn't do anything with it during abort anyway.
2719 : : *
2720 : : * Note: because the 2PC state file records will be replayed in the same
2721 : : * order they are made, the order of these calls has to match the order in
2722 : : * which we want things to happen during COMMIT PREPARED or ROLLBACK
2723 : : * PREPARED; in particular, pay attention to whether things should happen
2724 : : * before or after releasing the transaction's locks.
2725 : : */
2726 : 321 : StartPrepare(gxact);
2727 : :
2728 : 321 : AtPrepare_Notify();
2729 : 321 : AtPrepare_Locks();
2730 : 319 : AtPrepare_PredicateLocks();
2731 : 319 : AtPrepare_PgStat();
2732 : 319 : AtPrepare_MultiXact();
2733 : 319 : AtPrepare_RelationMap();
2734 : :
2735 : : /*
2736 : : * Here is where we really truly prepare.
2737 : : *
2738 : : * We have to record transaction prepares even if we didn't make any
2739 : : * updates, because the transaction manager might get confused if we lose
2740 : : * a global transaction.
2741 : : */
2742 : 319 : EndPrepare(gxact);
2743 : :
2744 : : /*
2745 : : * Now we clean up backend-internal state and release internal resources.
2746 : : */
2747 : :
2748 : : /* Reset XactLastRecEnd until the next transaction writes something */
2749 : 319 : XactLastRecEnd = 0;
2750 : :
2751 : : /*
2752 : : * Transfer our locks to a dummy PGPROC. This has to be done before
2753 : : * ProcArrayClearTransaction(). Otherwise, a GetLockConflicts() would
2754 : : * conclude "xact already committed or aborted" for our locks.
2755 : : */
2756 : 319 : PostPrepare_Locks(fxid);
2757 : :
2758 : : /*
2759 : : * Let others know about no transaction in progress by me. This has to be
2760 : : * done *after* the prepared transaction has been marked valid, else
2761 : : * someone may think it is unlocked and recyclable.
2762 : : */
2763 : 319 : ProcArrayClearTransaction(MyProc);
2764 : :
2765 : : /*
2766 : : * In normal commit-processing, this is all non-critical post-transaction
2767 : : * cleanup. When the transaction is prepared, however, it's important
2768 : : * that the locks and other per-backend resources are transferred to the
2769 : : * prepared transaction's PGPROC entry. Note that if an error is raised
2770 : : * here, it's too late to abort the transaction. XXX: This probably should
2771 : : * be in a critical section, to force a PANIC if any of this fails, but
2772 : : * that cure could be worse than the disease.
2773 : : */
2774 : :
2775 : 319 : CallXactCallbacks(XACT_EVENT_PREPARE);
2776 : :
2777 : 319 : ResourceOwnerRelease(TopTransactionResourceOwner,
2778 : : RESOURCE_RELEASE_BEFORE_LOCKS,
2779 : : true, true);
2780 : :
2781 : 319 : AtEOXact_Aio(true);
2782 : :
2783 : : /* Check we've released all buffer pins */
2784 : 319 : AtEOXact_Buffers(true);
2785 : :
2786 : : /* Clean up the relation cache */
2787 : 319 : AtEOXact_RelationCache(true);
2788 : :
2789 : : /* Clean up the type cache */
2790 : 319 : AtEOXact_TypeCache();
2791 : :
2792 : : /* notify doesn't need a postprepare call */
2793 : :
2794 : 319 : PostPrepare_PgStat();
2795 : :
2796 : 319 : PostPrepare_Inval();
2797 : :
2798 : 319 : PostPrepare_smgr();
2799 : :
2800 : 319 : PostPrepare_MultiXact(fxid);
2801 : :
2802 : 319 : PostPrepare_PredicateLocks(fxid);
2803 : :
2804 : 319 : ResourceOwnerRelease(TopTransactionResourceOwner,
2805 : : RESOURCE_RELEASE_LOCKS,
2806 : : true, true);
2807 : 319 : ResourceOwnerRelease(TopTransactionResourceOwner,
2808 : : RESOURCE_RELEASE_AFTER_LOCKS,
2809 : : true, true);
2810 : :
2811 : : /*
2812 : : * Allow another backend to finish the transaction. After
2813 : : * PostPrepare_Twophase(), the transaction is completely detached from our
2814 : : * backend. The rest is just non-critical cleanup of backend-local state.
2815 : : */
2816 : 319 : PostPrepare_Twophase();
2817 : :
2818 : : /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2819 : 319 : AtEOXact_GUC(true, 1);
2820 : 319 : AtEOXact_SPI(true);
2821 : 319 : AtEOXact_Enum();
2822 : 319 : AtEOXact_on_commit_actions(true);
2823 : 319 : AtEOXact_Namespace(true, false);
2824 : 319 : AtEOXact_SMgr();
2825 : 319 : AtEOXact_Files(true);
2826 : 319 : AtEOXact_ComboCid();
2827 : 319 : AtEOXact_HashTables(true);
2828 : 319 : AtEOXact_RI(true);
2829 : : /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2830 : 319 : AtEOXact_Snapshot(true, true);
2831 : : /* we treat PREPARE as ROLLBACK so far as waking workers goes */
2832 : 319 : AtEOXact_ApplyLauncher(false);
2833 : 319 : AtEOXact_LogicalRepWorkers(false);
2834 : 319 : AtEOXact_LogicalCtl();
2835 : 319 : pgstat_report_xact_timestamp(0);
2836 : :
2837 : 319 : CurrentResourceOwner = NULL;
2838 : 319 : ResourceOwnerDelete(TopTransactionResourceOwner);
2839 : 319 : s->curTransactionOwner = NULL;
2840 : 319 : CurTransactionResourceOwner = NULL;
2841 : 319 : TopTransactionResourceOwner = NULL;
2842 : :
2843 : 319 : AtCommit_Memory();
2844 : :
2845 : 319 : s->fullTransactionId = InvalidFullTransactionId;
2846 : 319 : s->subTransactionId = InvalidSubTransactionId;
2847 : 319 : s->nestingLevel = 0;
2848 : 319 : s->gucNestLevel = 0;
2849 : 319 : s->childXids = NULL;
2850 : 319 : s->nChildXids = 0;
2851 : 319 : s->maxChildXids = 0;
2852 : :
2853 : 319 : XactTopFullTransactionId = InvalidFullTransactionId;
2854 : 319 : nParallelCurrentXids = 0;
2855 : :
2856 : : /*
2857 : : * done with 1st phase commit processing, set current transaction state
2858 : : * back to default
2859 : : */
2860 : 319 : s->state = TRANS_DEFAULT;
2861 : :
2862 : 319 : RESUME_INTERRUPTS();
2863 : 319 : }
2864 : :
2865 : :
2866 : : /*
2867 : : * AbortTransaction
2868 : : */
2869 : : static void
2870 : 37196 : AbortTransaction(void)
2871 : : {
2872 : 37196 : TransactionState s = CurrentTransactionState;
2873 : : TransactionId latestXid;
2874 : : bool is_parallel_worker;
2875 : :
2876 : : /* Prevent cancel/die interrupt while cleaning up */
2877 : 37196 : HOLD_INTERRUPTS();
2878 : :
2879 : : /* Disable transaction timeout */
2880 [ + + ]: 37196 : if (TransactionTimeout > 0)
2881 : 1 : disable_timeout(TRANSACTION_TIMEOUT, false);
2882 : :
2883 : : /* Make sure we have a valid memory context and resource owner */
2884 : 37196 : AtAbort_Memory();
2885 : 37196 : AtAbort_ResourceOwner();
2886 : :
2887 : : /*
2888 : : * Release any LW locks we might be holding as quickly as possible.
2889 : : * (Regular locks, however, must be held till we finish aborting.)
2890 : : * Releasing LW locks is critical since we might try to grab them again
2891 : : * while cleaning up!
2892 : : */
2893 : 37196 : LWLockReleaseAll();
2894 : :
2895 : : /*
2896 : : * Cleanup waiting for LSN if any.
2897 : : */
2898 : 37196 : WaitLSNCleanup();
2899 : :
2900 : : /* Clear wait information and command progress indicator */
2901 : 37196 : pgstat_report_wait_end();
2902 : 37196 : pgstat_progress_end_command();
2903 : :
2904 : 37196 : pgaio_error_cleanup();
2905 : :
2906 : : /* Clean up buffer content locks, too */
2907 : 37196 : UnlockBuffers();
2908 : :
2909 : : /* Reset WAL record construction state */
2910 : 37196 : XLogResetInsertion();
2911 : :
2912 : : /* Cancel condition variable sleep */
2913 : 37196 : ConditionVariableCancelSleep();
2914 : :
2915 : : /*
2916 : : * Also clean up any open wait for lock, since the lock manager will choke
2917 : : * if we try to wait for another lock before doing this.
2918 : : */
2919 : 37196 : LockErrorCleanup();
2920 : :
2921 : : /*
2922 : : * If any timeout events are still active, make sure the timeout interrupt
2923 : : * is scheduled. This covers possible loss of a timeout interrupt due to
2924 : : * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2925 : : * We delay this till after LockErrorCleanup so that we don't uselessly
2926 : : * reschedule lock or deadlock check timeouts.
2927 : : */
2928 : 37196 : reschedule_timeouts();
2929 : :
2930 : : /*
2931 : : * Re-enable signals, in case we got here by longjmp'ing out of a signal
2932 : : * handler. We do this fairly early in the sequence so that the timeout
2933 : : * infrastructure will be functional if needed while aborting.
2934 : : */
2935 : 37196 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
2936 : :
2937 : : /*
2938 : : * check the current transaction state
2939 : : */
2940 : 37196 : is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2941 [ + + - + ]: 37196 : if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2942 [ # # ]: 0 : elog(WARNING, "AbortTransaction while in %s state",
2943 : : TransStateAsString(s->state));
2944 : : Assert(s->parent == NULL);
2945 : :
2946 : : /*
2947 : : * set the current transaction state information appropriately during the
2948 : : * abort processing
2949 : : */
2950 : 37196 : s->state = TRANS_ABORT;
2951 : :
2952 : : /*
2953 : : * Reset user ID which might have been changed transiently. We need this
2954 : : * to clean up in case control escaped out of a SECURITY DEFINER function
2955 : : * or other local change of CurrentUserId; therefore, the prior value of
2956 : : * SecurityRestrictionContext also needs to be restored.
2957 : : *
2958 : : * (Note: it is not necessary to restore session authorization or role
2959 : : * settings here because those can only be changed via GUC, and GUC will
2960 : : * take care of rolling them back if need be.)
2961 : : */
2962 : 37196 : SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
2963 : :
2964 : : /* Forget about any active REINDEX. */
2965 : 37196 : ResetReindexState(s->nestingLevel);
2966 : :
2967 : : /* Reset logical streaming state. */
2968 : 37196 : ResetLogicalStreamingState();
2969 : :
2970 : : /* Reset snapshot export state. */
2971 : 37196 : SnapBuildResetExportedSnapshotState();
2972 : :
2973 : : /*
2974 : : * If this xact has started any unfinished parallel operation, clean up
2975 : : * its workers and exit parallel mode. Don't warn about leaked resources.
2976 : : */
2977 : 37196 : AtEOXact_Parallel(false);
2978 : 37196 : s->parallelModeLevel = 0;
2979 : 37196 : s->parallelChildXact = false; /* should be false already */
2980 : :
2981 : : /*
2982 : : * do abort processing
2983 : : */
2984 : 37196 : AfterTriggerEndXact(false); /* 'false' means it's abort */
2985 : 37196 : AtAbort_Portals();
2986 : 37196 : smgrDoPendingSyncs(false, is_parallel_worker);
2987 : 37196 : AtEOXact_LargeObject(false);
2988 : 37196 : AtAbort_Notify();
2989 : 37196 : AtEOXact_RelationMap(false, is_parallel_worker);
2990 : 37196 : AtAbort_Twophase();
2991 : :
2992 : : /*
2993 : : * Advertise the fact that we aborted in pg_xact (assuming that we got as
2994 : : * far as assigning an XID to advertise). But if we're inside a parallel
2995 : : * worker, skip this; the user backend must be the one to write the abort
2996 : : * record.
2997 : : */
2998 [ + + ]: 37196 : if (!is_parallel_worker)
2999 : 37181 : latestXid = RecordTransactionAbort(false);
3000 : : else
3001 : : {
3002 : 15 : latestXid = InvalidTransactionId;
3003 : :
3004 : : /*
3005 : : * Since the parallel leader won't get our value of XactLastRecEnd in
3006 : : * this case, we nudge WAL-writer ourselves in this case. See related
3007 : : * comments in RecordTransactionAbort for why this matters.
3008 : : */
3009 : 15 : XLogSetAsyncXactLSN(XactLastRecEnd);
3010 : : }
3011 : :
3012 : : TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->vxid.lxid);
3013 : :
3014 : : /*
3015 : : * Let others know about no transaction in progress by me. Note that this
3016 : : * must be done _before_ releasing locks we hold and _after_
3017 : : * RecordTransactionAbort.
3018 : : */
3019 : 37196 : ProcArrayEndTransaction(MyProc, latestXid);
3020 : :
3021 : : /*
3022 : : * Post-abort cleanup. See notes in CommitTransaction() concerning
3023 : : * ordering. We can skip all of it if the transaction failed before
3024 : : * creating a resource owner.
3025 : : */
3026 [ + - ]: 37196 : if (TopTransactionResourceOwner != NULL)
3027 : : {
3028 [ + + ]: 37196 : if (is_parallel_worker)
3029 : 15 : CallXactCallbacks(XACT_EVENT_PARALLEL_ABORT);
3030 : : else
3031 : 37181 : CallXactCallbacks(XACT_EVENT_ABORT);
3032 : :
3033 : 37196 : ResourceOwnerRelease(TopTransactionResourceOwner,
3034 : : RESOURCE_RELEASE_BEFORE_LOCKS,
3035 : : false, true);
3036 : 37196 : AtEOXact_Aio(false);
3037 : 37196 : AtEOXact_Buffers(false);
3038 : 37196 : AtEOXact_RelationCache(false);
3039 : 37196 : AtEOXact_TypeCache();
3040 : 37196 : AtEOXact_Inval(false);
3041 : 37196 : AtEOXact_MultiXact();
3042 : 37196 : ResourceOwnerRelease(TopTransactionResourceOwner,
3043 : : RESOURCE_RELEASE_LOCKS,
3044 : : false, true);
3045 : 37196 : ResourceOwnerRelease(TopTransactionResourceOwner,
3046 : : RESOURCE_RELEASE_AFTER_LOCKS,
3047 : : false, true);
3048 : 37196 : smgrDoPendingDeletes(false);
3049 : :
3050 : 37196 : AtEOXact_GUC(false, 1);
3051 : 37196 : AtEOXact_SPI(false);
3052 : 37196 : AtEOXact_Enum();
3053 : 37196 : AtEOXact_on_commit_actions(false);
3054 : 37196 : AtEOXact_Namespace(false, is_parallel_worker);
3055 : 37196 : AtEOXact_SMgr();
3056 : 37196 : AtEOXact_Files(false);
3057 : 37196 : AtEOXact_ComboCid();
3058 : 37196 : AtEOXact_HashTables(false);
3059 : 37196 : AtEOXact_RI(false);
3060 : 37196 : AtEOXact_PgStat(false, is_parallel_worker);
3061 : 37196 : AtEOXact_ApplyLauncher(false);
3062 : 37196 : AtEOXact_LogicalRepWorkers(false);
3063 : 37196 : pgstat_report_xact_timestamp(0);
3064 : : }
3065 : :
3066 : : /*
3067 : : * State remains TRANS_ABORT until CleanupTransaction().
3068 : : */
3069 : 37196 : RESUME_INTERRUPTS();
3070 : 37196 : }
3071 : :
3072 : : /*
3073 : : * CleanupTransaction
3074 : : */
3075 : : static void
3076 : 37196 : CleanupTransaction(void)
3077 : : {
3078 : 37196 : TransactionState s = CurrentTransactionState;
3079 : :
3080 : : /*
3081 : : * State should still be TRANS_ABORT from AbortTransaction().
3082 : : */
3083 [ - + ]: 37196 : if (s->state != TRANS_ABORT)
3084 [ # # ]: 0 : elog(FATAL, "CleanupTransaction: unexpected state %s",
3085 : : TransStateAsString(s->state));
3086 : :
3087 : : /*
3088 : : * do abort cleanup processing
3089 : : */
3090 : 37196 : AtCleanup_Portals(); /* now safe to release portal memory */
3091 : 37196 : AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
3092 : :
3093 : 37196 : CurrentResourceOwner = NULL; /* and resource owner */
3094 [ + - ]: 37196 : if (TopTransactionResourceOwner)
3095 : 37196 : ResourceOwnerDelete(TopTransactionResourceOwner);
3096 : 37196 : s->curTransactionOwner = NULL;
3097 : 37196 : CurTransactionResourceOwner = NULL;
3098 : 37196 : TopTransactionResourceOwner = NULL;
3099 : :
3100 : 37196 : AtCleanup_Memory(); /* and transaction memory */
3101 : :
3102 : 37196 : s->fullTransactionId = InvalidFullTransactionId;
3103 : 37196 : s->subTransactionId = InvalidSubTransactionId;
3104 : 37196 : s->nestingLevel = 0;
3105 : 37196 : s->gucNestLevel = 0;
3106 : 37196 : s->childXids = NULL;
3107 : 37196 : s->nChildXids = 0;
3108 : 37196 : s->maxChildXids = 0;
3109 : 37196 : s->parallelModeLevel = 0;
3110 : 37196 : s->parallelChildXact = false;
3111 : :
3112 : 37196 : XactTopFullTransactionId = InvalidFullTransactionId;
3113 : 37196 : nParallelCurrentXids = 0;
3114 : :
3115 : : /*
3116 : : * Apply any pending XLogLogicalInfo update. This must be done here
3117 : : * rather than in AbortTransaction(), because a failed transaction block
3118 : : * keeps its XID until ROLLBACK, so a barrier absorbed meanwhile is
3119 : : * deferred. Unlike CommitTransaction() and PrepareTransaction(), we are
3120 : : * not necessarily holding interrupts here, so do this after resetting the
3121 : : * top-level XID; otherwise a barrier absorbed in between would be left
3122 : : * pending into the next transaction.
3123 : : */
3124 : 37196 : AtEOXact_LogicalCtl();
3125 : :
3126 : : /*
3127 : : * done with abort processing, set current transaction state back to
3128 : : * default
3129 : : */
3130 : 37196 : s->state = TRANS_DEFAULT;
3131 : 37196 : }
3132 : :
3133 : : /*
3134 : : * StartTransactionCommand
3135 : : */
3136 : : void
3137 : 778555 : StartTransactionCommand(void)
3138 : : {
3139 : 778555 : TransactionState s = CurrentTransactionState;
3140 : :
3141 [ + + + - : 778555 : switch (s->blockState)
- ]
3142 : : {
3143 : : /*
3144 : : * if we aren't in a transaction block, we just do our usual start
3145 : : * transaction.
3146 : : */
3147 : 659140 : case TBLOCK_DEFAULT:
3148 : 659140 : StartTransaction();
3149 : 659140 : s->blockState = TBLOCK_STARTED;
3150 : 659140 : break;
3151 : :
3152 : : /*
3153 : : * We are somewhere in a transaction block or subtransaction and
3154 : : * about to start a new command. For now we do nothing, but
3155 : : * someday we may do command-local resource initialization. (Note
3156 : : * that any needed CommandCounterIncrement was done by the
3157 : : * previous CommitTransactionCommand.)
3158 : : */
3159 : 118107 : case TBLOCK_INPROGRESS:
3160 : : case TBLOCK_IMPLICIT_INPROGRESS:
3161 : : case TBLOCK_SUBINPROGRESS:
3162 : 118107 : break;
3163 : :
3164 : : /*
3165 : : * Here we are in a failed transaction block (one of the commands
3166 : : * caused an abort) so we do nothing but remain in the abort
3167 : : * state. Eventually we will get a ROLLBACK command which will
3168 : : * get us out of this state. (It is up to other code to ensure
3169 : : * that no commands other than ROLLBACK will be processed in these
3170 : : * states.)
3171 : : */
3172 : 1308 : case TBLOCK_ABORT:
3173 : : case TBLOCK_SUBABORT:
3174 : 1308 : break;
3175 : :
3176 : : /* These cases are invalid. */
3177 : 0 : case TBLOCK_STARTED:
3178 : : case TBLOCK_BEGIN:
3179 : : case TBLOCK_PARALLEL_INPROGRESS:
3180 : : case TBLOCK_SUBBEGIN:
3181 : : case TBLOCK_END:
3182 : : case TBLOCK_SUBRELEASE:
3183 : : case TBLOCK_SUBCOMMIT:
3184 : : case TBLOCK_ABORT_END:
3185 : : case TBLOCK_SUBABORT_END:
3186 : : case TBLOCK_ABORT_PENDING:
3187 : : case TBLOCK_SUBABORT_PENDING:
3188 : : case TBLOCK_SUBRESTART:
3189 : : case TBLOCK_SUBABORT_RESTART:
3190 : : case TBLOCK_PREPARE:
3191 [ # # ]: 0 : elog(ERROR, "StartTransactionCommand: unexpected state %s",
3192 : : BlockStateAsString(s->blockState));
3193 : : break;
3194 : : }
3195 : :
3196 : : /*
3197 : : * We must switch to CurTransactionContext before returning. This is
3198 : : * already done if we called StartTransaction, otherwise not.
3199 : : */
3200 : : Assert(CurTransactionContext != NULL);
3201 : 778555 : MemoryContextSwitchTo(CurTransactionContext);
3202 : 778555 : }
3203 : :
3204 : :
3205 : : /*
3206 : : * Simple system for saving and restoring transaction characteristics
3207 : : * (isolation level, read only, deferrable). We need this for transaction
3208 : : * chaining, so that we can set the characteristics of the new transaction to
3209 : : * be the same as the previous one. (We need something like this because the
3210 : : * GUC system resets the characteristics at transaction end, so for example
3211 : : * just skipping the reset in StartTransaction() won't work.)
3212 : : */
3213 : : void
3214 : 780555 : SaveTransactionCharacteristics(SavedTransactionCharacteristics *s)
3215 : : {
3216 : 780555 : s->save_XactIsoLevel = XactIsoLevel;
3217 : 780555 : s->save_XactReadOnly = XactReadOnly;
3218 : 780555 : s->save_XactDeferrable = XactDeferrable;
3219 : 780555 : }
3220 : :
3221 : : void
3222 : 1150 : RestoreTransactionCharacteristics(const SavedTransactionCharacteristics *s)
3223 : : {
3224 : 1150 : XactIsoLevel = s->save_XactIsoLevel;
3225 : 1150 : XactReadOnly = s->save_XactReadOnly;
3226 : 1150 : XactDeferrable = s->save_XactDeferrable;
3227 : 1150 : }
3228 : :
3229 : : /*
3230 : : * CommitTransactionCommand -- a wrapper function handling the
3231 : : * loop over subtransactions to avoid a potentially dangerous recursion
3232 : : * in CommitTransactionCommandInternal().
3233 : : */
3234 : : void
3235 : 743792 : CommitTransactionCommand(void)
3236 : : {
3237 : : /*
3238 : : * Repeatedly call CommitTransactionCommandInternal() until all the work
3239 : : * is done.
3240 : : */
3241 [ + + ]: 744131 : while (!CommitTransactionCommandInternal())
3242 : : {
3243 : : }
3244 : 743412 : }
3245 : :
3246 : : /*
3247 : : * CommitTransactionCommandInternal - a function doing an iteration of work
3248 : : * regarding handling the commit transaction command. In the case of
3249 : : * subtransactions more than one iterations could be required. Returns
3250 : : * true when no more iterations required, false otherwise.
3251 : : */
3252 : : static bool
3253 : 744131 : CommitTransactionCommandInternal(void)
3254 : : {
3255 : 744131 : TransactionState s = CurrentTransactionState;
3256 : : SavedTransactionCharacteristics savetc;
3257 : :
3258 : : /* Must save in case we need to restore below */
3259 : 744131 : SaveTransactionCharacteristics(&savetc);
3260 : :
3261 [ - + + + : 744131 : switch (s->blockState)
+ + + + +
+ + + + +
+ + - ]
3262 : : {
3263 : : /*
3264 : : * These shouldn't happen. TBLOCK_DEFAULT means the previous
3265 : : * StartTransactionCommand didn't set the STARTED state
3266 : : * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
3267 : : * by EndParallelWorkerTransaction(), not this function.
3268 : : */
3269 : 0 : case TBLOCK_DEFAULT:
3270 : : case TBLOCK_PARALLEL_INPROGRESS:
3271 [ # # ]: 0 : elog(FATAL, "CommitTransactionCommand: unexpected state %s",
3272 : : BlockStateAsString(s->blockState));
3273 : : break;
3274 : :
3275 : : /*
3276 : : * If we aren't in a transaction block, just do our usual
3277 : : * transaction commit, and return to the idle state.
3278 : : */
3279 : 612727 : case TBLOCK_STARTED:
3280 : 612727 : CommitTransaction();
3281 : 612684 : s->blockState = TBLOCK_DEFAULT;
3282 : 612684 : break;
3283 : :
3284 : : /*
3285 : : * We are completing a "BEGIN TRANSACTION" command, so we change
3286 : : * to the "transaction block in progress" state and return. (We
3287 : : * assume the BEGIN did nothing to the database, so we need no
3288 : : * CommandCounterIncrement.)
3289 : : */
3290 : 12855 : case TBLOCK_BEGIN:
3291 : 12855 : s->blockState = TBLOCK_INPROGRESS;
3292 : 12855 : break;
3293 : :
3294 : : /*
3295 : : * This is the case when we have finished executing a command
3296 : : * someplace within a transaction block. We increment the command
3297 : : * counter and return.
3298 : : */
3299 : 82308 : case TBLOCK_INPROGRESS:
3300 : : case TBLOCK_IMPLICIT_INPROGRESS:
3301 : : case TBLOCK_SUBINPROGRESS:
3302 : 82308 : CommandCounterIncrement();
3303 : 82308 : break;
3304 : :
3305 : : /*
3306 : : * We are completing a "COMMIT" command. Do it and return to the
3307 : : * idle state.
3308 : : */
3309 : 8907 : case TBLOCK_END:
3310 : 8907 : CommitTransaction();
3311 : 8653 : s->blockState = TBLOCK_DEFAULT;
3312 [ + + ]: 8653 : if (s->chain)
3313 : : {
3314 : 8 : StartTransaction();
3315 : 8 : s->blockState = TBLOCK_INPROGRESS;
3316 : 8 : s->chain = false;
3317 : 8 : RestoreTransactionCharacteristics(&savetc);
3318 : : }
3319 : 8653 : break;
3320 : :
3321 : : /*
3322 : : * Here we are in the middle of a transaction block but one of the
3323 : : * commands caused an abort so we do nothing but remain in the
3324 : : * abort state. Eventually we will get a ROLLBACK command.
3325 : : */
3326 : 13 : case TBLOCK_ABORT:
3327 : : case TBLOCK_SUBABORT:
3328 : 13 : break;
3329 : :
3330 : : /*
3331 : : * Here we were in an aborted transaction block and we just got
3332 : : * the ROLLBACK command from the user, so clean up the
3333 : : * already-aborted transaction and return to the idle state.
3334 : : */
3335 : 963 : case TBLOCK_ABORT_END:
3336 : 963 : CleanupTransaction();
3337 : 963 : s->blockState = TBLOCK_DEFAULT;
3338 [ + + ]: 963 : if (s->chain)
3339 : : {
3340 : 16 : StartTransaction();
3341 : 16 : s->blockState = TBLOCK_INPROGRESS;
3342 : 16 : s->chain = false;
3343 : 16 : RestoreTransactionCharacteristics(&savetc);
3344 : : }
3345 : 963 : break;
3346 : :
3347 : : /*
3348 : : * Here we were in a perfectly good transaction block but the user
3349 : : * told us to ROLLBACK anyway. We have to abort the transaction
3350 : : * and then clean up.
3351 : : */
3352 : 1939 : case TBLOCK_ABORT_PENDING:
3353 : 1939 : AbortTransaction();
3354 : 1939 : CleanupTransaction();
3355 : 1939 : s->blockState = TBLOCK_DEFAULT;
3356 [ + + ]: 1939 : if (s->chain)
3357 : : {
3358 : 16 : StartTransaction();
3359 : 16 : s->blockState = TBLOCK_INPROGRESS;
3360 : 16 : s->chain = false;
3361 : 16 : RestoreTransactionCharacteristics(&savetc);
3362 : : }
3363 : 1939 : break;
3364 : :
3365 : : /*
3366 : : * We are completing a "PREPARE TRANSACTION" command. Do it and
3367 : : * return to the idle state.
3368 : : */
3369 : 281 : case TBLOCK_PREPARE:
3370 : 281 : PrepareTransaction();
3371 : 217 : s->blockState = TBLOCK_DEFAULT;
3372 : 217 : break;
3373 : :
3374 : : /*
3375 : : * The user issued a SAVEPOINT inside a transaction block. Start a
3376 : : * subtransaction. (DefineSavepoint already did PushTransaction,
3377 : : * so as to have someplace to put the SUBBEGIN state.)
3378 : : */
3379 : 22551 : case TBLOCK_SUBBEGIN:
3380 : 22551 : StartSubTransaction();
3381 : 22551 : s->blockState = TBLOCK_SUBINPROGRESS;
3382 : 22551 : break;
3383 : :
3384 : : /*
3385 : : * The user issued a RELEASE command, so we end the current
3386 : : * subtransaction and return to the parent transaction. The parent
3387 : : * might be ended too, so repeat till we find an INPROGRESS
3388 : : * transaction or subtransaction.
3389 : : */
3390 : 270 : case TBLOCK_SUBRELEASE:
3391 : : do
3392 : : {
3393 : 270 : CommitSubTransaction();
3394 : 270 : s = CurrentTransactionState; /* changed by pop */
3395 [ + + ]: 270 : } while (s->blockState == TBLOCK_SUBRELEASE);
3396 : :
3397 : : Assert(s->blockState == TBLOCK_INPROGRESS ||
3398 : : s->blockState == TBLOCK_SUBINPROGRESS);
3399 : 183 : break;
3400 : :
3401 : : /*
3402 : : * The user issued a COMMIT, so we end the current subtransaction
3403 : : * hierarchy and perform final commit. We do this by rolling up
3404 : : * any subtransactions into their parent, which leads to O(N^2)
3405 : : * operations with respect to resource owners - this isn't that
3406 : : * bad until we approach a thousands of savepoints but is
3407 : : * necessary for correctness should after triggers create new
3408 : : * resource owners.
3409 : : */
3410 : 599 : case TBLOCK_SUBCOMMIT:
3411 : : do
3412 : : {
3413 : 599 : CommitSubTransaction();
3414 : 599 : s = CurrentTransactionState; /* changed by pop */
3415 [ + + ]: 599 : } while (s->blockState == TBLOCK_SUBCOMMIT);
3416 : : /* If we had a COMMIT command, finish off the main xact too */
3417 [ + + ]: 506 : if (s->blockState == TBLOCK_END)
3418 : : {
3419 : : Assert(s->parent == NULL);
3420 : :
3421 : : /*
3422 : : * Save the characteristics again, now that the
3423 : : * subtransactions are committed. A subtransaction may have
3424 : : * switched to read-only, which should not be inherited by the
3425 : : * next AND CHAIN, if any.
3426 : : */
3427 : 402 : SaveTransactionCharacteristics(&savetc);
3428 : 402 : CommitTransaction();
3429 : 385 : s->blockState = TBLOCK_DEFAULT;
3430 [ + + ]: 385 : if (s->chain)
3431 : : {
3432 : 16 : StartTransaction();
3433 : 16 : s->blockState = TBLOCK_INPROGRESS;
3434 : 16 : s->chain = false;
3435 : 16 : RestoreTransactionCharacteristics(&savetc);
3436 : : }
3437 : : }
3438 [ + - ]: 104 : else if (s->blockState == TBLOCK_PREPARE)
3439 : : {
3440 : : Assert(s->parent == NULL);
3441 : 104 : PrepareTransaction();
3442 : 102 : s->blockState = TBLOCK_DEFAULT;
3443 : : }
3444 : : else
3445 [ # # ]: 0 : elog(ERROR, "CommitTransactionCommand: unexpected state %s",
3446 : : BlockStateAsString(s->blockState));
3447 : 487 : break;
3448 : :
3449 : : /*
3450 : : * The current already-failed subtransaction is ending due to a
3451 : : * ROLLBACK or ROLLBACK TO command, so pop it and recursively
3452 : : * examine the parent (which could be in any of several states).
3453 : : * As we need to examine the parent, return false to request the
3454 : : * caller to do the next iteration.
3455 : : */
3456 : 55 : case TBLOCK_SUBABORT_END:
3457 : 55 : CleanupSubTransaction();
3458 : 55 : return false;
3459 : :
3460 : : /*
3461 : : * As above, but it's not dead yet, so abort first.
3462 : : */
3463 : 284 : case TBLOCK_SUBABORT_PENDING:
3464 : 284 : AbortSubTransaction();
3465 : 284 : CleanupSubTransaction();
3466 : 284 : return false;
3467 : :
3468 : : /*
3469 : : * The current subtransaction is the target of a ROLLBACK TO
3470 : : * command. Abort and pop it, then start a new subtransaction
3471 : : * with the same name.
3472 : : */
3473 : 348 : case TBLOCK_SUBRESTART:
3474 : : {
3475 : : char *name;
3476 : : int savepointLevel;
3477 : :
3478 : : /* save name and keep Cleanup from freeing it */
3479 : 348 : name = s->name;
3480 : 348 : s->name = NULL;
3481 : 348 : savepointLevel = s->savepointLevel;
3482 : :
3483 : 348 : AbortSubTransaction();
3484 : 348 : CleanupSubTransaction();
3485 : :
3486 : 348 : DefineSavepoint(NULL);
3487 : 348 : s = CurrentTransactionState; /* changed by push */
3488 : 348 : s->name = name;
3489 : 348 : s->savepointLevel = savepointLevel;
3490 : :
3491 : : /* This is the same as TBLOCK_SUBBEGIN case */
3492 : : Assert(s->blockState == TBLOCK_SUBBEGIN);
3493 : 348 : StartSubTransaction();
3494 : 348 : s->blockState = TBLOCK_SUBINPROGRESS;
3495 : : }
3496 : 348 : break;
3497 : :
3498 : : /*
3499 : : * Same as above, but the subtransaction had already failed, so we
3500 : : * don't need AbortSubTransaction.
3501 : : */
3502 : 211 : case TBLOCK_SUBABORT_RESTART:
3503 : : {
3504 : : char *name;
3505 : : int savepointLevel;
3506 : :
3507 : : /* save name and keep Cleanup from freeing it */
3508 : 211 : name = s->name;
3509 : 211 : s->name = NULL;
3510 : 211 : savepointLevel = s->savepointLevel;
3511 : :
3512 : 211 : CleanupSubTransaction();
3513 : :
3514 : 211 : DefineSavepoint(NULL);
3515 : 211 : s = CurrentTransactionState; /* changed by push */
3516 : 211 : s->name = name;
3517 : 211 : s->savepointLevel = savepointLevel;
3518 : :
3519 : : /* This is the same as TBLOCK_SUBBEGIN case */
3520 : : Assert(s->blockState == TBLOCK_SUBBEGIN);
3521 : 211 : StartSubTransaction();
3522 : 211 : s->blockState = TBLOCK_SUBINPROGRESS;
3523 : : }
3524 : 211 : break;
3525 : : }
3526 : :
3527 : : /* Done, no more iterations required */
3528 : 743412 : return true;
3529 : : }
3530 : :
3531 : : /*
3532 : : * AbortCurrentTransaction -- a wrapper function handling the
3533 : : * loop over subtransactions to avoid potentially dangerous recursion in
3534 : : * AbortCurrentTransactionInternal().
3535 : : */
3536 : : void
3537 : 35936 : AbortCurrentTransaction(void)
3538 : : {
3539 : : /*
3540 : : * Repeatedly call AbortCurrentTransactionInternal() until all the work is
3541 : : * done.
3542 : : */
3543 [ - + ]: 35936 : while (!AbortCurrentTransactionInternal())
3544 : : {
3545 : : }
3546 : 35936 : }
3547 : :
3548 : : /*
3549 : : * AbortCurrentTransactionInternal - a function doing an iteration of work
3550 : : * regarding handling the current transaction abort. In the case of
3551 : : * subtransactions more than one iterations could be required. Returns
3552 : : * true when no more iterations required, false otherwise.
3553 : : */
3554 : : static bool
3555 : 35936 : AbortCurrentTransactionInternal(void)
3556 : : {
3557 : 35936 : TransactionState s = CurrentTransactionState;
3558 : : SavedTransactionCharacteristics savetc;
3559 : :
3560 : : /* Must save in case we need to restore below */
3561 : 35936 : SaveTransactionCharacteristics(&savetc);
3562 : :
3563 [ + + - + : 35936 : switch (s->blockState)
+ + - - +
+ - - - ]
3564 : : {
3565 : 57 : case TBLOCK_DEFAULT:
3566 [ - + ]: 57 : if (s->state == TRANS_DEFAULT)
3567 : : {
3568 : : /* we are idle, so nothing to do */
3569 : : }
3570 : : else
3571 : : {
3572 : : /*
3573 : : * We can get here after an error during transaction start
3574 : : * (state will be TRANS_START). Need to clean up the
3575 : : * incompletely started transaction. First, adjust the
3576 : : * low-level state to suppress warning message from
3577 : : * AbortTransaction.
3578 : : */
3579 [ # # ]: 0 : if (s->state == TRANS_START)
3580 : 0 : s->state = TRANS_INPROGRESS;
3581 : 0 : AbortTransaction();
3582 : 0 : CleanupTransaction();
3583 : : }
3584 : 57 : break;
3585 : :
3586 : : /*
3587 : : * If we aren't in a transaction block, we just do the basic abort
3588 : : * & cleanup transaction. For this purpose, we treat an implicit
3589 : : * transaction block as if it were a simple statement.
3590 : : */
3591 : 33191 : case TBLOCK_STARTED:
3592 : : case TBLOCK_IMPLICIT_INPROGRESS:
3593 : 33191 : AbortTransaction();
3594 : 33191 : CleanupTransaction();
3595 : 33191 : s->blockState = TBLOCK_DEFAULT;
3596 : 33191 : break;
3597 : :
3598 : : /*
3599 : : * If we are in TBLOCK_BEGIN it means something screwed up right
3600 : : * after reading "BEGIN TRANSACTION". We assume that the user
3601 : : * will interpret the error as meaning the BEGIN failed to get him
3602 : : * into a transaction block, so we should abort and return to idle
3603 : : * state.
3604 : : */
3605 : 0 : case TBLOCK_BEGIN:
3606 : 0 : AbortTransaction();
3607 : 0 : CleanupTransaction();
3608 : 0 : s->blockState = TBLOCK_DEFAULT;
3609 : 0 : break;
3610 : :
3611 : : /*
3612 : : * We are somewhere in a transaction block and we've gotten a
3613 : : * failure, so we abort the transaction and set up the persistent
3614 : : * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3615 : : */
3616 : 982 : case TBLOCK_INPROGRESS:
3617 : : case TBLOCK_PARALLEL_INPROGRESS:
3618 : 982 : AbortTransaction();
3619 : :
3620 : : /*
3621 : : * AbortTransaction() has reset the transaction characteristics;
3622 : : * restore them for AND CHAIN.
3623 : : */
3624 : 982 : RestoreTransactionCharacteristics(&savetc);
3625 : 982 : s->blockState = TBLOCK_ABORT;
3626 : : /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
3627 : 982 : break;
3628 : :
3629 : : /*
3630 : : * Here, we failed while trying to COMMIT. Clean up the
3631 : : * transaction and return to idle state (we do not want to stay in
3632 : : * the transaction).
3633 : : */
3634 : 271 : case TBLOCK_END:
3635 : 271 : AbortTransaction();
3636 : 271 : CleanupTransaction();
3637 : 271 : s->blockState = TBLOCK_DEFAULT;
3638 : 271 : break;
3639 : :
3640 : : /*
3641 : : * Here, we are already in an aborted transaction state and are
3642 : : * waiting for a ROLLBACK, but for some reason we failed again! So
3643 : : * we just remain in the abort state.
3644 : : */
3645 : 67 : case TBLOCK_ABORT:
3646 : : case TBLOCK_SUBABORT:
3647 : 67 : break;
3648 : :
3649 : : /*
3650 : : * We are in a failed transaction and we got the ROLLBACK command.
3651 : : * We have already aborted, we just need to cleanup and go to idle
3652 : : * state.
3653 : : */
3654 : 0 : case TBLOCK_ABORT_END:
3655 : 0 : CleanupTransaction();
3656 : 0 : s->blockState = TBLOCK_DEFAULT;
3657 : 0 : break;
3658 : :
3659 : : /*
3660 : : * We are in a live transaction and we got a ROLLBACK command.
3661 : : * Abort, cleanup, go to idle state.
3662 : : */
3663 : 0 : case TBLOCK_ABORT_PENDING:
3664 : 0 : AbortTransaction();
3665 : 0 : CleanupTransaction();
3666 : 0 : s->blockState = TBLOCK_DEFAULT;
3667 : 0 : break;
3668 : :
3669 : : /*
3670 : : * Here, we failed while trying to PREPARE. Clean up the
3671 : : * transaction and return to idle state (we do not want to stay in
3672 : : * the transaction).
3673 : : */
3674 : 63 : case TBLOCK_PREPARE:
3675 : 63 : AbortTransaction();
3676 : 63 : CleanupTransaction();
3677 : 63 : s->blockState = TBLOCK_DEFAULT;
3678 : 63 : break;
3679 : :
3680 : : /*
3681 : : * We got an error inside a subtransaction. Abort just the
3682 : : * subtransaction, and go to the persistent SUBABORT state until
3683 : : * we get ROLLBACK.
3684 : : */
3685 : 1305 : case TBLOCK_SUBINPROGRESS:
3686 : 1305 : AbortSubTransaction();
3687 : 1305 : s->blockState = TBLOCK_SUBABORT;
3688 : 1305 : break;
3689 : :
3690 : : /*
3691 : : * If we failed while trying to create a subtransaction, clean up
3692 : : * the broken subtransaction and abort the parent. The same
3693 : : * applies if we get a failure while ending a subtransaction. As
3694 : : * we need to abort the parent, return false to request the caller
3695 : : * to do the next iteration.
3696 : : */
3697 : 0 : case TBLOCK_SUBBEGIN:
3698 : : case TBLOCK_SUBRELEASE:
3699 : : case TBLOCK_SUBCOMMIT:
3700 : : case TBLOCK_SUBABORT_PENDING:
3701 : : case TBLOCK_SUBRESTART:
3702 : 0 : AbortSubTransaction();
3703 : 0 : CleanupSubTransaction();
3704 : 0 : return false;
3705 : :
3706 : : /*
3707 : : * Same as above, except the Abort() was already done.
3708 : : */
3709 : 0 : case TBLOCK_SUBABORT_END:
3710 : : case TBLOCK_SUBABORT_RESTART:
3711 : 0 : CleanupSubTransaction();
3712 : 0 : return false;
3713 : : }
3714 : :
3715 : : /* Done, no more iterations required */
3716 : 35936 : return true;
3717 : : }
3718 : :
3719 : : /*
3720 : : * PreventInTransactionBlock
3721 : : *
3722 : : * This routine is to be called by statements that must not run inside
3723 : : * a transaction block, typically because they have non-rollback-able
3724 : : * side effects or do internal commits.
3725 : : *
3726 : : * If this routine completes successfully, then the calling statement is
3727 : : * guaranteed that if it completes without error, its results will be
3728 : : * committed immediately.
3729 : : *
3730 : : * If we have already started a transaction block, issue an error; also issue
3731 : : * an error if we appear to be running inside a user-defined function (which
3732 : : * could issue more commands and possibly cause a failure after the statement
3733 : : * completes). Subtransactions are verboten too.
3734 : : *
3735 : : * We must also set XACT_FLAGS_NEEDIMMEDIATECOMMIT in MyXactFlags, to ensure
3736 : : * that postgres.c follows through by committing after the statement is done.
3737 : : *
3738 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3739 : : * inside a function. (We will always fail if this is false, but it's
3740 : : * convenient to centralize the check here instead of making callers do it.)
3741 : : * stmtType: statement type name, for error messages.
3742 : : */
3743 : : void
3744 : 115838 : PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
3745 : : {
3746 : : /*
3747 : : * xact block already started?
3748 : : */
3749 [ + + ]: 115838 : if (IsTransactionBlock())
3750 [ + - ]: 82 : ereport(ERROR,
3751 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3752 : : /* translator: %s represents an SQL statement name */
3753 : : errmsg("%s cannot run inside a transaction block",
3754 : : stmtType)));
3755 : :
3756 : : /*
3757 : : * subtransaction?
3758 : : */
3759 [ - + ]: 115756 : if (IsSubTransaction())
3760 [ # # ]: 0 : ereport(ERROR,
3761 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3762 : : /* translator: %s represents an SQL statement name */
3763 : : errmsg("%s cannot run inside a subtransaction",
3764 : : stmtType)));
3765 : :
3766 : : /*
3767 : : * inside a function call?
3768 : : */
3769 [ + + ]: 115756 : if (!isTopLevel)
3770 [ + - ]: 8 : ereport(ERROR,
3771 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3772 : : /* translator: %s represents an SQL statement name */
3773 : : errmsg("%s cannot be executed from a function or procedure",
3774 : : stmtType)));
3775 : :
3776 : : /* If we got past IsTransactionBlock test, should be in default state */
3777 [ + + ]: 115748 : if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3778 [ - + ]: 114625 : CurrentTransactionState->blockState != TBLOCK_STARTED)
3779 [ # # ]: 0 : elog(FATAL, "cannot prevent transaction chain");
3780 : :
3781 : : /* All okay. Set the flag to make sure the right thing happens later. */
3782 : 115748 : MyXactFlags |= XACT_FLAGS_NEEDIMMEDIATECOMMIT;
3783 : 115748 : }
3784 : :
3785 : : /*
3786 : : * WarnNoTransactionBlock
3787 : : * RequireTransactionBlock
3788 : : *
3789 : : * These two functions allow for warnings or errors if a command is executed
3790 : : * outside of a transaction block. This is useful for commands that have no
3791 : : * effects that persist past transaction end (and so calling them outside a
3792 : : * transaction block is presumably an error). DECLARE CURSOR is an example.
3793 : : * While top-level transaction control commands (BEGIN/COMMIT/ABORT) and SET
3794 : : * that have no effect issue warnings, all other no-effect commands generate
3795 : : * errors.
3796 : : *
3797 : : * If we appear to be running inside a user-defined function, we do not
3798 : : * issue anything, since the function could issue more commands that make
3799 : : * use of the current statement's results. Likewise subtransactions.
3800 : : * Thus these are inverses for PreventInTransactionBlock.
3801 : : *
3802 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3803 : : * inside a function.
3804 : : * stmtType: statement type name, for warning or error messages.
3805 : : */
3806 : : void
3807 : 1600 : WarnNoTransactionBlock(bool isTopLevel, const char *stmtType)
3808 : : {
3809 : 1600 : CheckTransactionBlock(isTopLevel, false, stmtType);
3810 : 1600 : }
3811 : :
3812 : : void
3813 : 5331 : RequireTransactionBlock(bool isTopLevel, const char *stmtType)
3814 : : {
3815 : 5331 : CheckTransactionBlock(isTopLevel, true, stmtType);
3816 : 5308 : }
3817 : :
3818 : : /*
3819 : : * This is the implementation of the above two.
3820 : : */
3821 : : static void
3822 : 6931 : CheckTransactionBlock(bool isTopLevel, bool throwError, const char *stmtType)
3823 : : {
3824 : : /*
3825 : : * xact block already started?
3826 : : */
3827 [ + + ]: 6931 : if (IsTransactionBlock())
3828 : 6809 : return;
3829 : :
3830 : : /*
3831 : : * subtransaction?
3832 : : */
3833 [ - + ]: 122 : if (IsSubTransaction())
3834 : 0 : return;
3835 : :
3836 : : /*
3837 : : * inside a function call?
3838 : : */
3839 [ + + ]: 122 : if (!isTopLevel)
3840 : 85 : return;
3841 : :
3842 [ + + + - ]: 37 : ereport(throwError ? ERROR : WARNING,
3843 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3844 : : /* translator: %s represents an SQL statement name */
3845 : : errmsg("%s can only be used in transaction blocks",
3846 : : stmtType)));
3847 : : }
3848 : :
3849 : : /*
3850 : : * IsInTransactionBlock
3851 : : *
3852 : : * This routine is for statements that need to behave differently inside
3853 : : * a transaction block than when running as single commands. ANALYZE is
3854 : : * currently the only example.
3855 : : *
3856 : : * If this routine returns "false", then the calling statement is allowed
3857 : : * to perform internal transaction-commit-and-start cycles; there is not a
3858 : : * risk of messing up any transaction already in progress. (Note that this
3859 : : * is not the identical guarantee provided by PreventInTransactionBlock,
3860 : : * since we will not force a post-statement commit.)
3861 : : *
3862 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3863 : : * inside a function.
3864 : : */
3865 : : bool
3866 : 3361 : IsInTransactionBlock(bool isTopLevel)
3867 : : {
3868 : : /*
3869 : : * Return true on same conditions that would make
3870 : : * PreventInTransactionBlock error out
3871 : : */
3872 [ + + ]: 3361 : if (IsTransactionBlock())
3873 : 114 : return true;
3874 : :
3875 [ - + ]: 3247 : if (IsSubTransaction())
3876 : 0 : return true;
3877 : :
3878 [ + + ]: 3247 : if (!isTopLevel)
3879 : 76 : return true;
3880 : :
3881 [ + - ]: 3171 : if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3882 [ - + ]: 3171 : CurrentTransactionState->blockState != TBLOCK_STARTED)
3883 : 0 : return true;
3884 : :
3885 : 3171 : return false;
3886 : : }
3887 : :
3888 : :
3889 : : /*
3890 : : * Register or deregister callback functions for start- and end-of-xact
3891 : : * operations.
3892 : : *
3893 : : * These functions are intended for use by dynamically loaded modules.
3894 : : * For built-in modules we generally just hardwire the appropriate calls
3895 : : * (mainly because it's easier to control the order that way, where needed).
3896 : : *
3897 : : * At transaction end, the callback occurs post-commit or post-abort, so the
3898 : : * callback functions can only do noncritical cleanup.
3899 : : */
3900 : : void
3901 : 2412 : RegisterXactCallback(XactCallback callback, void *arg)
3902 : : {
3903 : : XactCallbackItem *item;
3904 : :
3905 : : item = (XactCallbackItem *)
3906 : 2412 : MemoryContextAlloc(TopMemoryContext, sizeof(XactCallbackItem));
3907 : 2412 : item->callback = callback;
3908 : 2412 : item->arg = arg;
3909 : 2412 : item->next = Xact_callbacks;
3910 : 2412 : Xact_callbacks = item;
3911 : 2412 : }
3912 : :
3913 : : void
3914 : 0 : UnregisterXactCallback(XactCallback callback, void *arg)
3915 : : {
3916 : : XactCallbackItem *item;
3917 : : XactCallbackItem *prev;
3918 : :
3919 : 0 : prev = NULL;
3920 [ # # ]: 0 : for (item = Xact_callbacks; item; prev = item, item = item->next)
3921 : : {
3922 [ # # # # ]: 0 : if (item->callback == callback && item->arg == arg)
3923 : : {
3924 [ # # ]: 0 : if (prev)
3925 : 0 : prev->next = item->next;
3926 : : else
3927 : 0 : Xact_callbacks = item->next;
3928 : 0 : pfree(item);
3929 : 0 : break;
3930 : : }
3931 : : }
3932 : 0 : }
3933 : :
3934 : : static void
3935 : 1285575 : CallXactCallbacks(XactEvent event)
3936 : : {
3937 : : XactCallbackItem *item;
3938 : : XactCallbackItem *next;
3939 : :
3940 [ + + ]: 1504144 : for (item = Xact_callbacks; item; item = next)
3941 : : {
3942 : : /* allow callbacks to unregister themselves when called */
3943 : 218571 : next = item->next;
3944 : 218571 : item->callback(event, item->arg);
3945 : : }
3946 : 1285573 : }
3947 : :
3948 : :
3949 : : /*
3950 : : * Register or deregister callback functions for start- and end-of-subxact
3951 : : * operations.
3952 : : *
3953 : : * Pretty much same as above, but for subtransaction events.
3954 : : *
3955 : : * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3956 : : * so the callback functions can only do noncritical cleanup. At
3957 : : * subtransaction start, the callback is called when the subtransaction has
3958 : : * finished initializing.
3959 : : */
3960 : : void
3961 : 2412 : RegisterSubXactCallback(SubXactCallback callback, void *arg)
3962 : : {
3963 : : SubXactCallbackItem *item;
3964 : :
3965 : : item = (SubXactCallbackItem *)
3966 : 2412 : MemoryContextAlloc(TopMemoryContext, sizeof(SubXactCallbackItem));
3967 : 2412 : item->callback = callback;
3968 : 2412 : item->arg = arg;
3969 : 2412 : item->next = SubXact_callbacks;
3970 : 2412 : SubXact_callbacks = item;
3971 : 2412 : }
3972 : :
3973 : : void
3974 : 0 : UnregisterSubXactCallback(SubXactCallback callback, void *arg)
3975 : : {
3976 : : SubXactCallbackItem *item;
3977 : : SubXactCallbackItem *prev;
3978 : :
3979 : 0 : prev = NULL;
3980 [ # # ]: 0 : for (item = SubXact_callbacks; item; prev = item, item = item->next)
3981 : : {
3982 [ # # # # ]: 0 : if (item->callback == callback && item->arg == arg)
3983 : : {
3984 [ # # ]: 0 : if (prev)
3985 : 0 : prev->next = item->next;
3986 : : else
3987 : 0 : SubXact_callbacks = item->next;
3988 : 0 : pfree(item);
3989 : 0 : break;
3990 : : }
3991 : : }
3992 : 0 : }
3993 : :
3994 : : static void
3995 : 63627 : CallSubXactCallbacks(SubXactEvent event,
3996 : : SubTransactionId mySubid,
3997 : : SubTransactionId parentSubid)
3998 : : {
3999 : : SubXactCallbackItem *item;
4000 : : SubXactCallbackItem *next;
4001 : :
4002 [ + + ]: 121159 : for (item = SubXact_callbacks; item; item = next)
4003 : : {
4004 : : /* allow callbacks to unregister themselves when called */
4005 : 57532 : next = item->next;
4006 : 57532 : item->callback(event, mySubid, parentSubid, item->arg);
4007 : : }
4008 : 63627 : }
4009 : :
4010 : :
4011 : : /* ----------------------------------------------------------------
4012 : : * transaction block support
4013 : : * ----------------------------------------------------------------
4014 : : */
4015 : :
4016 : : /*
4017 : : * BeginTransactionBlock
4018 : : * This executes a BEGIN command.
4019 : : */
4020 : : void
4021 : 12855 : BeginTransactionBlock(void)
4022 : : {
4023 : 12855 : TransactionState s = CurrentTransactionState;
4024 : :
4025 [ + + - - : 12855 : switch (s->blockState)
- ]
4026 : : {
4027 : : /*
4028 : : * We are not inside a transaction block, so allow one to begin.
4029 : : */
4030 : 12339 : case TBLOCK_STARTED:
4031 : 12339 : s->blockState = TBLOCK_BEGIN;
4032 : 12339 : break;
4033 : :
4034 : : /*
4035 : : * BEGIN converts an implicit transaction block to a regular one.
4036 : : * (Note that we allow this even if we've already done some
4037 : : * commands, which is a bit odd but matches historical practice.)
4038 : : */
4039 : 516 : case TBLOCK_IMPLICIT_INPROGRESS:
4040 : 516 : s->blockState = TBLOCK_BEGIN;
4041 : 516 : break;
4042 : :
4043 : : /*
4044 : : * Already a transaction block in progress.
4045 : : */
4046 : 0 : case TBLOCK_INPROGRESS:
4047 : : case TBLOCK_PARALLEL_INPROGRESS:
4048 : : case TBLOCK_SUBINPROGRESS:
4049 : : case TBLOCK_ABORT:
4050 : : case TBLOCK_SUBABORT:
4051 [ # # ]: 0 : ereport(WARNING,
4052 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
4053 : : errmsg("there is already a transaction in progress")));
4054 : 0 : break;
4055 : :
4056 : : /* These cases are invalid. */
4057 : 0 : case TBLOCK_DEFAULT:
4058 : : case TBLOCK_BEGIN:
4059 : : case TBLOCK_SUBBEGIN:
4060 : : case TBLOCK_END:
4061 : : case TBLOCK_SUBRELEASE:
4062 : : case TBLOCK_SUBCOMMIT:
4063 : : case TBLOCK_ABORT_END:
4064 : : case TBLOCK_SUBABORT_END:
4065 : : case TBLOCK_ABORT_PENDING:
4066 : : case TBLOCK_SUBABORT_PENDING:
4067 : : case TBLOCK_SUBRESTART:
4068 : : case TBLOCK_SUBABORT_RESTART:
4069 : : case TBLOCK_PREPARE:
4070 [ # # ]: 0 : elog(FATAL, "BeginTransactionBlock: unexpected state %s",
4071 : : BlockStateAsString(s->blockState));
4072 : : break;
4073 : : }
4074 : 12855 : }
4075 : :
4076 : : /*
4077 : : * PrepareTransactionBlock
4078 : : * This executes a PREPARE command.
4079 : : *
4080 : : * Since PREPARE may actually do a ROLLBACK, the result indicates what
4081 : : * happened: true for PREPARE, false for ROLLBACK.
4082 : : *
4083 : : * Note that we don't actually do anything here except change blockState.
4084 : : * The real work will be done in the upcoming PrepareTransaction().
4085 : : * We do it this way because it's not convenient to change memory context,
4086 : : * resource owner, etc while executing inside a Portal.
4087 : : */
4088 : : bool
4089 : 387 : PrepareTransactionBlock(const char *gid)
4090 : : {
4091 : : TransactionState s;
4092 : : bool result;
4093 : :
4094 : : /* Set up to commit the current transaction */
4095 : 387 : result = EndTransactionBlock(false);
4096 : :
4097 : : /* If successful, change outer tblock state to PREPARE */
4098 [ + + ]: 387 : if (result)
4099 : : {
4100 : 385 : s = CurrentTransactionState;
4101 : :
4102 [ + + ]: 499 : while (s->parent != NULL)
4103 : 114 : s = s->parent;
4104 : :
4105 [ + - ]: 385 : if (s->blockState == TBLOCK_END)
4106 : : {
4107 : : /* Save GID where PrepareTransaction can find it again */
4108 : 385 : prepareGID = MemoryContextStrdup(TopTransactionContext, gid);
4109 : :
4110 : 385 : s->blockState = TBLOCK_PREPARE;
4111 : : }
4112 : : else
4113 : : {
4114 : : /*
4115 : : * ignore case where we are not in a transaction;
4116 : : * EndTransactionBlock already issued a warning.
4117 : : */
4118 : : Assert(s->blockState == TBLOCK_STARTED ||
4119 : : s->blockState == TBLOCK_IMPLICIT_INPROGRESS);
4120 : : /* Don't send back a PREPARE result tag... */
4121 : 0 : result = false;
4122 : : }
4123 : : }
4124 : :
4125 : 387 : return result;
4126 : : }
4127 : :
4128 : : /*
4129 : : * EndTransactionBlock
4130 : : * This executes a COMMIT command.
4131 : : *
4132 : : * Since COMMIT may actually do a ROLLBACK, the result indicates what
4133 : : * happened: true for COMMIT, false for ROLLBACK.
4134 : : *
4135 : : * Note that we don't actually do anything here except change blockState.
4136 : : * The real work will be done in the upcoming CommitTransactionCommand().
4137 : : * We do it this way because it's not convenient to change memory context,
4138 : : * resource owner, etc while executing inside a Portal.
4139 : : */
4140 : : bool
4141 : 10217 : EndTransactionBlock(bool chain)
4142 : : {
4143 : 10217 : TransactionState s = CurrentTransactionState;
4144 : 10217 : bool result = false;
4145 : :
4146 [ + + + + : 10217 : switch (s->blockState)
+ + - -
- ]
4147 : : {
4148 : : /*
4149 : : * We are in a transaction block, so tell CommitTransactionCommand
4150 : : * to COMMIT.
4151 : : */
4152 : 9172 : case TBLOCK_INPROGRESS:
4153 : 9172 : s->blockState = TBLOCK_END;
4154 : 9172 : result = true;
4155 : 9172 : break;
4156 : :
4157 : : /*
4158 : : * We are in an implicit transaction block. If AND CHAIN was
4159 : : * specified, error. Otherwise commit, but issue a warning
4160 : : * because there was no explicit BEGIN before this.
4161 : : */
4162 : 32 : case TBLOCK_IMPLICIT_INPROGRESS:
4163 [ + + ]: 32 : if (chain)
4164 [ + - ]: 16 : ereport(ERROR,
4165 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4166 : : /* translator: %s represents an SQL statement name */
4167 : : errmsg("%s can only be used in transaction blocks",
4168 : : "COMMIT AND CHAIN")));
4169 : : else
4170 [ + - ]: 16 : ereport(WARNING,
4171 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4172 : : errmsg("there is no transaction in progress")));
4173 : 16 : s->blockState = TBLOCK_END;
4174 : 16 : result = true;
4175 : 16 : break;
4176 : :
4177 : : /*
4178 : : * We are in a failed transaction block. Tell
4179 : : * CommitTransactionCommand it's time to exit the block.
4180 : : */
4181 : 449 : case TBLOCK_ABORT:
4182 : 449 : s->blockState = TBLOCK_ABORT_END;
4183 : 449 : break;
4184 : :
4185 : : /*
4186 : : * We are in a live subtransaction block. Set up to subcommit all
4187 : : * open subtransactions and then commit the main transaction.
4188 : : */
4189 : 506 : case TBLOCK_SUBINPROGRESS:
4190 [ + + ]: 1105 : while (s->parent != NULL)
4191 : : {
4192 [ + - ]: 599 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4193 : 599 : s->blockState = TBLOCK_SUBCOMMIT;
4194 : : else
4195 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4196 : : BlockStateAsString(s->blockState));
4197 : 599 : s = s->parent;
4198 : : }
4199 [ + - ]: 506 : if (s->blockState == TBLOCK_INPROGRESS)
4200 : 506 : s->blockState = TBLOCK_END;
4201 : : else
4202 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4203 : : BlockStateAsString(s->blockState));
4204 : 506 : result = true;
4205 : 506 : break;
4206 : :
4207 : : /*
4208 : : * Here we are inside an aborted subtransaction. Treat the COMMIT
4209 : : * as ROLLBACK: set up to abort everything and exit the main
4210 : : * transaction.
4211 : : */
4212 : 42 : case TBLOCK_SUBABORT:
4213 [ + + ]: 84 : while (s->parent != NULL)
4214 : : {
4215 [ - + ]: 42 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4216 : 0 : s->blockState = TBLOCK_SUBABORT_PENDING;
4217 [ + - ]: 42 : else if (s->blockState == TBLOCK_SUBABORT)
4218 : 42 : s->blockState = TBLOCK_SUBABORT_END;
4219 : : else
4220 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4221 : : BlockStateAsString(s->blockState));
4222 : 42 : s = s->parent;
4223 : : }
4224 [ + - ]: 42 : if (s->blockState == TBLOCK_INPROGRESS)
4225 : 42 : s->blockState = TBLOCK_ABORT_PENDING;
4226 [ # # ]: 0 : else if (s->blockState == TBLOCK_ABORT)
4227 : 0 : s->blockState = TBLOCK_ABORT_END;
4228 : : else
4229 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4230 : : BlockStateAsString(s->blockState));
4231 : 42 : break;
4232 : :
4233 : : /*
4234 : : * The user issued COMMIT when not inside a transaction. For
4235 : : * COMMIT without CHAIN, issue a WARNING, staying in
4236 : : * TBLOCK_STARTED state. The upcoming call to
4237 : : * CommitTransactionCommand() will then close the transaction and
4238 : : * put us back into the default state. For COMMIT AND CHAIN,
4239 : : * error.
4240 : : */
4241 : 16 : case TBLOCK_STARTED:
4242 [ + + ]: 16 : if (chain)
4243 [ + - ]: 4 : ereport(ERROR,
4244 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4245 : : /* translator: %s represents an SQL statement name */
4246 : : errmsg("%s can only be used in transaction blocks",
4247 : : "COMMIT AND CHAIN")));
4248 : : else
4249 [ + - ]: 12 : ereport(WARNING,
4250 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4251 : : errmsg("there is no transaction in progress")));
4252 : 12 : result = true;
4253 : 12 : break;
4254 : :
4255 : : /*
4256 : : * The user issued a COMMIT that somehow ran inside a parallel
4257 : : * worker. We can't cope with that.
4258 : : */
4259 : 0 : case TBLOCK_PARALLEL_INPROGRESS:
4260 [ # # ]: 0 : ereport(FATAL,
4261 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4262 : : errmsg("cannot commit during a parallel operation")));
4263 : : break;
4264 : :
4265 : : /* These cases are invalid. */
4266 : 0 : case TBLOCK_DEFAULT:
4267 : : case TBLOCK_BEGIN:
4268 : : case TBLOCK_SUBBEGIN:
4269 : : case TBLOCK_END:
4270 : : case TBLOCK_SUBRELEASE:
4271 : : case TBLOCK_SUBCOMMIT:
4272 : : case TBLOCK_ABORT_END:
4273 : : case TBLOCK_SUBABORT_END:
4274 : : case TBLOCK_ABORT_PENDING:
4275 : : case TBLOCK_SUBABORT_PENDING:
4276 : : case TBLOCK_SUBRESTART:
4277 : : case TBLOCK_SUBABORT_RESTART:
4278 : : case TBLOCK_PREPARE:
4279 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4280 : : BlockStateAsString(s->blockState));
4281 : : break;
4282 : : }
4283 : :
4284 : : Assert(s->blockState == TBLOCK_STARTED ||
4285 : : s->blockState == TBLOCK_END ||
4286 : : s->blockState == TBLOCK_ABORT_END ||
4287 : : s->blockState == TBLOCK_ABORT_PENDING);
4288 : :
4289 : 10197 : s->chain = chain;
4290 : :
4291 : 10197 : return result;
4292 : : }
4293 : :
4294 : : /*
4295 : : * UserAbortTransactionBlock
4296 : : * This executes a ROLLBACK command.
4297 : : *
4298 : : * As above, we don't actually do anything here except change blockState.
4299 : : */
4300 : : void
4301 : 2431 : UserAbortTransactionBlock(bool chain)
4302 : : {
4303 : 2431 : TransactionState s = CurrentTransactionState;
4304 : :
4305 [ + + + + : 2431 : switch (s->blockState)
- - - ]
4306 : : {
4307 : : /*
4308 : : * We are inside a transaction block and we got a ROLLBACK command
4309 : : * from the user, so tell CommitTransactionCommand to abort and
4310 : : * exit the transaction block.
4311 : : */
4312 : 1771 : case TBLOCK_INPROGRESS:
4313 : 1771 : s->blockState = TBLOCK_ABORT_PENDING;
4314 : 1771 : break;
4315 : :
4316 : : /*
4317 : : * We are inside a failed transaction block and we got a ROLLBACK
4318 : : * command from the user. Abort processing is already done, so
4319 : : * CommitTransactionCommand just has to cleanup and go back to
4320 : : * idle state.
4321 : : */
4322 : 514 : case TBLOCK_ABORT:
4323 : 514 : s->blockState = TBLOCK_ABORT_END;
4324 : 514 : break;
4325 : :
4326 : : /*
4327 : : * We are inside a subtransaction. Mark everything up to top
4328 : : * level as exitable.
4329 : : */
4330 : 95 : case TBLOCK_SUBINPROGRESS:
4331 : : case TBLOCK_SUBABORT:
4332 [ + + ]: 354 : while (s->parent != NULL)
4333 : : {
4334 [ + + ]: 259 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4335 : 246 : s->blockState = TBLOCK_SUBABORT_PENDING;
4336 [ + - ]: 13 : else if (s->blockState == TBLOCK_SUBABORT)
4337 : 13 : s->blockState = TBLOCK_SUBABORT_END;
4338 : : else
4339 [ # # ]: 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4340 : : BlockStateAsString(s->blockState));
4341 : 259 : s = s->parent;
4342 : : }
4343 [ + - ]: 95 : if (s->blockState == TBLOCK_INPROGRESS)
4344 : 95 : s->blockState = TBLOCK_ABORT_PENDING;
4345 [ # # ]: 0 : else if (s->blockState == TBLOCK_ABORT)
4346 : 0 : s->blockState = TBLOCK_ABORT_END;
4347 : : else
4348 [ # # ]: 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4349 : : BlockStateAsString(s->blockState));
4350 : 95 : break;
4351 : :
4352 : : /*
4353 : : * The user issued ABORT when not inside a transaction. For
4354 : : * ROLLBACK without CHAIN, issue a WARNING and go to abort state.
4355 : : * The upcoming call to CommitTransactionCommand() will then put
4356 : : * us back into the default state. For ROLLBACK AND CHAIN, error.
4357 : : *
4358 : : * We do the same thing with ABORT inside an implicit transaction,
4359 : : * although in this case we might be rolling back actual database
4360 : : * state changes. (It's debatable whether we should issue a
4361 : : * WARNING in this case, but we have done so historically.)
4362 : : */
4363 : 51 : case TBLOCK_STARTED:
4364 : : case TBLOCK_IMPLICIT_INPROGRESS:
4365 [ + + ]: 51 : if (chain)
4366 [ + - ]: 20 : ereport(ERROR,
4367 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4368 : : /* translator: %s represents an SQL statement name */
4369 : : errmsg("%s can only be used in transaction blocks",
4370 : : "ROLLBACK AND CHAIN")));
4371 : : else
4372 [ + - ]: 31 : ereport(WARNING,
4373 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4374 : : errmsg("there is no transaction in progress")));
4375 : 31 : s->blockState = TBLOCK_ABORT_PENDING;
4376 : 31 : break;
4377 : :
4378 : : /*
4379 : : * The user issued an ABORT that somehow ran inside a parallel
4380 : : * worker. We can't cope with that.
4381 : : */
4382 : 0 : case TBLOCK_PARALLEL_INPROGRESS:
4383 [ # # ]: 0 : ereport(FATAL,
4384 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4385 : : errmsg("cannot abort during a parallel operation")));
4386 : : break;
4387 : :
4388 : : /* These cases are invalid. */
4389 : 0 : case TBLOCK_DEFAULT:
4390 : : case TBLOCK_BEGIN:
4391 : : case TBLOCK_SUBBEGIN:
4392 : : case TBLOCK_END:
4393 : : case TBLOCK_SUBRELEASE:
4394 : : case TBLOCK_SUBCOMMIT:
4395 : : case TBLOCK_ABORT_END:
4396 : : case TBLOCK_SUBABORT_END:
4397 : : case TBLOCK_ABORT_PENDING:
4398 : : case TBLOCK_SUBABORT_PENDING:
4399 : : case TBLOCK_SUBRESTART:
4400 : : case TBLOCK_SUBABORT_RESTART:
4401 : : case TBLOCK_PREPARE:
4402 [ # # ]: 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4403 : : BlockStateAsString(s->blockState));
4404 : : break;
4405 : : }
4406 : :
4407 : : Assert(s->blockState == TBLOCK_ABORT_END ||
4408 : : s->blockState == TBLOCK_ABORT_PENDING);
4409 : :
4410 : 2411 : s->chain = chain;
4411 : 2411 : }
4412 : :
4413 : : /*
4414 : : * BeginImplicitTransactionBlock
4415 : : * Start an implicit transaction block if we're not already in one.
4416 : : *
4417 : : * Unlike BeginTransactionBlock, this is called directly from the main loop
4418 : : * in postgres.c, not within a Portal. So we can just change blockState
4419 : : * without a lot of ceremony. We do not expect caller to do
4420 : : * CommitTransactionCommand/StartTransactionCommand.
4421 : : */
4422 : : void
4423 : 53684 : BeginImplicitTransactionBlock(void)
4424 : : {
4425 : 53684 : TransactionState s = CurrentTransactionState;
4426 : :
4427 : : /*
4428 : : * If we are in STARTED state (that is, no transaction block is open),
4429 : : * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
4430 : : * block.
4431 : : *
4432 : : * For caller convenience, we consider all other transaction states as
4433 : : * legal here; otherwise the caller would need its own state check, which
4434 : : * seems rather pointless.
4435 : : */
4436 [ + + ]: 53684 : if (s->blockState == TBLOCK_STARTED)
4437 : 6385 : s->blockState = TBLOCK_IMPLICIT_INPROGRESS;
4438 : 53684 : }
4439 : :
4440 : : /*
4441 : : * EndImplicitTransactionBlock
4442 : : * End an implicit transaction block, if we're in one.
4443 : : *
4444 : : * Like EndTransactionBlock, we just make any needed blockState change here.
4445 : : * The real work will be done in the upcoming CommitTransactionCommand().
4446 : : */
4447 : : void
4448 : 21260 : EndImplicitTransactionBlock(void)
4449 : : {
4450 : 21260 : TransactionState s = CurrentTransactionState;
4451 : :
4452 : : /*
4453 : : * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
4454 : : * allowing CommitTransactionCommand to commit whatever happened during
4455 : : * the implicit transaction block as though it were a single statement.
4456 : : *
4457 : : * For caller convenience, we consider all other transaction states as
4458 : : * legal here; otherwise the caller would need its own state check, which
4459 : : * seems rather pointless.
4460 : : */
4461 [ + + ]: 21260 : if (s->blockState == TBLOCK_IMPLICIT_INPROGRESS)
4462 : 5755 : s->blockState = TBLOCK_STARTED;
4463 : 21260 : }
4464 : :
4465 : : /*
4466 : : * DefineSavepoint
4467 : : * This executes a SAVEPOINT command.
4468 : : */
4469 : : void
4470 : 1777 : DefineSavepoint(const char *name)
4471 : : {
4472 : 1777 : TransactionState s = CurrentTransactionState;
4473 : :
4474 : : /*
4475 : : * Workers synchronize transaction state at the beginning of each parallel
4476 : : * operation, so we can't account for new subtransactions after that
4477 : : * point. (Note that this check will certainly error out if s->blockState
4478 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4479 : : * below.)
4480 : : */
4481 [ + - - + ]: 1777 : if (IsInParallelMode() || IsParallelWorker())
4482 [ # # ]: 0 : ereport(ERROR,
4483 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4484 : : errmsg("cannot define savepoints during a parallel operation")));
4485 : :
4486 [ + + - - ]: 1777 : switch (s->blockState)
4487 : : {
4488 : 1769 : case TBLOCK_INPROGRESS:
4489 : : case TBLOCK_SUBINPROGRESS:
4490 : : /* Normal subtransaction start */
4491 : 1769 : PushTransaction();
4492 : 1769 : s = CurrentTransactionState; /* changed by push */
4493 : :
4494 : : /*
4495 : : * Savepoint names, like the TransactionState block itself, live
4496 : : * in TopTransactionContext.
4497 : : */
4498 [ + + ]: 1769 : if (name)
4499 : 1210 : s->name = MemoryContextStrdup(TopTransactionContext, name);
4500 : 1769 : break;
4501 : :
4502 : : /*
4503 : : * We disallow savepoint commands in implicit transaction blocks.
4504 : : * There would be no great difficulty in allowing them so far as
4505 : : * this module is concerned, but a savepoint seems inconsistent
4506 : : * with exec_simple_query's behavior of abandoning the whole query
4507 : : * string upon error. Also, the point of an implicit transaction
4508 : : * block (as opposed to a regular one) is to automatically close
4509 : : * after an error, so it's hard to see how a savepoint would fit
4510 : : * into that.
4511 : : *
4512 : : * The error messages for this are phrased as if there were no
4513 : : * active transaction block at all, which is historical but
4514 : : * perhaps could be improved.
4515 : : */
4516 : 8 : case TBLOCK_IMPLICIT_INPROGRESS:
4517 [ + - ]: 8 : ereport(ERROR,
4518 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4519 : : /* translator: %s represents an SQL statement name */
4520 : : errmsg("%s can only be used in transaction blocks",
4521 : : "SAVEPOINT")));
4522 : : break;
4523 : :
4524 : : /* These cases are invalid. */
4525 : 0 : case TBLOCK_DEFAULT:
4526 : : case TBLOCK_STARTED:
4527 : : case TBLOCK_BEGIN:
4528 : : case TBLOCK_PARALLEL_INPROGRESS:
4529 : : case TBLOCK_SUBBEGIN:
4530 : : case TBLOCK_END:
4531 : : case TBLOCK_SUBRELEASE:
4532 : : case TBLOCK_SUBCOMMIT:
4533 : : case TBLOCK_ABORT:
4534 : : case TBLOCK_SUBABORT:
4535 : : case TBLOCK_ABORT_END:
4536 : : case TBLOCK_SUBABORT_END:
4537 : : case TBLOCK_ABORT_PENDING:
4538 : : case TBLOCK_SUBABORT_PENDING:
4539 : : case TBLOCK_SUBRESTART:
4540 : : case TBLOCK_SUBABORT_RESTART:
4541 : : case TBLOCK_PREPARE:
4542 [ # # ]: 0 : elog(FATAL, "DefineSavepoint: unexpected state %s",
4543 : : BlockStateAsString(s->blockState));
4544 : : break;
4545 : : }
4546 : 1769 : }
4547 : :
4548 : : /*
4549 : : * ReleaseSavepoint
4550 : : * This executes a RELEASE command.
4551 : : *
4552 : : * As above, we don't actually do anything here except change blockState.
4553 : : */
4554 : : void
4555 : 187 : ReleaseSavepoint(const char *name)
4556 : : {
4557 : 187 : TransactionState s = CurrentTransactionState;
4558 : : TransactionState target,
4559 : : xact;
4560 : :
4561 : : /*
4562 : : * Workers synchronize transaction state at the beginning of each parallel
4563 : : * operation, so we can't account for transaction state change after that
4564 : : * point. (Note that this check will certainly error out if s->blockState
4565 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4566 : : * below.)
4567 : : */
4568 [ + - - + ]: 187 : if (IsInParallelMode() || IsParallelWorker())
4569 [ # # ]: 0 : ereport(ERROR,
4570 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4571 : : errmsg("cannot release savepoints during a parallel operation")));
4572 : :
4573 [ - + + - : 187 : switch (s->blockState)
- ]
4574 : : {
4575 : : /*
4576 : : * We can't release a savepoint if there is no savepoint defined.
4577 : : */
4578 : 0 : case TBLOCK_INPROGRESS:
4579 [ # # ]: 0 : ereport(ERROR,
4580 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4581 : : errmsg("savepoint \"%s\" does not exist", name)));
4582 : : break;
4583 : :
4584 : 4 : case TBLOCK_IMPLICIT_INPROGRESS:
4585 : : /* See comment about implicit transactions in DefineSavepoint */
4586 [ + - ]: 4 : ereport(ERROR,
4587 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4588 : : /* translator: %s represents an SQL statement name */
4589 : : errmsg("%s can only be used in transaction blocks",
4590 : : "RELEASE SAVEPOINT")));
4591 : : break;
4592 : :
4593 : : /*
4594 : : * We are in a non-aborted subtransaction. This is the only valid
4595 : : * case.
4596 : : */
4597 : 183 : case TBLOCK_SUBINPROGRESS:
4598 : 183 : break;
4599 : :
4600 : : /* These cases are invalid. */
4601 : 0 : case TBLOCK_DEFAULT:
4602 : : case TBLOCK_STARTED:
4603 : : case TBLOCK_BEGIN:
4604 : : case TBLOCK_PARALLEL_INPROGRESS:
4605 : : case TBLOCK_SUBBEGIN:
4606 : : case TBLOCK_END:
4607 : : case TBLOCK_SUBRELEASE:
4608 : : case TBLOCK_SUBCOMMIT:
4609 : : case TBLOCK_ABORT:
4610 : : case TBLOCK_SUBABORT:
4611 : : case TBLOCK_ABORT_END:
4612 : : case TBLOCK_SUBABORT_END:
4613 : : case TBLOCK_ABORT_PENDING:
4614 : : case TBLOCK_SUBABORT_PENDING:
4615 : : case TBLOCK_SUBRESTART:
4616 : : case TBLOCK_SUBABORT_RESTART:
4617 : : case TBLOCK_PREPARE:
4618 [ # # ]: 0 : elog(FATAL, "ReleaseSavepoint: unexpected state %s",
4619 : : BlockStateAsString(s->blockState));
4620 : : break;
4621 : : }
4622 : :
4623 [ + - ]: 270 : for (target = s; target; target = target->parent)
4624 : : {
4625 [ + - + + ]: 270 : if (target->name && strcmp(target->name, name) == 0)
4626 : 183 : break;
4627 : : }
4628 : :
4629 [ - + ]: 183 : if (!target)
4630 [ # # ]: 0 : ereport(ERROR,
4631 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4632 : : errmsg("savepoint \"%s\" does not exist", name)));
4633 : :
4634 : : /* disallow crossing savepoint level boundaries */
4635 [ - + ]: 183 : if (target->savepointLevel != s->savepointLevel)
4636 [ # # ]: 0 : ereport(ERROR,
4637 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4638 : : errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4639 : :
4640 : : /*
4641 : : * Mark "commit pending" all subtransactions up to the target
4642 : : * subtransaction. The actual commits will happen when control gets to
4643 : : * CommitTransactionCommand.
4644 : : */
4645 : 183 : xact = CurrentTransactionState;
4646 : : for (;;)
4647 : : {
4648 : 87 : Assert(xact->blockState == TBLOCK_SUBINPROGRESS);
4649 : 270 : xact->blockState = TBLOCK_SUBRELEASE;
4650 [ + + ]: 270 : if (xact == target)
4651 : 183 : break;
4652 : 87 : xact = xact->parent;
4653 : : Assert(xact);
4654 : : }
4655 : 183 : }
4656 : :
4657 : : /*
4658 : : * RollbackToSavepoint
4659 : : * This executes a ROLLBACK TO <savepoint> command.
4660 : : *
4661 : : * As above, we don't actually do anything here except change blockState.
4662 : : */
4663 : : void
4664 : 567 : RollbackToSavepoint(const char *name)
4665 : : {
4666 : 567 : TransactionState s = CurrentTransactionState;
4667 : : TransactionState target,
4668 : : xact;
4669 : :
4670 : : /*
4671 : : * Workers synchronize transaction state at the beginning of each parallel
4672 : : * operation, so we can't account for transaction state change after that
4673 : : * point. (Note that this check will certainly error out if s->blockState
4674 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4675 : : * below.)
4676 : : */
4677 [ + - - + ]: 567 : if (IsInParallelMode() || IsParallelWorker())
4678 [ # # ]: 0 : ereport(ERROR,
4679 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4680 : : errmsg("cannot rollback to savepoints during a parallel operation")));
4681 : :
4682 [ + + + - : 567 : switch (s->blockState)
- ]
4683 : : {
4684 : : /*
4685 : : * We can't rollback to a savepoint if there is no savepoint
4686 : : * defined.
4687 : : */
4688 : 4 : case TBLOCK_INPROGRESS:
4689 : : case TBLOCK_ABORT:
4690 [ + - ]: 4 : ereport(ERROR,
4691 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4692 : : errmsg("savepoint \"%s\" does not exist", name)));
4693 : : break;
4694 : :
4695 : 4 : case TBLOCK_IMPLICIT_INPROGRESS:
4696 : : /* See comment about implicit transactions in DefineSavepoint */
4697 [ + - ]: 4 : ereport(ERROR,
4698 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4699 : : /* translator: %s represents an SQL statement name */
4700 : : errmsg("%s can only be used in transaction blocks",
4701 : : "ROLLBACK TO SAVEPOINT")));
4702 : : break;
4703 : :
4704 : : /*
4705 : : * There is at least one savepoint, so proceed.
4706 : : */
4707 : 559 : case TBLOCK_SUBINPROGRESS:
4708 : : case TBLOCK_SUBABORT:
4709 : 559 : break;
4710 : :
4711 : : /* These cases are invalid. */
4712 : 0 : case TBLOCK_DEFAULT:
4713 : : case TBLOCK_STARTED:
4714 : : case TBLOCK_BEGIN:
4715 : : case TBLOCK_PARALLEL_INPROGRESS:
4716 : : case TBLOCK_SUBBEGIN:
4717 : : case TBLOCK_END:
4718 : : case TBLOCK_SUBRELEASE:
4719 : : case TBLOCK_SUBCOMMIT:
4720 : : case TBLOCK_ABORT_END:
4721 : : case TBLOCK_SUBABORT_END:
4722 : : case TBLOCK_ABORT_PENDING:
4723 : : case TBLOCK_SUBABORT_PENDING:
4724 : : case TBLOCK_SUBRESTART:
4725 : : case TBLOCK_SUBABORT_RESTART:
4726 : : case TBLOCK_PREPARE:
4727 [ # # ]: 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4728 : : BlockStateAsString(s->blockState));
4729 : : break;
4730 : : }
4731 : :
4732 [ + - ]: 597 : for (target = s; target; target = target->parent)
4733 : : {
4734 [ + - + + ]: 597 : if (target->name && strcmp(target->name, name) == 0)
4735 : 559 : break;
4736 : : }
4737 : :
4738 [ - + ]: 559 : if (!target)
4739 [ # # ]: 0 : ereport(ERROR,
4740 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4741 : : errmsg("savepoint \"%s\" does not exist", name)));
4742 : :
4743 : : /* disallow crossing savepoint level boundaries */
4744 [ - + ]: 559 : if (target->savepointLevel != s->savepointLevel)
4745 [ # # ]: 0 : ereport(ERROR,
4746 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4747 : : errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4748 : :
4749 : : /*
4750 : : * Mark "abort pending" all subtransactions up to the target
4751 : : * subtransaction. The actual aborts will happen when control gets to
4752 : : * CommitTransactionCommand.
4753 : : */
4754 : 559 : xact = CurrentTransactionState;
4755 : : for (;;)
4756 : : {
4757 [ + + ]: 597 : if (xact == target)
4758 : 559 : break;
4759 [ + - ]: 38 : if (xact->blockState == TBLOCK_SUBINPROGRESS)
4760 : 38 : xact->blockState = TBLOCK_SUBABORT_PENDING;
4761 [ # # ]: 0 : else if (xact->blockState == TBLOCK_SUBABORT)
4762 : 0 : xact->blockState = TBLOCK_SUBABORT_END;
4763 : : else
4764 [ # # ]: 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4765 : : BlockStateAsString(xact->blockState));
4766 : 38 : xact = xact->parent;
4767 : : Assert(xact);
4768 : : }
4769 : :
4770 : : /* And mark the target as "restart pending" */
4771 [ + + ]: 559 : if (xact->blockState == TBLOCK_SUBINPROGRESS)
4772 : 348 : xact->blockState = TBLOCK_SUBRESTART;
4773 [ + - ]: 211 : else if (xact->blockState == TBLOCK_SUBABORT)
4774 : 211 : xact->blockState = TBLOCK_SUBABORT_RESTART;
4775 : : else
4776 [ # # ]: 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4777 : : BlockStateAsString(xact->blockState));
4778 : 559 : }
4779 : :
4780 : : /*
4781 : : * BeginInternalSubTransaction
4782 : : * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
4783 : : * TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_END,
4784 : : * and TBLOCK_PREPARE states, and therefore it can safely be used in
4785 : : * functions that might be called when not inside a BEGIN block or when
4786 : : * running deferred triggers at COMMIT/PREPARE time. Also, it
4787 : : * automatically does CommitTransactionCommand/StartTransactionCommand
4788 : : * instead of expecting the caller to do it.
4789 : : */
4790 : : void
4791 : 21341 : BeginInternalSubTransaction(const char *name)
4792 : : {
4793 : 21341 : TransactionState s = CurrentTransactionState;
4794 : 21341 : bool save_ExitOnAnyError = ExitOnAnyError;
4795 : :
4796 : : /*
4797 : : * Errors within this function are improbable, but if one does happen we
4798 : : * force a FATAL exit. Callers generally aren't prepared to handle losing
4799 : : * control, and moreover our transaction state is probably corrupted if we
4800 : : * fail partway through; so an ordinary ERROR longjmp isn't okay.
4801 : : */
4802 : 21341 : ExitOnAnyError = true;
4803 : :
4804 : : /*
4805 : : * We do not check for parallel mode here. It's permissible to start and
4806 : : * end "internal" subtransactions while in parallel mode, so long as no
4807 : : * new XIDs or command IDs are assigned. Enforcement of that occurs in
4808 : : * AssignTransactionId() and CommandCounterIncrement().
4809 : : */
4810 : :
4811 [ + - - ]: 21341 : switch (s->blockState)
4812 : : {
4813 : 21341 : case TBLOCK_STARTED:
4814 : : case TBLOCK_INPROGRESS:
4815 : : case TBLOCK_IMPLICIT_INPROGRESS:
4816 : : case TBLOCK_PARALLEL_INPROGRESS:
4817 : : case TBLOCK_END:
4818 : : case TBLOCK_PREPARE:
4819 : : case TBLOCK_SUBINPROGRESS:
4820 : : /* Normal subtransaction start */
4821 : 21341 : PushTransaction();
4822 : 21341 : s = CurrentTransactionState; /* changed by push */
4823 : :
4824 : : /*
4825 : : * Savepoint names, like the TransactionState block itself, live
4826 : : * in TopTransactionContext.
4827 : : */
4828 [ + + ]: 21341 : if (name)
4829 : 1039 : s->name = MemoryContextStrdup(TopTransactionContext, name);
4830 : 21341 : break;
4831 : :
4832 : : /* These cases are invalid. */
4833 : 0 : case TBLOCK_DEFAULT:
4834 : : case TBLOCK_BEGIN:
4835 : : case TBLOCK_SUBBEGIN:
4836 : : case TBLOCK_SUBRELEASE:
4837 : : case TBLOCK_SUBCOMMIT:
4838 : : case TBLOCK_ABORT:
4839 : : case TBLOCK_SUBABORT:
4840 : : case TBLOCK_ABORT_END:
4841 : : case TBLOCK_SUBABORT_END:
4842 : : case TBLOCK_ABORT_PENDING:
4843 : : case TBLOCK_SUBABORT_PENDING:
4844 : : case TBLOCK_SUBRESTART:
4845 : : case TBLOCK_SUBABORT_RESTART:
4846 [ # # ]: 0 : elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4847 : : BlockStateAsString(s->blockState));
4848 : : break;
4849 : : }
4850 : :
4851 : 21341 : CommitTransactionCommand();
4852 : 21341 : StartTransactionCommand();
4853 : :
4854 : 21341 : ExitOnAnyError = save_ExitOnAnyError;
4855 : 21341 : }
4856 : :
4857 : : /*
4858 : : * ReleaseCurrentSubTransaction
4859 : : *
4860 : : * RELEASE (ie, commit) the innermost subtransaction, regardless of its
4861 : : * savepoint name (if any).
4862 : : * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4863 : : */
4864 : : void
4865 : 16538 : ReleaseCurrentSubTransaction(void)
4866 : : {
4867 : 16538 : TransactionState s = CurrentTransactionState;
4868 : :
4869 : : /*
4870 : : * We do not check for parallel mode here. It's permissible to start and
4871 : : * end "internal" subtransactions while in parallel mode, so long as no
4872 : : * new XIDs or command IDs are assigned.
4873 : : */
4874 : :
4875 [ - + ]: 16538 : if (s->blockState != TBLOCK_SUBINPROGRESS)
4876 [ # # ]: 0 : elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
4877 : : BlockStateAsString(s->blockState));
4878 : : Assert(s->state == TRANS_INPROGRESS);
4879 : 16538 : MemoryContextSwitchTo(CurTransactionContext);
4880 : 16538 : CommitSubTransaction();
4881 : 16538 : s = CurrentTransactionState; /* changed by pop */
4882 : : Assert(s->state == TRANS_INPROGRESS);
4883 : 16538 : }
4884 : :
4885 : : /*
4886 : : * RollbackAndReleaseCurrentSubTransaction
4887 : : *
4888 : : * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
4889 : : * of its savepoint name (if any).
4890 : : * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4891 : : */
4892 : : void
4893 : 4803 : RollbackAndReleaseCurrentSubTransaction(void)
4894 : : {
4895 : 4803 : TransactionState s = CurrentTransactionState;
4896 : :
4897 : : /*
4898 : : * We do not check for parallel mode here. It's permissible to start and
4899 : : * end "internal" subtransactions while in parallel mode, so long as no
4900 : : * new XIDs or command IDs are assigned.
4901 : : */
4902 : :
4903 [ + - - ]: 4803 : switch (s->blockState)
4904 : : {
4905 : : /* Must be in a subtransaction */
4906 : 4803 : case TBLOCK_SUBINPROGRESS:
4907 : : case TBLOCK_SUBABORT:
4908 : 4803 : break;
4909 : :
4910 : : /* These cases are invalid. */
4911 : 0 : case TBLOCK_DEFAULT:
4912 : : case TBLOCK_STARTED:
4913 : : case TBLOCK_BEGIN:
4914 : : case TBLOCK_IMPLICIT_INPROGRESS:
4915 : : case TBLOCK_PARALLEL_INPROGRESS:
4916 : : case TBLOCK_SUBBEGIN:
4917 : : case TBLOCK_INPROGRESS:
4918 : : case TBLOCK_END:
4919 : : case TBLOCK_SUBRELEASE:
4920 : : case TBLOCK_SUBCOMMIT:
4921 : : case TBLOCK_ABORT:
4922 : : case TBLOCK_ABORT_END:
4923 : : case TBLOCK_SUBABORT_END:
4924 : : case TBLOCK_ABORT_PENDING:
4925 : : case TBLOCK_SUBABORT_PENDING:
4926 : : case TBLOCK_SUBRESTART:
4927 : : case TBLOCK_SUBABORT_RESTART:
4928 : : case TBLOCK_PREPARE:
4929 [ # # ]: 0 : elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
4930 : : BlockStateAsString(s->blockState));
4931 : : break;
4932 : : }
4933 : :
4934 : : /*
4935 : : * Abort the current subtransaction, if needed.
4936 : : */
4937 [ + + ]: 4803 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4938 : 3764 : AbortSubTransaction();
4939 : :
4940 : : /* And clean it up, too */
4941 : 4803 : CleanupSubTransaction();
4942 : :
4943 : 4803 : s = CurrentTransactionState; /* changed by pop */
4944 : : Assert(s->blockState == TBLOCK_SUBINPROGRESS ||
4945 : : s->blockState == TBLOCK_INPROGRESS ||
4946 : : s->blockState == TBLOCK_IMPLICIT_INPROGRESS ||
4947 : : s->blockState == TBLOCK_PARALLEL_INPROGRESS ||
4948 : : s->blockState == TBLOCK_END ||
4949 : : s->blockState == TBLOCK_PREPARE ||
4950 : : s->blockState == TBLOCK_STARTED);
4951 : 4803 : }
4952 : :
4953 : : /*
4954 : : * AbortOutOfAnyTransaction
4955 : : *
4956 : : * This routine is provided for error recovery purposes. It aborts any
4957 : : * active transaction or transaction block, leaving the system in a known
4958 : : * idle state.
4959 : : */
4960 : : void
4961 : 22339 : AbortOutOfAnyTransaction(void)
4962 : : {
4963 : 22339 : TransactionState s = CurrentTransactionState;
4964 : :
4965 : : /* Ensure we're not running in a doomed memory context */
4966 : 22339 : AtAbort_Memory();
4967 : :
4968 : : /*
4969 : : * Get out of any transaction or nested transaction
4970 : : */
4971 : : do
4972 : : {
4973 [ + + + + : 22341 : switch (s->blockState)
- - ]
4974 : : {
4975 : 21570 : case TBLOCK_DEFAULT:
4976 [ - + ]: 21570 : if (s->state == TRANS_DEFAULT)
4977 : : {
4978 : : /* Not in a transaction, do nothing */
4979 : : }
4980 : : else
4981 : : {
4982 : : /*
4983 : : * We can get here after an error during transaction start
4984 : : * (state will be TRANS_START). Need to clean up the
4985 : : * incompletely started transaction. First, adjust the
4986 : : * low-level state to suppress warning message from
4987 : : * AbortTransaction.
4988 : : */
4989 [ # # ]: 0 : if (s->state == TRANS_START)
4990 : 0 : s->state = TRANS_INPROGRESS;
4991 : 0 : AbortTransaction();
4992 : 0 : CleanupTransaction();
4993 : : }
4994 : 21570 : break;
4995 : 750 : case TBLOCK_STARTED:
4996 : : case TBLOCK_BEGIN:
4997 : : case TBLOCK_INPROGRESS:
4998 : : case TBLOCK_IMPLICIT_INPROGRESS:
4999 : : case TBLOCK_PARALLEL_INPROGRESS:
5000 : : case TBLOCK_END:
5001 : : case TBLOCK_ABORT_PENDING:
5002 : : case TBLOCK_PREPARE:
5003 : : /* In a transaction, so clean up */
5004 : 750 : AbortTransaction();
5005 : 750 : CleanupTransaction();
5006 : 750 : s->blockState = TBLOCK_DEFAULT;
5007 : 750 : break;
5008 : 19 : case TBLOCK_ABORT:
5009 : : case TBLOCK_ABORT_END:
5010 : :
5011 : : /*
5012 : : * AbortTransaction is already done, still need Cleanup.
5013 : : * However, if we failed partway through running ROLLBACK,
5014 : : * there will be an active portal running that command, which
5015 : : * we need to shut down before doing CleanupTransaction.
5016 : : */
5017 : 19 : AtAbort_Portals();
5018 : 19 : CleanupTransaction();
5019 : 19 : s->blockState = TBLOCK_DEFAULT;
5020 : 19 : break;
5021 : :
5022 : : /*
5023 : : * In a subtransaction, so clean it up and abort parent too
5024 : : */
5025 : 2 : case TBLOCK_SUBBEGIN:
5026 : : case TBLOCK_SUBINPROGRESS:
5027 : : case TBLOCK_SUBRELEASE:
5028 : : case TBLOCK_SUBCOMMIT:
5029 : : case TBLOCK_SUBABORT_PENDING:
5030 : : case TBLOCK_SUBRESTART:
5031 : 2 : AbortSubTransaction();
5032 : 2 : CleanupSubTransaction();
5033 : 2 : s = CurrentTransactionState; /* changed by pop */
5034 : 2 : break;
5035 : :
5036 : 0 : case TBLOCK_SUBABORT:
5037 : : case TBLOCK_SUBABORT_END:
5038 : : case TBLOCK_SUBABORT_RESTART:
5039 : : /* As above, but AbortSubTransaction already done */
5040 [ # # ]: 0 : if (s->curTransactionOwner)
5041 : : {
5042 : : /* As in TBLOCK_ABORT, might have a live portal to zap */
5043 : 0 : AtSubAbort_Portals(s->subTransactionId,
5044 : 0 : s->parent->subTransactionId,
5045 : : s->curTransactionOwner,
5046 : 0 : s->parent->curTransactionOwner);
5047 : : }
5048 : 0 : CleanupSubTransaction();
5049 : 0 : s = CurrentTransactionState; /* changed by pop */
5050 : 0 : break;
5051 : : }
5052 [ + + ]: 22341 : } while (s->blockState != TBLOCK_DEFAULT);
5053 : :
5054 : : /* Should be out of all subxacts now */
5055 : : Assert(s->parent == NULL);
5056 : :
5057 : : /*
5058 : : * Revert to TopMemoryContext, to ensure we exit in a well-defined state
5059 : : * whether there were any transactions to close or not. (Callers that
5060 : : * don't intend to exit soon should switch to some other context to avoid
5061 : : * long-term memory leaks.)
5062 : : */
5063 : 22339 : MemoryContextSwitchTo(TopMemoryContext);
5064 : 22339 : }
5065 : :
5066 : : /*
5067 : : * IsTransactionBlock --- are we within a transaction block?
5068 : : */
5069 : : bool
5070 : 360776 : IsTransactionBlock(void)
5071 : : {
5072 : 360776 : TransactionState s = CurrentTransactionState;
5073 : :
5074 [ + + + + ]: 360776 : if (s->blockState == TBLOCK_DEFAULT || s->blockState == TBLOCK_STARTED)
5075 : 288381 : return false;
5076 : :
5077 : 72395 : return true;
5078 : : }
5079 : :
5080 : : /*
5081 : : * IsTransactionOrTransactionBlock --- are we within either a transaction
5082 : : * or a transaction block? (The backend is only really "idle" when this
5083 : : * returns false.)
5084 : : *
5085 : : * This should match up with IsTransactionBlock and IsTransactionState.
5086 : : */
5087 : : bool
5088 : 478810 : IsTransactionOrTransactionBlock(void)
5089 : : {
5090 : 478810 : TransactionState s = CurrentTransactionState;
5091 : :
5092 [ + + ]: 478810 : if (s->blockState == TBLOCK_DEFAULT)
5093 : 380070 : return false;
5094 : :
5095 : 98740 : return true;
5096 : : }
5097 : :
5098 : : /*
5099 : : * TransactionBlockStatusCode - return status code to send in ReadyForQuery
5100 : : */
5101 : : char
5102 : 434774 : TransactionBlockStatusCode(void)
5103 : : {
5104 : 434774 : TransactionState s = CurrentTransactionState;
5105 : :
5106 [ + + + - ]: 434774 : switch (s->blockState)
5107 : : {
5108 : 336722 : case TBLOCK_DEFAULT:
5109 : : case TBLOCK_STARTED:
5110 : 336722 : return 'I'; /* idle --- not in transaction */
5111 : 96725 : case TBLOCK_BEGIN:
5112 : : case TBLOCK_SUBBEGIN:
5113 : : case TBLOCK_INPROGRESS:
5114 : : case TBLOCK_IMPLICIT_INPROGRESS:
5115 : : case TBLOCK_PARALLEL_INPROGRESS:
5116 : : case TBLOCK_SUBINPROGRESS:
5117 : : case TBLOCK_END:
5118 : : case TBLOCK_SUBRELEASE:
5119 : : case TBLOCK_SUBCOMMIT:
5120 : : case TBLOCK_PREPARE:
5121 : 96725 : return 'T'; /* in transaction */
5122 : 1327 : case TBLOCK_ABORT:
5123 : : case TBLOCK_SUBABORT:
5124 : : case TBLOCK_ABORT_END:
5125 : : case TBLOCK_SUBABORT_END:
5126 : : case TBLOCK_ABORT_PENDING:
5127 : : case TBLOCK_SUBABORT_PENDING:
5128 : : case TBLOCK_SUBRESTART:
5129 : : case TBLOCK_SUBABORT_RESTART:
5130 : 1327 : return 'E'; /* in failed transaction */
5131 : : }
5132 : :
5133 : : /* should never get here */
5134 [ # # ]: 0 : elog(FATAL, "invalid transaction block state: %s",
5135 : : BlockStateAsString(s->blockState));
5136 : : return 0; /* keep compiler quiet */
5137 : : }
5138 : :
5139 : : /*
5140 : : * IsSubTransaction
5141 : : */
5142 : : bool
5143 : 738646 : IsSubTransaction(void)
5144 : : {
5145 : 738646 : TransactionState s = CurrentTransactionState;
5146 : :
5147 [ + + ]: 738646 : if (s->nestingLevel >= 2)
5148 : 257 : return true;
5149 : :
5150 : 738389 : return false;
5151 : : }
5152 : :
5153 : : /*
5154 : : * StartSubTransaction
5155 : : *
5156 : : * If you're wondering why this is separate from PushTransaction: it's because
5157 : : * we can't conveniently do this stuff right inside DefineSavepoint. The
5158 : : * SAVEPOINT utility command will be executed inside a Portal, and if we
5159 : : * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
5160 : : * the Portal will undo those settings. So we make DefineSavepoint just
5161 : : * push a dummy transaction block, and when control returns to the main
5162 : : * idle loop, CommitTransactionCommand will be called, and we'll come here
5163 : : * to finish starting the subtransaction.
5164 : : */
5165 : : static void
5166 : 23110 : StartSubTransaction(void)
5167 : : {
5168 : 23110 : TransactionState s = CurrentTransactionState;
5169 : :
5170 [ - + ]: 23110 : if (s->state != TRANS_DEFAULT)
5171 [ # # ]: 0 : elog(WARNING, "StartSubTransaction while in %s state",
5172 : : TransStateAsString(s->state));
5173 : :
5174 : 23110 : s->state = TRANS_START;
5175 : :
5176 : : /*
5177 : : * Initialize subsystems for new subtransaction
5178 : : *
5179 : : * must initialize resource-management stuff first
5180 : : */
5181 : 23110 : AtSubStart_Memory();
5182 : 23110 : AtSubStart_ResourceOwner();
5183 : 23110 : AfterTriggerBeginSubXact();
5184 : :
5185 : 23110 : s->state = TRANS_INPROGRESS;
5186 : :
5187 : : /*
5188 : : * Call start-of-subxact callbacks
5189 : : */
5190 : 23110 : CallSubXactCallbacks(SUBXACT_EVENT_START_SUB, s->subTransactionId,
5191 : 23110 : s->parent->subTransactionId);
5192 : :
5193 : 23110 : ShowTransactionState("StartSubTransaction");
5194 : 23110 : }
5195 : :
5196 : : /*
5197 : : * CommitSubTransaction
5198 : : *
5199 : : * The caller has to make sure to always reassign CurrentTransactionState
5200 : : * if it has a local pointer to it after calling this function.
5201 : : */
5202 : : static void
5203 : 17407 : CommitSubTransaction(void)
5204 : : {
5205 : 17407 : TransactionState s = CurrentTransactionState;
5206 : :
5207 : 17407 : ShowTransactionState("CommitSubTransaction");
5208 : :
5209 [ - + ]: 17407 : if (s->state != TRANS_INPROGRESS)
5210 [ # # ]: 0 : elog(WARNING, "CommitSubTransaction while in %s state",
5211 : : TransStateAsString(s->state));
5212 : :
5213 : : /* Pre-commit processing goes here */
5214 : :
5215 : 17407 : CallSubXactCallbacks(SUBXACT_EVENT_PRE_COMMIT_SUB, s->subTransactionId,
5216 : 17407 : s->parent->subTransactionId);
5217 : :
5218 : : /*
5219 : : * If this subxact has started any unfinished parallel operation, clean up
5220 : : * its workers and exit parallel mode. Warn about leaked resources.
5221 : : */
5222 : 17407 : AtEOSubXact_Parallel(true, s->subTransactionId);
5223 [ - + ]: 17407 : if (s->parallelModeLevel != 0)
5224 : : {
5225 [ # # ]: 0 : elog(WARNING, "parallelModeLevel is %d not 0 at end of subtransaction",
5226 : : s->parallelModeLevel);
5227 : 0 : s->parallelModeLevel = 0;
5228 : : }
5229 : :
5230 : : /* Do the actual "commit", such as it is */
5231 : 17407 : s->state = TRANS_COMMIT;
5232 : :
5233 : : /* Must CCI to ensure commands of subtransaction are seen as done */
5234 : 17407 : CommandCounterIncrement();
5235 : :
5236 : : /*
5237 : : * Prior to 8.4 we marked subcommit in clog at this point. We now only
5238 : : * perform that step, if required, as part of the atomic update of the
5239 : : * whole transaction tree at top level commit or abort.
5240 : : */
5241 : :
5242 : : /* Post-commit cleanup */
5243 [ + + ]: 17407 : if (FullTransactionIdIsValid(s->fullTransactionId))
5244 : 15466 : AtSubCommit_childXids();
5245 : 17407 : AfterTriggerEndSubXact(true);
5246 : 17407 : AtSubCommit_Portals(s->subTransactionId,
5247 : 17407 : s->parent->subTransactionId,
5248 : 17407 : s->parent->nestingLevel,
5249 : 17407 : s->parent->curTransactionOwner);
5250 : 17407 : AtEOSubXact_LargeObject(true, s->subTransactionId,
5251 : 17407 : s->parent->subTransactionId);
5252 : 17407 : AtSubCommit_Notify();
5253 : :
5254 : 17407 : CallSubXactCallbacks(SUBXACT_EVENT_COMMIT_SUB, s->subTransactionId,
5255 : 17407 : s->parent->subTransactionId);
5256 : :
5257 : 17407 : ResourceOwnerRelease(s->curTransactionOwner,
5258 : : RESOURCE_RELEASE_BEFORE_LOCKS,
5259 : : true, false);
5260 : 17407 : AtEOSubXact_RelationCache(true, s->subTransactionId,
5261 : 17407 : s->parent->subTransactionId);
5262 : 17407 : AtEOSubXact_TypeCache();
5263 : 17407 : AtEOSubXact_Inval(true);
5264 : 17407 : AtSubCommit_smgr();
5265 : :
5266 : : /*
5267 : : * The only lock we actually release here is the subtransaction XID lock.
5268 : : */
5269 : 17407 : CurrentResourceOwner = s->curTransactionOwner;
5270 [ + + ]: 17407 : if (FullTransactionIdIsValid(s->fullTransactionId))
5271 : 15466 : XactLockTableDelete(XidFromFullTransactionId(s->fullTransactionId));
5272 : :
5273 : : /*
5274 : : * Other locks should get transferred to their parent resource owner.
5275 : : */
5276 : 17407 : ResourceOwnerRelease(s->curTransactionOwner,
5277 : : RESOURCE_RELEASE_LOCKS,
5278 : : true, false);
5279 : 17407 : ResourceOwnerRelease(s->curTransactionOwner,
5280 : : RESOURCE_RELEASE_AFTER_LOCKS,
5281 : : true, false);
5282 : :
5283 : 17407 : AtEOXact_GUC(true, s->gucNestLevel);
5284 : 17407 : AtEOSubXact_SPI(true, s->subTransactionId);
5285 : 17407 : AtEOSubXact_on_commit_actions(true, s->subTransactionId,
5286 : 17407 : s->parent->subTransactionId);
5287 : 17407 : AtEOSubXact_Namespace(true, s->subTransactionId,
5288 : 17407 : s->parent->subTransactionId);
5289 : 17407 : AtEOSubXact_Files(true, s->subTransactionId,
5290 : 17407 : s->parent->subTransactionId);
5291 : 17407 : AtEOSubXact_HashTables(true, s->nestingLevel);
5292 : 17407 : AtEOSubXact_PgStat(true, s->nestingLevel);
5293 : 17407 : AtSubCommit_Snapshot(s->nestingLevel);
5294 : :
5295 : : /*
5296 : : * We need to restore the upper transaction's read-only state, in case the
5297 : : * upper is read-write while the child is read-only; GUC will incorrectly
5298 : : * think it should leave the child state in place.
5299 : : */
5300 : 17407 : XactReadOnly = s->prevXactReadOnly;
5301 : :
5302 : 17407 : CurrentResourceOwner = s->parent->curTransactionOwner;
5303 : 17407 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
5304 : 17407 : ResourceOwnerDelete(s->curTransactionOwner);
5305 : 17407 : s->curTransactionOwner = NULL;
5306 : :
5307 : 17407 : AtSubCommit_Memory();
5308 : :
5309 : 17407 : s->state = TRANS_DEFAULT;
5310 : :
5311 : 17407 : PopTransaction();
5312 : 17407 : }
5313 : :
5314 : : /*
5315 : : * AbortSubTransaction
5316 : : */
5317 : : static void
5318 : 5703 : AbortSubTransaction(void)
5319 : : {
5320 : 5703 : TransactionState s = CurrentTransactionState;
5321 : :
5322 : : /* Prevent cancel/die interrupt while cleaning up */
5323 : 5703 : HOLD_INTERRUPTS();
5324 : :
5325 : : /* Make sure we have a valid memory context and resource owner */
5326 : 5703 : AtSubAbort_Memory();
5327 : 5703 : AtSubAbort_ResourceOwner();
5328 : :
5329 : : /*
5330 : : * Release any LW locks we might be holding as quickly as possible.
5331 : : * (Regular locks, however, must be held till we finish aborting.)
5332 : : * Releasing LW locks is critical since we might try to grab them again
5333 : : * while cleaning up!
5334 : : *
5335 : : * FIXME This may be incorrect --- Are there some locks we should keep?
5336 : : * Buffer locks, for example? I don't think so but I'm not sure.
5337 : : */
5338 : 5703 : LWLockReleaseAll();
5339 : :
5340 : : /*
5341 : : * Cleanup waiting for LSN if any.
5342 : : */
5343 : 5703 : WaitLSNCleanup();
5344 : :
5345 : 5703 : pgstat_report_wait_end();
5346 : 5703 : pgstat_progress_end_command();
5347 : :
5348 : 5703 : pgaio_error_cleanup();
5349 : :
5350 : 5703 : UnlockBuffers();
5351 : :
5352 : : /* Reset WAL record construction state */
5353 : 5703 : XLogResetInsertion();
5354 : :
5355 : : /* Cancel condition variable sleep */
5356 : 5703 : ConditionVariableCancelSleep();
5357 : :
5358 : : /*
5359 : : * Also clean up any open wait for lock, since the lock manager will choke
5360 : : * if we try to wait for another lock before doing this.
5361 : : */
5362 : 5703 : LockErrorCleanup();
5363 : :
5364 : : /*
5365 : : * If any timeout events are still active, make sure the timeout interrupt
5366 : : * is scheduled. This covers possible loss of a timeout interrupt due to
5367 : : * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
5368 : : * We delay this till after LockErrorCleanup so that we don't uselessly
5369 : : * reschedule lock or deadlock check timeouts.
5370 : : */
5371 : 5703 : reschedule_timeouts();
5372 : :
5373 : : /*
5374 : : * Re-enable signals, in case we got here by longjmp'ing out of a signal
5375 : : * handler. We do this fairly early in the sequence so that the timeout
5376 : : * infrastructure will be functional if needed while aborting.
5377 : : */
5378 : 5703 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
5379 : :
5380 : : /*
5381 : : * check the current transaction state
5382 : : */
5383 : 5703 : ShowTransactionState("AbortSubTransaction");
5384 : :
5385 [ - + ]: 5703 : if (s->state != TRANS_INPROGRESS)
5386 [ # # ]: 0 : elog(WARNING, "AbortSubTransaction while in %s state",
5387 : : TransStateAsString(s->state));
5388 : :
5389 : 5703 : s->state = TRANS_ABORT;
5390 : :
5391 : : /*
5392 : : * Reset user ID which might have been changed transiently. (See notes in
5393 : : * AbortTransaction.)
5394 : : */
5395 : 5703 : SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
5396 : :
5397 : : /* Forget about any active REINDEX. */
5398 : 5703 : ResetReindexState(s->nestingLevel);
5399 : :
5400 : : /* Reset logical streaming state. */
5401 : 5703 : ResetLogicalStreamingState();
5402 : :
5403 : : /*
5404 : : * No need for SnapBuildResetExportedSnapshotState() here, snapshot
5405 : : * exports are not supported in subtransactions.
5406 : : */
5407 : :
5408 : : /*
5409 : : * If this subxact has started any unfinished parallel operation, clean up
5410 : : * its workers and exit parallel mode. Don't warn about leaked resources.
5411 : : */
5412 : 5703 : AtEOSubXact_Parallel(false, s->subTransactionId);
5413 : 5703 : s->parallelModeLevel = 0;
5414 : :
5415 : : /*
5416 : : * We can skip all this stuff if the subxact failed before creating a
5417 : : * ResourceOwner...
5418 : : */
5419 [ + - ]: 5703 : if (s->curTransactionOwner)
5420 : : {
5421 : 5703 : AfterTriggerEndSubXact(false);
5422 : 5703 : AtSubAbort_Portals(s->subTransactionId,
5423 : 5703 : s->parent->subTransactionId,
5424 : : s->curTransactionOwner,
5425 : 5703 : s->parent->curTransactionOwner);
5426 : 5703 : AtEOSubXact_LargeObject(false, s->subTransactionId,
5427 : 5703 : s->parent->subTransactionId);
5428 : 5703 : AtSubAbort_Notify();
5429 : :
5430 : : /* Advertise the fact that we aborted in pg_xact. */
5431 : 5703 : (void) RecordTransactionAbort(true);
5432 : :
5433 : : /* Post-abort cleanup */
5434 [ + + ]: 5703 : if (FullTransactionIdIsValid(s->fullTransactionId))
5435 : 1036 : AtSubAbort_childXids();
5436 : :
5437 : 5703 : CallSubXactCallbacks(SUBXACT_EVENT_ABORT_SUB, s->subTransactionId,
5438 : 5703 : s->parent->subTransactionId);
5439 : :
5440 : 5703 : ResourceOwnerRelease(s->curTransactionOwner,
5441 : : RESOURCE_RELEASE_BEFORE_LOCKS,
5442 : : false, false);
5443 : :
5444 : 5703 : AtEOXact_Aio(false);
5445 : 5703 : AtEOSubXact_RelationCache(false, s->subTransactionId,
5446 : 5703 : s->parent->subTransactionId);
5447 : 5703 : AtEOSubXact_TypeCache();
5448 : 5703 : AtEOSubXact_Inval(false);
5449 : 5703 : ResourceOwnerRelease(s->curTransactionOwner,
5450 : : RESOURCE_RELEASE_LOCKS,
5451 : : false, false);
5452 : 5703 : ResourceOwnerRelease(s->curTransactionOwner,
5453 : : RESOURCE_RELEASE_AFTER_LOCKS,
5454 : : false, false);
5455 : 5703 : AtSubAbort_smgr();
5456 : :
5457 : 5703 : AtEOXact_GUC(false, s->gucNestLevel);
5458 : 5703 : AtEOSubXact_SPI(false, s->subTransactionId);
5459 : 5703 : AtEOSubXact_on_commit_actions(false, s->subTransactionId,
5460 : 5703 : s->parent->subTransactionId);
5461 : 5703 : AtEOSubXact_Namespace(false, s->subTransactionId,
5462 : 5703 : s->parent->subTransactionId);
5463 : 5703 : AtEOSubXact_Files(false, s->subTransactionId,
5464 : 5703 : s->parent->subTransactionId);
5465 : 5703 : AtEOSubXact_HashTables(false, s->nestingLevel);
5466 : 5703 : AtEOSubXact_PgStat(false, s->nestingLevel);
5467 : 5703 : AtSubAbort_Snapshot(s->nestingLevel);
5468 : : }
5469 : :
5470 : : /*
5471 : : * Restore the upper transaction's read-only state, too. This should be
5472 : : * redundant with GUC's cleanup but we may as well do it for consistency
5473 : : * with the commit case.
5474 : : */
5475 : 5703 : XactReadOnly = s->prevXactReadOnly;
5476 : :
5477 : 5703 : RESUME_INTERRUPTS();
5478 : 5703 : }
5479 : :
5480 : : /*
5481 : : * CleanupSubTransaction
5482 : : *
5483 : : * The caller has to make sure to always reassign CurrentTransactionState
5484 : : * if it has a local pointer to it after calling this function.
5485 : : */
5486 : : static void
5487 : 5703 : CleanupSubTransaction(void)
5488 : : {
5489 : 5703 : TransactionState s = CurrentTransactionState;
5490 : :
5491 : 5703 : ShowTransactionState("CleanupSubTransaction");
5492 : :
5493 [ - + ]: 5703 : if (s->state != TRANS_ABORT)
5494 [ # # ]: 0 : elog(WARNING, "CleanupSubTransaction while in %s state",
5495 : : TransStateAsString(s->state));
5496 : :
5497 : 5703 : AtSubCleanup_Portals(s->subTransactionId);
5498 : :
5499 : 5703 : CurrentResourceOwner = s->parent->curTransactionOwner;
5500 : 5703 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
5501 [ + - ]: 5703 : if (s->curTransactionOwner)
5502 : 5703 : ResourceOwnerDelete(s->curTransactionOwner);
5503 : 5703 : s->curTransactionOwner = NULL;
5504 : :
5505 : 5703 : AtSubCleanup_Memory();
5506 : :
5507 : 5703 : s->state = TRANS_DEFAULT;
5508 : :
5509 : 5703 : PopTransaction();
5510 : 5703 : }
5511 : :
5512 : : /*
5513 : : * PushTransaction
5514 : : * Create transaction state stack entry for a subtransaction
5515 : : *
5516 : : * The caller has to make sure to always reassign CurrentTransactionState
5517 : : * if it has a local pointer to it after calling this function.
5518 : : */
5519 : : static void
5520 : 23110 : PushTransaction(void)
5521 : : {
5522 : 23110 : TransactionState p = CurrentTransactionState;
5523 : : TransactionState s;
5524 : :
5525 : : /*
5526 : : * We keep subtransaction state nodes in TopTransactionContext.
5527 : : */
5528 : : s = (TransactionState)
5529 : 23110 : MemoryContextAllocZero(TopTransactionContext,
5530 : : sizeof(TransactionStateData));
5531 : :
5532 : : /*
5533 : : * Assign a subtransaction ID, watching out for counter wraparound.
5534 : : */
5535 : 23110 : currentSubTransactionId += 1;
5536 [ - + ]: 23110 : if (currentSubTransactionId == InvalidSubTransactionId)
5537 : : {
5538 : 0 : currentSubTransactionId -= 1;
5539 : 0 : pfree(s);
5540 [ # # ]: 0 : ereport(ERROR,
5541 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5542 : : errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
5543 : : }
5544 : :
5545 : : /*
5546 : : * We can now stack a minimally valid subtransaction without fear of
5547 : : * failure.
5548 : : */
5549 : 23110 : s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
5550 : 23110 : s->subTransactionId = currentSubTransactionId;
5551 : 23110 : s->parent = p;
5552 : 23110 : s->nestingLevel = p->nestingLevel + 1;
5553 : 23110 : s->gucNestLevel = NewGUCNestLevel();
5554 : 23110 : s->savepointLevel = p->savepointLevel;
5555 : 23110 : s->state = TRANS_DEFAULT;
5556 : 23110 : s->blockState = TBLOCK_SUBBEGIN;
5557 : 23110 : GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
5558 : 23110 : s->prevXactReadOnly = XactReadOnly;
5559 : 23110 : s->startedInRecovery = p->startedInRecovery;
5560 : 23110 : s->parallelModeLevel = 0;
5561 [ + + - + ]: 23110 : s->parallelChildXact = (p->parallelModeLevel != 0 || p->parallelChildXact);
5562 : 23110 : s->topXidLogged = false;
5563 : :
5564 : 23110 : CurrentTransactionState = s;
5565 : :
5566 : : /*
5567 : : * AbortSubTransaction and CleanupSubTransaction have to be able to cope
5568 : : * with the subtransaction from here on out; in particular they should not
5569 : : * assume that it necessarily has a transaction context, resource owner,
5570 : : * or XID.
5571 : : */
5572 : 23110 : }
5573 : :
5574 : : /*
5575 : : * PopTransaction
5576 : : * Pop back to parent transaction state
5577 : : *
5578 : : * The caller has to make sure to always reassign CurrentTransactionState
5579 : : * if it has a local pointer to it after calling this function.
5580 : : */
5581 : : static void
5582 : 23110 : PopTransaction(void)
5583 : : {
5584 : 23110 : TransactionState s = CurrentTransactionState;
5585 : :
5586 [ - + ]: 23110 : if (s->state != TRANS_DEFAULT)
5587 [ # # ]: 0 : elog(WARNING, "PopTransaction while in %s state",
5588 : : TransStateAsString(s->state));
5589 : :
5590 [ - + ]: 23110 : if (s->parent == NULL)
5591 [ # # ]: 0 : elog(FATAL, "PopTransaction with no parent");
5592 : :
5593 : 23110 : CurrentTransactionState = s->parent;
5594 : :
5595 : : /* Let's just make sure CurTransactionContext is good */
5596 : 23110 : CurTransactionContext = s->parent->curTransactionContext;
5597 : 23110 : MemoryContextSwitchTo(CurTransactionContext);
5598 : :
5599 : : /* Ditto for ResourceOwner links */
5600 : 23110 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
5601 : 23110 : CurrentResourceOwner = s->parent->curTransactionOwner;
5602 : :
5603 : : /* Free the old child structure */
5604 [ + + ]: 23110 : if (s->name)
5605 : 2249 : pfree(s->name);
5606 : 23110 : pfree(s);
5607 : 23110 : }
5608 : :
5609 : : /*
5610 : : * EstimateTransactionStateSpace
5611 : : * Estimate the amount of space that will be needed by
5612 : : * SerializeTransactionState. It would be OK to overestimate slightly,
5613 : : * but it's simple for us to work out the precise value, so we do.
5614 : : */
5615 : : Size
5616 : 680 : EstimateTransactionStateSpace(void)
5617 : : {
5618 : : TransactionState s;
5619 : 680 : Size nxids = 0;
5620 : 680 : Size size = SerializedTransactionStateHeaderSize;
5621 : :
5622 [ + + ]: 3052 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5623 : : {
5624 [ + + ]: 2372 : if (FullTransactionIdIsValid(s->fullTransactionId))
5625 : 1367 : nxids = add_size(nxids, 1);
5626 : 2372 : nxids = add_size(nxids, s->nChildXids);
5627 : : }
5628 : :
5629 : 680 : return add_size(size, mul_size(sizeof(TransactionId), nxids));
5630 : : }
5631 : :
5632 : : /*
5633 : : * SerializeTransactionState
5634 : : * Write out relevant details of our transaction state that will be
5635 : : * needed by a parallel worker.
5636 : : *
5637 : : * We need to save and restore XactDeferrable, XactIsoLevel, and the XIDs
5638 : : * associated with this transaction. These are serialized into a
5639 : : * caller-supplied buffer big enough to hold the number of bytes reported by
5640 : : * EstimateTransactionStateSpace(). We emit the XIDs in sorted order for the
5641 : : * convenience of the receiving process.
5642 : : */
5643 : : void
5644 : 680 : SerializeTransactionState(Size maxsize, char *start_address)
5645 : : {
5646 : : TransactionState s;
5647 : 680 : Size nxids = 0;
5648 : 680 : Size i = 0;
5649 : : TransactionId *workspace;
5650 : : SerializedTransactionState *result;
5651 : :
5652 : 680 : result = (SerializedTransactionState *) start_address;
5653 : :
5654 : 680 : result->xactIsoLevel = XactIsoLevel;
5655 : 680 : result->xactDeferrable = XactDeferrable;
5656 : 680 : result->topFullTransactionId = XactTopFullTransactionId;
5657 : 680 : result->currentFullTransactionId =
5658 : 680 : CurrentTransactionState->fullTransactionId;
5659 : 680 : result->currentCommandId = currentCommandId;
5660 : :
5661 : : /*
5662 : : * If we're running in a parallel worker and launching a parallel worker
5663 : : * of our own, we can just pass along the information that was passed to
5664 : : * us.
5665 : : */
5666 [ - + ]: 680 : if (nParallelCurrentXids > 0)
5667 : : {
5668 : 0 : result->nParallelCurrentXids = nParallelCurrentXids;
5669 : 0 : memcpy(&result->parallelCurrentXids[0], ParallelCurrentXids,
5670 : : nParallelCurrentXids * sizeof(TransactionId));
5671 : 0 : return;
5672 : : }
5673 : :
5674 : : /*
5675 : : * OK, we need to generate a sorted list of XIDs that our workers should
5676 : : * view as current. First, figure out how many there are.
5677 : : */
5678 [ + + ]: 3052 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5679 : : {
5680 [ + + ]: 2372 : if (FullTransactionIdIsValid(s->fullTransactionId))
5681 : 1367 : nxids = add_size(nxids, 1);
5682 : 2372 : nxids = add_size(nxids, s->nChildXids);
5683 : : }
5684 : : Assert(SerializedTransactionStateHeaderSize + nxids * sizeof(TransactionId)
5685 : : <= maxsize);
5686 : :
5687 : : /* Copy them to our scratch space. */
5688 : 680 : workspace = palloc_array(TransactionId, nxids);
5689 [ + + ]: 3052 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5690 : : {
5691 [ + + ]: 2372 : if (FullTransactionIdIsValid(s->fullTransactionId))
5692 : 1367 : workspace[i++] = XidFromFullTransactionId(s->fullTransactionId);
5693 [ - + ]: 2372 : if (s->nChildXids > 0)
5694 : 0 : memcpy(&workspace[i], s->childXids,
5695 : 0 : s->nChildXids * sizeof(TransactionId));
5696 : 2372 : i += s->nChildXids;
5697 : : }
5698 : : Assert(i == nxids);
5699 : :
5700 : : /* Sort them. */
5701 : 680 : qsort(workspace, nxids, sizeof(TransactionId), xidComparator);
5702 : :
5703 : : /* Copy data into output area. */
5704 : 680 : result->nParallelCurrentXids = nxids;
5705 : 680 : memcpy(&result->parallelCurrentXids[0], workspace,
5706 : : nxids * sizeof(TransactionId));
5707 : : }
5708 : :
5709 : : /*
5710 : : * StartParallelWorkerTransaction
5711 : : * Start a parallel worker transaction, restoring the relevant
5712 : : * transaction state serialized by SerializeTransactionState.
5713 : : */
5714 : : void
5715 : 2048 : StartParallelWorkerTransaction(char *tstatespace)
5716 : : {
5717 : : SerializedTransactionState *tstate;
5718 : :
5719 : : Assert(CurrentTransactionState->blockState == TBLOCK_DEFAULT);
5720 : 2048 : StartTransaction();
5721 : :
5722 : 2048 : tstate = (SerializedTransactionState *) tstatespace;
5723 : 2048 : XactIsoLevel = tstate->xactIsoLevel;
5724 : 2048 : XactDeferrable = tstate->xactDeferrable;
5725 : 2048 : XactTopFullTransactionId = tstate->topFullTransactionId;
5726 : 2048 : CurrentTransactionState->fullTransactionId =
5727 : : tstate->currentFullTransactionId;
5728 : 2048 : currentCommandId = tstate->currentCommandId;
5729 : 2048 : nParallelCurrentXids = tstate->nParallelCurrentXids;
5730 : 2048 : ParallelCurrentXids = &tstate->parallelCurrentXids[0];
5731 : :
5732 : 2048 : CurrentTransactionState->blockState = TBLOCK_PARALLEL_INPROGRESS;
5733 : 2048 : }
5734 : :
5735 : : /*
5736 : : * EndParallelWorkerTransaction
5737 : : * End a parallel worker transaction.
5738 : : */
5739 : : void
5740 : 2033 : EndParallelWorkerTransaction(void)
5741 : : {
5742 : : Assert(CurrentTransactionState->blockState == TBLOCK_PARALLEL_INPROGRESS);
5743 : 2033 : CommitTransaction();
5744 : 2033 : CurrentTransactionState->blockState = TBLOCK_DEFAULT;
5745 : 2033 : }
5746 : :
5747 : : /*
5748 : : * ShowTransactionState
5749 : : * Debug support
5750 : : */
5751 : : static void
5752 : 1337647 : ShowTransactionState(const char *str)
5753 : : {
5754 : : /* skip work if message will definitely not be printed */
5755 [ - + ]: 1337647 : if (message_level_is_interesting(DEBUG5))
5756 : 0 : ShowTransactionStateRec(str, CurrentTransactionState);
5757 : 1337647 : }
5758 : :
5759 : : /*
5760 : : * ShowTransactionStateRec
5761 : : * Recursive subroutine for ShowTransactionState
5762 : : */
5763 : : static void
5764 : 0 : ShowTransactionStateRec(const char *str, TransactionState s)
5765 : : {
5766 : : StringInfoData buf;
5767 : :
5768 [ # # ]: 0 : if (s->parent)
5769 : : {
5770 : : /*
5771 : : * Since this function recurses, it could be driven to stack overflow.
5772 : : * This is just a debugging aid, so we can leave out some details
5773 : : * instead of erroring out with check_stack_depth().
5774 : : */
5775 [ # # ]: 0 : if (stack_is_too_deep())
5776 [ # # ]: 0 : ereport(DEBUG5,
5777 : : (errmsg_internal("%s(%d): parent omitted to avoid stack overflow",
5778 : : str, s->nestingLevel)));
5779 : : else
5780 : 0 : ShowTransactionStateRec(str, s->parent);
5781 : : }
5782 : :
5783 : 0 : initStringInfo(&buf);
5784 [ # # ]: 0 : if (s->nChildXids > 0)
5785 : : {
5786 : : int i;
5787 : :
5788 : 0 : appendStringInfo(&buf, ", children: %u", s->childXids[0]);
5789 [ # # ]: 0 : for (i = 1; i < s->nChildXids; i++)
5790 : 0 : appendStringInfo(&buf, " %u", s->childXids[i]);
5791 : : }
5792 [ # # # # : 0 : ereport(DEBUG5,
# # ]
5793 : : (errmsg_internal("%s(%d) name: %s; blockState: %s; state: %s, xid/subid/cid: %u/%u/%u%s%s",
5794 : : str, s->nestingLevel,
5795 : : s->name ? s->name : "unnamed",
5796 : : BlockStateAsString(s->blockState),
5797 : : TransStateAsString(s->state),
5798 : : XidFromFullTransactionId(s->fullTransactionId),
5799 : : s->subTransactionId,
5800 : : currentCommandId,
5801 : : currentCommandIdUsed ? " (used)" : "",
5802 : : buf.data)));
5803 : 0 : pfree(buf.data);
5804 : 0 : }
5805 : :
5806 : : /*
5807 : : * BlockStateAsString
5808 : : * Debug support
5809 : : */
5810 : : static const char *
5811 : 0 : BlockStateAsString(TBlockState blockState)
5812 : : {
5813 [ # # # # : 0 : switch (blockState)
# # # # #
# # # # #
# # # # #
# # ]
5814 : : {
5815 : 0 : case TBLOCK_DEFAULT:
5816 : 0 : return "DEFAULT";
5817 : 0 : case TBLOCK_STARTED:
5818 : 0 : return "STARTED";
5819 : 0 : case TBLOCK_BEGIN:
5820 : 0 : return "BEGIN";
5821 : 0 : case TBLOCK_INPROGRESS:
5822 : 0 : return "INPROGRESS";
5823 : 0 : case TBLOCK_IMPLICIT_INPROGRESS:
5824 : 0 : return "IMPLICIT_INPROGRESS";
5825 : 0 : case TBLOCK_PARALLEL_INPROGRESS:
5826 : 0 : return "PARALLEL_INPROGRESS";
5827 : 0 : case TBLOCK_END:
5828 : 0 : return "END";
5829 : 0 : case TBLOCK_ABORT:
5830 : 0 : return "ABORT";
5831 : 0 : case TBLOCK_ABORT_END:
5832 : 0 : return "ABORT_END";
5833 : 0 : case TBLOCK_ABORT_PENDING:
5834 : 0 : return "ABORT_PENDING";
5835 : 0 : case TBLOCK_PREPARE:
5836 : 0 : return "PREPARE";
5837 : 0 : case TBLOCK_SUBBEGIN:
5838 : 0 : return "SUBBEGIN";
5839 : 0 : case TBLOCK_SUBINPROGRESS:
5840 : 0 : return "SUBINPROGRESS";
5841 : 0 : case TBLOCK_SUBRELEASE:
5842 : 0 : return "SUBRELEASE";
5843 : 0 : case TBLOCK_SUBCOMMIT:
5844 : 0 : return "SUBCOMMIT";
5845 : 0 : case TBLOCK_SUBABORT:
5846 : 0 : return "SUBABORT";
5847 : 0 : case TBLOCK_SUBABORT_END:
5848 : 0 : return "SUBABORT_END";
5849 : 0 : case TBLOCK_SUBABORT_PENDING:
5850 : 0 : return "SUBABORT_PENDING";
5851 : 0 : case TBLOCK_SUBRESTART:
5852 : 0 : return "SUBRESTART";
5853 : 0 : case TBLOCK_SUBABORT_RESTART:
5854 : 0 : return "SUBABORT_RESTART";
5855 : : }
5856 : 0 : return "UNRECOGNIZED";
5857 : : }
5858 : :
5859 : : /*
5860 : : * TransStateAsString
5861 : : * Debug support
5862 : : */
5863 : : static const char *
5864 : 0 : TransStateAsString(TransState state)
5865 : : {
5866 [ # # # # : 0 : switch (state)
# # # ]
5867 : : {
5868 : 0 : case TRANS_DEFAULT:
5869 : 0 : return "DEFAULT";
5870 : 0 : case TRANS_START:
5871 : 0 : return "START";
5872 : 0 : case TRANS_INPROGRESS:
5873 : 0 : return "INPROGRESS";
5874 : 0 : case TRANS_COMMIT:
5875 : 0 : return "COMMIT";
5876 : 0 : case TRANS_ABORT:
5877 : 0 : return "ABORT";
5878 : 0 : case TRANS_PREPARE:
5879 : 0 : return "PREPARE";
5880 : : }
5881 : 0 : return "UNRECOGNIZED";
5882 : : }
5883 : :
5884 : : /*
5885 : : * xactGetCommittedChildren
5886 : : *
5887 : : * Gets the list of committed children of the current transaction. The return
5888 : : * value is the number of child transactions. *ptr is set to point to an
5889 : : * array of TransactionIds. The array is allocated in TopTransactionContext;
5890 : : * the caller should *not* pfree() it (this is a change from pre-8.4 code!).
5891 : : * If there are no subxacts, *ptr is set to NULL.
5892 : : */
5893 : : int
5894 : 632125 : xactGetCommittedChildren(TransactionId **ptr)
5895 : : {
5896 : 632125 : TransactionState s = CurrentTransactionState;
5897 : :
5898 [ + + ]: 632125 : if (s->nChildXids == 0)
5899 : 631502 : *ptr = NULL;
5900 : : else
5901 : 623 : *ptr = s->childXids;
5902 : :
5903 : 632125 : return s->nChildXids;
5904 : : }
5905 : :
5906 : : /*
5907 : : * XLOG support routines
5908 : : */
5909 : :
5910 : :
5911 : : /*
5912 : : * Log the commit record for a plain or twophase transaction commit.
5913 : : *
5914 : : * A 2pc commit will be emitted when twophase_xid is valid, a plain one
5915 : : * otherwise.
5916 : : */
5917 : : XLogRecPtr
5918 : 164033 : XactLogCommitRecord(TimestampTz commit_time,
5919 : : int nsubxacts, TransactionId *subxacts,
5920 : : int nrels, RelFileLocator *rels,
5921 : : int ndroppedstats, xl_xact_stats_item *droppedstats,
5922 : : int nmsgs, SharedInvalidationMessage *msgs,
5923 : : bool relcacheInval,
5924 : : int xactflags, TransactionId twophase_xid,
5925 : : const char *twophase_gid)
5926 : : {
5927 : : xl_xact_commit xlrec;
5928 : : xl_xact_xinfo xl_xinfo;
5929 : : xl_xact_dbinfo xl_dbinfo;
5930 : : xl_xact_subxacts xl_subxacts;
5931 : : xl_xact_relfilelocators xl_relfilelocators;
5932 : : xl_xact_stats_items xl_dropped_stats;
5933 : : xl_xact_invals xl_invals;
5934 : : xl_xact_twophase xl_twophase;
5935 : : xl_xact_origin xl_origin;
5936 : : uint8 info;
5937 : :
5938 : : Assert(CritSectionCount > 0);
5939 : :
5940 : 164033 : xl_xinfo.xinfo = 0;
5941 : :
5942 : : /* decide between a plain and 2pc commit */
5943 [ + + ]: 164033 : if (!TransactionIdIsValid(twophase_xid))
5944 : 163757 : info = XLOG_XACT_COMMIT;
5945 : : else
5946 : 276 : info = XLOG_XACT_COMMIT_PREPARED;
5947 : :
5948 : : /* First figure out and collect all the information needed */
5949 : :
5950 : 164033 : xlrec.xact_time = commit_time;
5951 : :
5952 [ + + ]: 164033 : if (relcacheInval)
5953 : 4729 : xl_xinfo.xinfo |= XACT_COMPLETION_UPDATE_RELCACHE_FILE;
5954 [ + + ]: 164033 : if (forceSyncCommit)
5955 : 628 : xl_xinfo.xinfo |= XACT_COMPLETION_FORCE_SYNC_COMMIT;
5956 [ + + ]: 164033 : if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
5957 : 66293 : xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
5958 : :
5959 : : /*
5960 : : * Check if the caller would like to ask standbys for immediate feedback
5961 : : * once this commit is applied.
5962 : : */
5963 [ + + ]: 164033 : if (synchronous_commit >= SYNCHRONOUS_COMMIT_REMOTE_APPLY)
5964 : 3 : xl_xinfo.xinfo |= XACT_COMPLETION_APPLY_FEEDBACK;
5965 : :
5966 : : /*
5967 : : * Relcache invalidations requires information about the current database
5968 : : * and so does logical decoding.
5969 : : */
5970 [ + + + + : 164033 : if (nmsgs > 0 || XLogLogicalInfoActive())
+ + ]
5971 : : {
5972 : 116861 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
5973 : 116861 : xl_dbinfo.dbId = MyDatabaseId;
5974 : 116861 : xl_dbinfo.tsId = MyDatabaseTableSpace;
5975 : : }
5976 : :
5977 [ + + ]: 164033 : if (nsubxacts > 0)
5978 : : {
5979 : 518 : xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
5980 : 518 : xl_subxacts.nsubxacts = nsubxacts;
5981 : : }
5982 : :
5983 [ + + ]: 164033 : if (nrels > 0)
5984 : : {
5985 : 13040 : xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILELOCATORS;
5986 : 13040 : xl_relfilelocators.nrels = nrels;
5987 : 13040 : info |= XLR_SPECIAL_REL_UPDATE;
5988 : : }
5989 : :
5990 [ + + ]: 164033 : if (ndroppedstats > 0)
5991 : : {
5992 : 16111 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DROPPED_STATS;
5993 : 16111 : xl_dropped_stats.nitems = ndroppedstats;
5994 : : }
5995 : :
5996 [ + + ]: 164033 : if (nmsgs > 0)
5997 : : {
5998 : 115883 : xl_xinfo.xinfo |= XACT_XINFO_HAS_INVALS;
5999 : 115883 : xl_invals.nmsgs = nmsgs;
6000 : : }
6001 : :
6002 [ + + ]: 164033 : if (TransactionIdIsValid(twophase_xid))
6003 : : {
6004 : 276 : xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
6005 : 276 : xl_twophase.xid = twophase_xid;
6006 : : Assert(twophase_gid != NULL);
6007 : :
6008 [ + + - + ]: 276 : if (XLogLogicalInfoActive())
6009 : 43 : xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
6010 : : }
6011 : :
6012 : : /* dump transaction origin information */
6013 [ + + ]: 164033 : if (replorigin_xact_state.origin != InvalidReplOriginId)
6014 : : {
6015 : 1126 : xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
6016 : :
6017 : 1126 : xl_origin.origin_lsn = replorigin_xact_state.origin_lsn;
6018 : 1126 : xl_origin.origin_timestamp = replorigin_xact_state.origin_timestamp;
6019 : : }
6020 : :
6021 [ + + ]: 164033 : if (xl_xinfo.xinfo != 0)
6022 : 120098 : info |= XLOG_XACT_HAS_INFO;
6023 : :
6024 : : /* Then include all the collected data into the commit record. */
6025 : :
6026 : 164033 : XLogBeginInsert();
6027 : :
6028 : 164033 : XLogRegisterData(&xlrec, sizeof(xl_xact_commit));
6029 : :
6030 [ + + ]: 164033 : if (xl_xinfo.xinfo != 0)
6031 : 120098 : XLogRegisterData(&xl_xinfo.xinfo, sizeof(xl_xinfo.xinfo));
6032 : :
6033 [ + + ]: 164033 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
6034 : 116861 : XLogRegisterData(&xl_dbinfo, sizeof(xl_dbinfo));
6035 : :
6036 [ + + ]: 164033 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
6037 : : {
6038 : 518 : XLogRegisterData(&xl_subxacts,
6039 : : MinSizeOfXactSubxacts);
6040 : 518 : XLogRegisterData(subxacts,
6041 : : nsubxacts * sizeof(TransactionId));
6042 : : }
6043 : :
6044 [ + + ]: 164033 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILELOCATORS)
6045 : : {
6046 : 13040 : XLogRegisterData(&xl_relfilelocators,
6047 : : MinSizeOfXactRelfileLocators);
6048 : 13040 : XLogRegisterData(rels,
6049 : : nrels * sizeof(RelFileLocator));
6050 : : }
6051 : :
6052 [ + + ]: 164033 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DROPPED_STATS)
6053 : : {
6054 : 16111 : XLogRegisterData(&xl_dropped_stats,
6055 : : MinSizeOfXactStatsItems);
6056 : 16111 : XLogRegisterData(droppedstats,
6057 : : ndroppedstats * sizeof(xl_xact_stats_item));
6058 : : }
6059 : :
6060 [ + + ]: 164033 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_INVALS)
6061 : : {
6062 : 115883 : XLogRegisterData(&xl_invals, MinSizeOfXactInvals);
6063 : 115883 : XLogRegisterData(msgs,
6064 : : nmsgs * sizeof(SharedInvalidationMessage));
6065 : : }
6066 : :
6067 [ + + ]: 164033 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
6068 : : {
6069 : 276 : XLogRegisterData(&xl_twophase, sizeof(xl_xact_twophase));
6070 [ + + ]: 276 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_GID)
6071 : 43 : XLogRegisterData(twophase_gid, strlen(twophase_gid) + 1);
6072 : : }
6073 : :
6074 [ + + ]: 164033 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_ORIGIN)
6075 : 1126 : XLogRegisterData(&xl_origin, sizeof(xl_xact_origin));
6076 : :
6077 : : /* we allow filtering by xacts */
6078 : 164033 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6079 : :
6080 : 164033 : return XLogInsert(RM_XACT_ID, info);
6081 : : }
6082 : :
6083 : : /*
6084 : : * Log the commit record for a plain or twophase transaction abort.
6085 : : *
6086 : : * A 2pc abort will be emitted when twophase_xid is valid, a plain one
6087 : : * otherwise.
6088 : : */
6089 : : XLogRecPtr
6090 : 10121 : XactLogAbortRecord(TimestampTz abort_time,
6091 : : int nsubxacts, TransactionId *subxacts,
6092 : : int nrels, RelFileLocator *rels,
6093 : : int ndroppedstats, xl_xact_stats_item *droppedstats,
6094 : : int xactflags, TransactionId twophase_xid,
6095 : : const char *twophase_gid)
6096 : : {
6097 : : xl_xact_abort xlrec;
6098 : : xl_xact_xinfo xl_xinfo;
6099 : : xl_xact_subxacts xl_subxacts;
6100 : : xl_xact_relfilelocators xl_relfilelocators;
6101 : : xl_xact_stats_items xl_dropped_stats;
6102 : : xl_xact_twophase xl_twophase;
6103 : : xl_xact_dbinfo xl_dbinfo;
6104 : : xl_xact_origin xl_origin;
6105 : :
6106 : : uint8 info;
6107 : :
6108 : : Assert(CritSectionCount > 0);
6109 : :
6110 : 10121 : xl_xinfo.xinfo = 0;
6111 : :
6112 : : /* decide between a plain and 2pc abort */
6113 [ + + ]: 10121 : if (!TransactionIdIsValid(twophase_xid))
6114 : 10072 : info = XLOG_XACT_ABORT;
6115 : : else
6116 : 49 : info = XLOG_XACT_ABORT_PREPARED;
6117 : :
6118 : :
6119 : : /* First figure out and collect all the information needed */
6120 : :
6121 : 10121 : xlrec.xact_time = abort_time;
6122 : :
6123 [ + + ]: 10121 : if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
6124 : 5633 : xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
6125 : :
6126 [ + + ]: 10121 : if (nsubxacts > 0)
6127 : : {
6128 : 108 : xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
6129 : 108 : xl_subxacts.nsubxacts = nsubxacts;
6130 : : }
6131 : :
6132 [ + + ]: 10121 : if (nrels > 0)
6133 : : {
6134 : 1576 : xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILELOCATORS;
6135 : 1576 : xl_relfilelocators.nrels = nrels;
6136 : 1576 : info |= XLR_SPECIAL_REL_UPDATE;
6137 : : }
6138 : :
6139 [ + + ]: 10121 : if (ndroppedstats > 0)
6140 : : {
6141 : 2154 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DROPPED_STATS;
6142 : 2154 : xl_dropped_stats.nitems = ndroppedstats;
6143 : : }
6144 : :
6145 [ + + ]: 10121 : if (TransactionIdIsValid(twophase_xid))
6146 : : {
6147 : 49 : xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
6148 : 49 : xl_twophase.xid = twophase_xid;
6149 : : Assert(twophase_gid != NULL);
6150 : :
6151 [ + + - + ]: 49 : if (XLogLogicalInfoActive())
6152 : 15 : xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
6153 : : }
6154 : :
6155 [ + + + + : 10121 : if (TransactionIdIsValid(twophase_xid) && XLogLogicalInfoActive())
- + ]
6156 : : {
6157 : 15 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
6158 : 15 : xl_dbinfo.dbId = MyDatabaseId;
6159 : 15 : xl_dbinfo.tsId = MyDatabaseTableSpace;
6160 : : }
6161 : :
6162 : : /*
6163 : : * Dump transaction origin information. We need this during recovery to
6164 : : * update the replication origin progress.
6165 : : */
6166 [ + + ]: 10121 : if (replorigin_xact_state.origin != InvalidReplOriginId)
6167 : : {
6168 : 29 : xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
6169 : :
6170 : 29 : xl_origin.origin_lsn = replorigin_xact_state.origin_lsn;
6171 : 29 : xl_origin.origin_timestamp = replorigin_xact_state.origin_timestamp;
6172 : : }
6173 : :
6174 [ + + ]: 10121 : if (xl_xinfo.xinfo != 0)
6175 : 5893 : info |= XLOG_XACT_HAS_INFO;
6176 : :
6177 : : /* Then include all the collected data into the abort record. */
6178 : :
6179 : 10121 : XLogBeginInsert();
6180 : :
6181 : 10121 : XLogRegisterData(&xlrec, MinSizeOfXactAbort);
6182 : :
6183 [ + + ]: 10121 : if (xl_xinfo.xinfo != 0)
6184 : 5893 : XLogRegisterData(&xl_xinfo, sizeof(xl_xinfo));
6185 : :
6186 [ + + ]: 10121 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
6187 : 15 : XLogRegisterData(&xl_dbinfo, sizeof(xl_dbinfo));
6188 : :
6189 [ + + ]: 10121 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
6190 : : {
6191 : 108 : XLogRegisterData(&xl_subxacts,
6192 : : MinSizeOfXactSubxacts);
6193 : 108 : XLogRegisterData(subxacts,
6194 : : nsubxacts * sizeof(TransactionId));
6195 : : }
6196 : :
6197 [ + + ]: 10121 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILELOCATORS)
6198 : : {
6199 : 1576 : XLogRegisterData(&xl_relfilelocators,
6200 : : MinSizeOfXactRelfileLocators);
6201 : 1576 : XLogRegisterData(rels,
6202 : : nrels * sizeof(RelFileLocator));
6203 : : }
6204 : :
6205 [ + + ]: 10121 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DROPPED_STATS)
6206 : : {
6207 : 2154 : XLogRegisterData(&xl_dropped_stats,
6208 : : MinSizeOfXactStatsItems);
6209 : 2154 : XLogRegisterData(droppedstats,
6210 : : ndroppedstats * sizeof(xl_xact_stats_item));
6211 : : }
6212 : :
6213 [ + + ]: 10121 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
6214 : : {
6215 : 49 : XLogRegisterData(&xl_twophase, sizeof(xl_xact_twophase));
6216 [ + + ]: 49 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_GID)
6217 : 15 : XLogRegisterData(twophase_gid, strlen(twophase_gid) + 1);
6218 : : }
6219 : :
6220 [ + + ]: 10121 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_ORIGIN)
6221 : 29 : XLogRegisterData(&xl_origin, sizeof(xl_xact_origin));
6222 : :
6223 : : /* Include the replication origin */
6224 : 10121 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6225 : :
6226 : 10121 : return XLogInsert(RM_XACT_ID, info);
6227 : : }
6228 : :
6229 : : /*
6230 : : * Before 9.0 this was a fairly short function, but now it performs many
6231 : : * actions for which the order of execution is critical.
6232 : : */
6233 : : static void
6234 : 24521 : xact_redo_commit(xl_xact_parsed_commit *parsed,
6235 : : TransactionId xid,
6236 : : XLogRecPtr lsn,
6237 : : ReplOriginId origin_id)
6238 : : {
6239 : : TransactionId max_xid;
6240 : : TimestampTz commit_time;
6241 : :
6242 : : Assert(TransactionIdIsValid(xid));
6243 : :
6244 : 24521 : max_xid = TransactionIdLatest(xid, parsed->nsubxacts, parsed->subxacts);
6245 : :
6246 : : /* Make sure nextXid is beyond any XID mentioned in the record. */
6247 : 24521 : AdvanceNextFullTransactionIdPastXid(max_xid);
6248 : :
6249 : : Assert(((parsed->xinfo & XACT_XINFO_HAS_ORIGIN) == 0) ==
6250 : : (origin_id == InvalidReplOriginId));
6251 : :
6252 [ + + ]: 24521 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6253 : 20 : commit_time = parsed->origin_timestamp;
6254 : : else
6255 : 24501 : commit_time = parsed->xact_time;
6256 : :
6257 : : /* Set the transaction commit timestamp and metadata */
6258 : 24521 : TransactionTreeSetCommitTsData(xid, parsed->nsubxacts, parsed->subxacts,
6259 : : commit_time, origin_id);
6260 : :
6261 [ + + ]: 24521 : if (standbyState == STANDBY_DISABLED)
6262 : : {
6263 : : /*
6264 : : * Mark the transaction committed in pg_xact. We use the async commit
6265 : : * protocol during recovery to ensure that minRecoveryPoint is
6266 : : * advanced before the CLOG is written. This ensures that if we crash,
6267 : : * we don't see the committed status set for transactions that haven't
6268 : : * yet recovered.
6269 : : */
6270 : 2228 : TransactionIdAsyncCommitTree(xid, parsed->nsubxacts, parsed->subxacts, lsn);
6271 : : }
6272 : : else
6273 : : {
6274 : : /*
6275 : : * If a transaction completion record arrives that has as-yet
6276 : : * unobserved subtransactions then this will not have been fully
6277 : : * handled by the call to RecordKnownAssignedTransactionIds() in the
6278 : : * main recovery loop in PerformWalRecovery(). So we need to do
6279 : : * bookkeeping again to cover that case. This is confusing and it is
6280 : : * easy to think this call is irrelevant, which has happened three
6281 : : * times in development already. Leave it in.
6282 : : */
6283 : 22293 : RecordKnownAssignedTransactionIds(max_xid);
6284 : :
6285 : : /*
6286 : : * Hot standby also needs the commit LSN so that readers can safely
6287 : : * set hint bits.
6288 : : */
6289 : 22293 : TransactionIdAsyncCommitTree(xid, parsed->nsubxacts, parsed->subxacts, lsn);
6290 : :
6291 : : /*
6292 : : * We must mark clog before we update the ProcArray.
6293 : : */
6294 : 22293 : ExpireTreeKnownAssignedTransactionIds(xid, parsed->nsubxacts, parsed->subxacts, max_xid);
6295 : :
6296 : : /*
6297 : : * Send any cache invalidations attached to the commit. We must
6298 : : * maintain the same order of invalidation then release locks as
6299 : : * occurs in CommitTransaction().
6300 : : */
6301 : 22293 : ProcessCommittedInvalidationMessages(parsed->msgs, parsed->nmsgs,
6302 : 22293 : XactCompletionRelcacheInitFileInval(parsed->xinfo),
6303 : : parsed->dbId, parsed->tsId);
6304 : :
6305 : : /*
6306 : : * Release locks, if any. We do this for both two phase and normal one
6307 : : * phase transactions. In effect we are ignoring the prepare phase and
6308 : : * just going straight to lock release.
6309 : : */
6310 [ + + ]: 22293 : if (parsed->xinfo & XACT_XINFO_HAS_AE_LOCKS)
6311 : 10945 : StandbyReleaseLockTree(xid, parsed->nsubxacts, parsed->subxacts);
6312 : : }
6313 : :
6314 [ + + ]: 24521 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6315 : : {
6316 : : /* recover apply progress */
6317 : 20 : replorigin_advance(origin_id, parsed->origin_lsn, lsn,
6318 : : false /* backward */ , false /* WAL */ );
6319 : : }
6320 : :
6321 : : /* Make sure files supposed to be dropped are dropped */
6322 [ + + ]: 24521 : if (parsed->nrels > 0)
6323 : : {
6324 : : /*
6325 : : * First update minimum recovery point to cover this WAL record. Once
6326 : : * a relation is deleted, there's no going back. The buffer manager
6327 : : * enforces the WAL-first rule for normal updates to relation files,
6328 : : * so that the minimum recovery point is always updated before the
6329 : : * corresponding change in the data file is flushed to disk, but we
6330 : : * have to do the same here since we're bypassing the buffer manager.
6331 : : *
6332 : : * Doing this before deleting the files means that if a deletion fails
6333 : : * for some reason, you cannot start up the system even after restart,
6334 : : * until you fix the underlying situation so that the deletion will
6335 : : * succeed. Alternatively, we could update the minimum recovery point
6336 : : * after deletion, but that would leave a small window where the
6337 : : * WAL-first rule would be violated.
6338 : : */
6339 : 2393 : XLogFlush(lsn);
6340 : :
6341 : : /* Make sure files supposed to be dropped are dropped */
6342 : 2393 : DropRelationFiles(parsed->xlocators, parsed->nrels, true);
6343 : : }
6344 : :
6345 [ + + ]: 24521 : if (parsed->nstats > 0)
6346 : : {
6347 : : /* see equivalent call for relations above */
6348 : 3217 : XLogFlush(lsn);
6349 : :
6350 : 3217 : pgstat_execute_transactional_drops(parsed->nstats, parsed->stats);
6351 : : }
6352 : :
6353 : : /*
6354 : : * We issue an XLogFlush() for the same reason we emit ForceSyncCommit()
6355 : : * in normal operation. For example, in CREATE DATABASE, we copy all files
6356 : : * from the template database, and then commit the transaction. If we
6357 : : * crash after all the files have been copied but before the commit, you
6358 : : * have files in the data directory without an entry in pg_database. To
6359 : : * minimize the window for that, we use ForceSyncCommit() to rush the
6360 : : * commit record to disk as quick as possible. We have the same window
6361 : : * during recovery, and forcing an XLogFlush() (which updates
6362 : : * minRecoveryPoint during recovery) helps to reduce that problem window,
6363 : : * for any user that requested ForceSyncCommit().
6364 : : */
6365 [ + + ]: 24521 : if (XactCompletionForceSyncCommit(parsed->xinfo))
6366 : 51 : XLogFlush(lsn);
6367 : :
6368 : : /*
6369 : : * If asked by the primary (because someone is waiting for a synchronous
6370 : : * commit = remote_apply), we will need to ask walreceiver to send a reply
6371 : : * immediately.
6372 : : */
6373 [ + + ]: 24521 : if (XactCompletionApplyFeedback(parsed->xinfo))
6374 : 3 : XLogRequestWalReceiverReply();
6375 : 24521 : }
6376 : :
6377 : : /*
6378 : : * Be careful with the order of execution, as with xact_redo_commit().
6379 : : * The two functions are similar but differ in key places.
6380 : : *
6381 : : * Note also that an abort can be for a subtransaction and its children,
6382 : : * not just for a top level abort. That means we have to consider
6383 : : * topxid != xid, whereas in commit we would find topxid == xid always
6384 : : * because subtransaction commit is never WAL logged.
6385 : : */
6386 : : static void
6387 : 2170 : xact_redo_abort(xl_xact_parsed_abort *parsed, TransactionId xid,
6388 : : XLogRecPtr lsn, ReplOriginId origin_id)
6389 : : {
6390 : : TransactionId max_xid;
6391 : :
6392 : : Assert(TransactionIdIsValid(xid));
6393 : :
6394 : : /* Make sure nextXid is beyond any XID mentioned in the record. */
6395 : 2170 : max_xid = TransactionIdLatest(xid,
6396 : : parsed->nsubxacts,
6397 : 2170 : parsed->subxacts);
6398 : 2170 : AdvanceNextFullTransactionIdPastXid(max_xid);
6399 : :
6400 [ + + ]: 2170 : if (standbyState == STANDBY_DISABLED)
6401 : : {
6402 : : /* Mark the transaction aborted in pg_xact, no need for async stuff */
6403 : 20 : TransactionIdAbortTree(xid, parsed->nsubxacts, parsed->subxacts);
6404 : : }
6405 : : else
6406 : : {
6407 : : /*
6408 : : * If a transaction completion record arrives that has as-yet
6409 : : * unobserved subtransactions then this will not have been fully
6410 : : * handled by the call to RecordKnownAssignedTransactionIds() in the
6411 : : * main recovery loop in PerformWalRecovery(). So we need to do
6412 : : * bookkeeping again to cover that case. This is confusing and it is
6413 : : * easy to think this call is irrelevant, which has happened three
6414 : : * times in development already. Leave it in.
6415 : : */
6416 : 2150 : RecordKnownAssignedTransactionIds(max_xid);
6417 : :
6418 : : /* Mark the transaction aborted in pg_xact, no need for async stuff */
6419 : 2150 : TransactionIdAbortTree(xid, parsed->nsubxacts, parsed->subxacts);
6420 : :
6421 : : /*
6422 : : * We must update the ProcArray after we have marked clog.
6423 : : */
6424 : 2150 : ExpireTreeKnownAssignedTransactionIds(xid, parsed->nsubxacts, parsed->subxacts, max_xid);
6425 : :
6426 : : /*
6427 : : * There are no invalidation messages to send or undo.
6428 : : */
6429 : :
6430 : : /*
6431 : : * Release locks, if any. There are no invalidations to send.
6432 : : */
6433 [ + + ]: 2150 : if (parsed->xinfo & XACT_XINFO_HAS_AE_LOCKS)
6434 : 1351 : StandbyReleaseLockTree(xid, parsed->nsubxacts, parsed->subxacts);
6435 : : }
6436 : :
6437 [ + + ]: 2170 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6438 : : {
6439 : : /* recover apply progress */
6440 : 5 : replorigin_advance(origin_id, parsed->origin_lsn, lsn,
6441 : : false /* backward */ , false /* WAL */ );
6442 : : }
6443 : :
6444 : : /* Make sure files supposed to be dropped are dropped */
6445 [ + + ]: 2170 : if (parsed->nrels > 0)
6446 : : {
6447 : : /*
6448 : : * See comments about update of minimum recovery point on truncation,
6449 : : * in xact_redo_commit().
6450 : : */
6451 : 380 : XLogFlush(lsn);
6452 : :
6453 : 380 : DropRelationFiles(parsed->xlocators, parsed->nrels, true);
6454 : : }
6455 : :
6456 [ + + ]: 2170 : if (parsed->nstats > 0)
6457 : : {
6458 : : /* see equivalent call for relations above */
6459 : 506 : XLogFlush(lsn);
6460 : :
6461 : 506 : pgstat_execute_transactional_drops(parsed->nstats, parsed->stats);
6462 : : }
6463 : 2170 : }
6464 : :
6465 : : void
6466 : 27077 : xact_redo(XLogReaderState *record)
6467 : : {
6468 : 27077 : uint8 info = XLogRecGetInfo(record) & XLOG_XACT_OPMASK;
6469 : :
6470 : : /* Backup blocks are not used in xact records */
6471 : : Assert(!XLogRecHasAnyBlockRefs(record));
6472 : :
6473 [ + + ]: 27077 : if (info == XLOG_XACT_COMMIT)
6474 : : {
6475 : 24475 : xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
6476 : : xl_xact_parsed_commit parsed;
6477 : :
6478 : 24475 : ParseCommitRecord(XLogRecGetInfo(record), xlrec, &parsed);
6479 : 24475 : xact_redo_commit(&parsed, XLogRecGetXid(record),
6480 : 24475 : record->EndRecPtr, XLogRecGetOrigin(record));
6481 : : }
6482 [ + + ]: 2602 : else if (info == XLOG_XACT_COMMIT_PREPARED)
6483 : : {
6484 : 46 : xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
6485 : : xl_xact_parsed_commit parsed;
6486 : :
6487 : 46 : ParseCommitRecord(XLogRecGetInfo(record), xlrec, &parsed);
6488 : 46 : xact_redo_commit(&parsed, parsed.twophase_xid,
6489 : 46 : record->EndRecPtr, XLogRecGetOrigin(record));
6490 : :
6491 : : /* Delete TwoPhaseState gxact entry and/or 2PC file. */
6492 : 46 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
6493 : 46 : PrepareRedoRemove(parsed.twophase_xid, false);
6494 : 46 : LWLockRelease(TwoPhaseStateLock);
6495 : : }
6496 [ + + ]: 2556 : else if (info == XLOG_XACT_ABORT)
6497 : : {
6498 : 2145 : xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
6499 : : xl_xact_parsed_abort parsed;
6500 : :
6501 : 2145 : ParseAbortRecord(XLogRecGetInfo(record), xlrec, &parsed);
6502 : 2145 : xact_redo_abort(&parsed, XLogRecGetXid(record),
6503 : 2145 : record->EndRecPtr, XLogRecGetOrigin(record));
6504 : : }
6505 [ + + ]: 411 : else if (info == XLOG_XACT_ABORT_PREPARED)
6506 : : {
6507 : 25 : xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
6508 : : xl_xact_parsed_abort parsed;
6509 : :
6510 : 25 : ParseAbortRecord(XLogRecGetInfo(record), xlrec, &parsed);
6511 : 25 : xact_redo_abort(&parsed, parsed.twophase_xid,
6512 : 25 : record->EndRecPtr, XLogRecGetOrigin(record));
6513 : :
6514 : : /* Delete TwoPhaseState gxact entry and/or 2PC file. */
6515 : 25 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
6516 : 25 : PrepareRedoRemove(parsed.twophase_xid, false);
6517 : 25 : LWLockRelease(TwoPhaseStateLock);
6518 : : }
6519 [ + + ]: 386 : else if (info == XLOG_XACT_PREPARE)
6520 : : {
6521 : : /*
6522 : : * Store xid and start/end pointers of the WAL record in TwoPhaseState
6523 : : * gxact entry.
6524 : : */
6525 : 82 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
6526 : 82 : PrepareRedoAdd(InvalidFullTransactionId,
6527 : 82 : XLogRecGetData(record),
6528 : : record->ReadRecPtr,
6529 : : record->EndRecPtr,
6530 : 82 : XLogRecGetOrigin(record));
6531 : 82 : LWLockRelease(TwoPhaseStateLock);
6532 : : }
6533 [ + + ]: 304 : else if (info == XLOG_XACT_ASSIGNMENT)
6534 : : {
6535 : 22 : xl_xact_assignment *xlrec = (xl_xact_assignment *) XLogRecGetData(record);
6536 : :
6537 [ + - ]: 22 : if (standbyState >= STANDBY_INITIALIZED)
6538 : 22 : ProcArrayApplyXidAssignment(xlrec->xtop,
6539 : 22 : xlrec->nsubxacts, xlrec->xsub);
6540 : : }
6541 [ - + ]: 282 : else if (info == XLOG_XACT_INVALIDATIONS)
6542 : : {
6543 : : /*
6544 : : * XXX we do ignore this for now, what matters are invalidations
6545 : : * written into the commit record.
6546 : : */
6547 : : }
6548 : : else
6549 [ # # ]: 0 : elog(PANIC, "xact_redo: unknown op code %u", info);
6550 : 27077 : }
|