PostgreSQL Source Code  git master
xact.c
Go to the documentation of this file.
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-2020, 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/xlogutils.h"
33 #include "catalog/index.h"
34 #include "catalog/namespace.h"
35 #include "catalog/pg_enum.h"
36 #include "catalog/storage.h"
37 #include "commands/async.h"
38 #include "commands/tablecmds.h"
39 #include "commands/trigger.h"
40 #include "executor/spi.h"
41 #include "libpq/be-fsstubs.h"
42 #include "libpq/pqsignal.h"
43 #include "miscadmin.h"
44 #include "pg_trace.h"
45 #include "pgstat.h"
46 #include "replication/logical.h"
48 #include "replication/origin.h"
49 #include "replication/syncrep.h"
50 #include "replication/walsender.h"
52 #include "storage/fd.h"
53 #include "storage/lmgr.h"
54 #include "storage/md.h"
55 #include "storage/predicate.h"
56 #include "storage/proc.h"
57 #include "storage/procarray.h"
58 #include "storage/sinvaladt.h"
59 #include "storage/smgr.h"
60 #include "utils/builtins.h"
61 #include "utils/catcache.h"
62 #include "utils/combocid.h"
63 #include "utils/guc.h"
64 #include "utils/inval.h"
65 #include "utils/memutils.h"
66 #include "utils/relmapper.h"
67 #include "utils/snapmgr.h"
68 #include "utils/timeout.h"
69 #include "utils/timestamp.h"
70 
71 /*
72  * User-tweakable parameters
73  */
76 
77 bool DefaultXactReadOnly = false;
79 
80 bool DefaultXactDeferrable = false;
82 
84 
85 /*
86  * CheckXidAlive is a xid value pointing to a possibly ongoing (sub)
87  * transaction. Currently, it is used in logical decoding. It's possible
88  * that such transactions can get aborted while the decoding is ongoing in
89  * which case we skip decoding that particular transaction. To ensure that we
90  * check whether the CheckXidAlive is aborted after fetching the tuple from
91  * system tables. We also ensure that during logical decoding we never
92  * directly access the tableam or heap APIs because we are checking for the
93  * concurrent aborts only in systable_* APIs.
94  */
96 bool bsysscan = false;
97 
98 /*
99  * When running as a parallel worker, we place only a single
100  * TransactionStateData on the parallel worker's state stack, and the XID
101  * reflected there will be that of the *innermost* currently-active
102  * subtransaction in the backend that initiated parallelism. However,
103  * GetTopTransactionId() and TransactionIdIsCurrentTransactionId()
104  * need to return the same answers in the parallel worker as they would have
105  * in the user backend, so we need some additional bookkeeping.
106  *
107  * XactTopFullTransactionId stores the XID of our toplevel transaction, which
108  * will be the same as TopTransactionStateData.fullTransactionId in an
109  * ordinary backend; but in a parallel backend, which does not have the entire
110  * transaction state, it will instead be copied from the backend that started
111  * the parallel operation.
112  *
113  * nParallelCurrentXids will be 0 and ParallelCurrentXids NULL in an ordinary
114  * backend, but in a parallel backend, nParallelCurrentXids will contain the
115  * number of XIDs that need to be considered current, and ParallelCurrentXids
116  * will contain the XIDs themselves. This includes all XIDs that were current
117  * or sub-committed in the parent at the time the parallel operation began.
118  * The XIDs are stored sorted in numerical order (not logical order) to make
119  * lookups as fast as possible.
120  */
124 
125 /*
126  * Miscellaneous flag bits to record events which occur on the top level
127  * transaction. These flags are only persisted in MyXactFlags and are intended
128  * so we remember to do certain things later on in the transaction. This is
129  * globally accessible, so can be set from anywhere in the code that requires
130  * recording flags.
131  */
133 
134 /*
135  * transaction states - transaction state from server perspective
136  */
137 typedef enum TransState
138 {
139  TRANS_DEFAULT, /* idle */
140  TRANS_START, /* transaction starting */
141  TRANS_INPROGRESS, /* inside a valid transaction */
142  TRANS_COMMIT, /* commit in progress */
143  TRANS_ABORT, /* abort in progress */
144  TRANS_PREPARE /* prepare in progress */
145 } TransState;
146 
147 /*
148  * transaction block states - transaction state of client queries
149  *
150  * Note: the subtransaction states are used only for non-topmost
151  * transactions; the others appear only in the topmost transaction.
152  */
153 typedef enum TBlockState
154 {
155  /* not-in-transaction-block states */
156  TBLOCK_DEFAULT, /* idle */
157  TBLOCK_STARTED, /* running single-query transaction */
158 
159  /* transaction block states */
160  TBLOCK_BEGIN, /* starting transaction block */
161  TBLOCK_INPROGRESS, /* live transaction */
162  TBLOCK_IMPLICIT_INPROGRESS, /* live transaction after implicit BEGIN */
163  TBLOCK_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
164  TBLOCK_END, /* COMMIT received */
165  TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
166  TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
167  TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
168  TBLOCK_PREPARE, /* live xact, PREPARE received */
169 
170  /* subtransaction states */
171  TBLOCK_SUBBEGIN, /* starting a subtransaction */
172  TBLOCK_SUBINPROGRESS, /* live subtransaction */
173  TBLOCK_SUBRELEASE, /* RELEASE received */
174  TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
175  TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
176  TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
177  TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
178  TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
179  TBLOCK_SUBABORT_RESTART /* failed subxact, ROLLBACK TO received */
180 } TBlockState;
181 
182 /*
183  * transaction state structure
184  */
185 typedef struct TransactionStateData
186 {
187  FullTransactionId fullTransactionId; /* my FullTransactionId */
188  SubTransactionId subTransactionId; /* my subxact ID */
189  char *name; /* savepoint name, if any */
190  int savepointLevel; /* savepoint level */
191  TransState state; /* low-level state */
192  TBlockState blockState; /* high-level state */
193  int nestingLevel; /* transaction nesting depth */
194  int gucNestLevel; /* GUC context nesting depth */
195  MemoryContext curTransactionContext; /* my xact-lifetime context */
196  ResourceOwner curTransactionOwner; /* my query resources */
197  TransactionId *childXids; /* subcommitted child XIDs, in XID order */
198  int nChildXids; /* # of subcommitted child XIDs */
199  int maxChildXids; /* allocated size of childXids[] */
200  Oid prevUser; /* previous CurrentUserId setting */
201  int prevSecContext; /* previous SecurityRestrictionContext */
202  bool prevXactReadOnly; /* entry-time xact r/o state */
203  bool startedInRecovery; /* did we start in recovery? */
204  bool didLogXid; /* has xid been included in WAL record? */
205  int parallelModeLevel; /* Enter/ExitParallelMode counter */
206  bool chain; /* start a new block after this one */
207  bool assigned; /* assigned to top-level XID */
208  struct TransactionStateData *parent; /* back link to parent */
210 
212 
213 /*
214  * Serialized representation used to transmit transaction state to parallel
215  * workers through shared memory.
216  */
218 {
225  TransactionId parallelCurrentXids[FLEXIBLE_ARRAY_MEMBER];
227 
228 /* The size of SerializedTransactionState, not including the final array. */
229 #define SerializedTransactionStateHeaderSize \
230  offsetof(SerializedTransactionState, parallelCurrentXids)
231 
232 /*
233  * CurrentTransactionState always points to the current transaction state
234  * block. It will point to TopTransactionStateData when not in a
235  * transaction at all, or when in a top-level transaction.
236  */
238  .state = TRANS_DEFAULT,
239  .blockState = TBLOCK_DEFAULT,
240  .assigned = false,
241 };
242 
243 /*
244  * unreportedXids holds XIDs of all subtransactions that have not yet been
245  * reported in an XLOG_XACT_ASSIGNMENT record.
246  */
247 static int nUnreportedXids;
249 
251 
252 /*
253  * The subtransaction ID and command ID assignment counters are global
254  * to a whole transaction, so we do not keep them in the state stack.
255  */
259 
260 /*
261  * xactStartTimestamp is the value of transaction_timestamp().
262  * stmtStartTimestamp is the value of statement_timestamp().
263  * xactStopTimestamp is the time at which we log a commit or abort WAL record.
264  * These do not change as we enter and exit subtransactions, so we don't
265  * keep them inside the TransactionState stack.
266  */
270 
271 /*
272  * GID to be used for preparing the current transaction. This is also
273  * global to a whole transaction, so we don't keep it in the state stack.
274  */
275 static char *prepareGID;
276 
277 /*
278  * Some commands want to force synchronous commit.
279  */
280 static bool forceSyncCommit = false;
281 
282 /* Flag for logging statements in a transaction. */
283 bool xact_is_sampled = false;
284 
285 /*
286  * Private context for transaction-abort work --- we reserve space for this
287  * at startup to ensure that AbortTransaction and AbortSubTransaction can work
288  * when we've run out of memory.
289  */
291 
292 /*
293  * List of add-on start- and end-of-xact callbacks
294  */
295 typedef struct XactCallbackItem
296 {
299  void *arg;
301 
303 
304 /*
305  * List of add-on start- and end-of-subxact callbacks
306  */
307 typedef struct SubXactCallbackItem
308 {
311  void *arg;
313 
315 
316 
317 /* local function prototypes */
319 static void AbortTransaction(void);
320 static void AtAbort_Memory(void);
321 static void AtCleanup_Memory(void);
322 static void AtAbort_ResourceOwner(void);
323 static void AtCCI_LocalCache(void);
324 static void AtCommit_Memory(void);
325 static void AtStart_Cache(void);
326 static void AtStart_Memory(void);
327 static void AtStart_ResourceOwner(void);
328 static void CallXactCallbacks(XactEvent event);
329 static void CallSubXactCallbacks(SubXactEvent event,
330  SubTransactionId mySubid,
331  SubTransactionId parentSubid);
332 static void CleanupTransaction(void);
333 static void CheckTransactionBlock(bool isTopLevel, bool throwError,
334  const char *stmtType);
335 static void CommitTransaction(void);
336 static TransactionId RecordTransactionAbort(bool isSubXact);
337 static void StartTransaction(void);
338 
339 static void StartSubTransaction(void);
340 static void CommitSubTransaction(void);
341 static void AbortSubTransaction(void);
342 static void CleanupSubTransaction(void);
343 static void PushTransaction(void);
344 static void PopTransaction(void);
345 
346 static void AtSubAbort_Memory(void);
347 static void AtSubCleanup_Memory(void);
348 static void AtSubAbort_ResourceOwner(void);
349 static void AtSubCommit_Memory(void);
350 static void AtSubStart_Memory(void);
351 static void AtSubStart_ResourceOwner(void);
352 
353 static void ShowTransactionState(const char *str);
354 static void ShowTransactionStateRec(const char *str, TransactionState state);
355 static const char *BlockStateAsString(TBlockState blockState);
356 static const char *TransStateAsString(TransState state);
357 
358 
359 /* ----------------------------------------------------------------
360  * transaction state accessors
361  * ----------------------------------------------------------------
362  */
363 
364 /*
365  * IsTransactionState
366  *
367  * This returns true if we are inside a valid transaction; that is,
368  * it is safe to initiate database access, take heavyweight locks, etc.
369  */
370 bool
372 {
374 
375  /*
376  * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
377  * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
378  * TRANS_PREPARE since it might be too soon or too late within those
379  * transition states to do anything interesting. Hence, the only "valid"
380  * state is TRANS_INPROGRESS.
381  */
382  return (s->state == TRANS_INPROGRESS);
383 }
384 
385 /*
386  * IsAbortedTransactionBlockState
387  *
388  * This returns true if we are within an aborted transaction block.
389  */
390 bool
392 {
394 
395  if (s->blockState == TBLOCK_ABORT ||
397  return true;
398 
399  return false;
400 }
401 
402 
403 /*
404  * GetTopTransactionId
405  *
406  * This will return the XID of the main transaction, assigning one if
407  * it's not yet set. Be careful to call this only inside a valid xact.
408  */
411 {
412  if (!FullTransactionIdIsValid(XactTopFullTransactionId))
413  AssignTransactionId(&TopTransactionStateData);
414  return XidFromFullTransactionId(XactTopFullTransactionId);
415 }
416 
417 /*
418  * GetTopTransactionIdIfAny
419  *
420  * This will return the XID of the main transaction, if one is assigned.
421  * It will return InvalidTransactionId if we are not currently inside a
422  * transaction, or inside a transaction that hasn't yet been assigned an XID.
423  */
426 {
427  return XidFromFullTransactionId(XactTopFullTransactionId);
428 }
429 
430 /*
431  * GetCurrentTransactionId
432  *
433  * This will return the XID of the current transaction (main or sub
434  * transaction), assigning one if it's not yet set. Be careful to call this
435  * only inside a valid xact.
436  */
439 {
441 
445 }
446 
447 /*
448  * GetCurrentTransactionIdIfAny
449  *
450  * This will return the XID of the current sub xact, if one is assigned.
451  * It will return InvalidTransactionId if we are not currently inside a
452  * transaction, or inside a transaction that hasn't been assigned an XID yet.
453  */
456 {
457  return XidFromFullTransactionId(CurrentTransactionState->fullTransactionId);
458 }
459 
460 /*
461  * GetTopFullTransactionId
462  *
463  * This will return the FullTransactionId of the main transaction, assigning
464  * one if it's not yet set. Be careful to call this only inside a valid xact.
465  */
468 {
469  if (!FullTransactionIdIsValid(XactTopFullTransactionId))
470  AssignTransactionId(&TopTransactionStateData);
472 }
473 
474 /*
475  * GetTopFullTransactionIdIfAny
476  *
477  * This will return the FullTransactionId of the main transaction, if one is
478  * assigned. It will return InvalidFullTransactionId if we are not currently
479  * inside a transaction, or inside a transaction that hasn't yet been assigned
480  * one.
481  */
484 {
486 }
487 
488 /*
489  * GetCurrentFullTransactionId
490  *
491  * This will return the FullTransactionId of the current transaction (main or
492  * sub transaction), assigning one if it's not yet set. Be careful to call
493  * this only inside a valid xact.
494  */
497 {
499 
502  return s->fullTransactionId;
503 }
504 
505 /*
506  * GetCurrentFullTransactionIdIfAny
507  *
508  * This will return the FullTransactionId of the current sub xact, if one is
509  * assigned. It will return InvalidFullTransactionId if we are not currently
510  * inside a transaction, or inside a transaction that hasn't been assigned one
511  * yet.
512  */
515 {
516  return CurrentTransactionState->fullTransactionId;
517 }
518 
519 /*
520  * MarkCurrentTransactionIdLoggedIfAny
521  *
522  * Remember that the current xid - if it is assigned - now has been wal logged.
523  */
524 void
526 {
527  if (FullTransactionIdIsValid(CurrentTransactionState->fullTransactionId))
528  CurrentTransactionState->didLogXid = true;
529 }
530 
531 
532 /*
533  * GetStableLatestTransactionId
534  *
535  * Get the transaction's XID if it has one, else read the next-to-be-assigned
536  * XID. Once we have a value, return that same value for the remainder of the
537  * current transaction. This is meant to provide the reference point for the
538  * age(xid) function, but might be useful for other maintenance tasks as well.
539  */
542 {
544  static TransactionId stablexid = InvalidTransactionId;
545 
546  if (lxid != MyProc->lxid)
547  {
548  lxid = MyProc->lxid;
549  stablexid = GetTopTransactionIdIfAny();
550  if (!TransactionIdIsValid(stablexid))
551  stablexid = ReadNewTransactionId();
552  }
553 
554  Assert(TransactionIdIsValid(stablexid));
555 
556  return stablexid;
557 }
558 
559 /*
560  * AssignTransactionId
561  *
562  * Assigns a new permanent FullTransactionId to the given TransactionState.
563  * We do not assign XIDs to transactions until/unless this is called.
564  * Also, any parent TransactionStates that don't yet have XIDs are assigned
565  * one; this maintains the invariant that a child transaction has an XID
566  * following its parent's.
567  */
568 static void
570 {
571  bool isSubXact = (s->parent != NULL);
572  ResourceOwner currentOwner;
573  bool log_unknown_top = false;
574 
575  /* Assert that caller didn't screw up */
578 
579  /*
580  * Workers synchronize transaction state at the beginning of each parallel
581  * operation, so we can't account for new XIDs at this point.
582  */
584  elog(ERROR, "cannot assign XIDs during a parallel operation");
585 
586  /*
587  * Ensure parent(s) have XIDs, so that a child always has an XID later
588  * than its parent. Mustn't recurse here, or we might get a stack
589  * overflow if we're at the bottom of a huge stack of subtransactions none
590  * of which have XIDs yet.
591  */
592  if (isSubXact && !FullTransactionIdIsValid(s->parent->fullTransactionId))
593  {
594  TransactionState p = s->parent;
595  TransactionState *parents;
596  size_t parentOffset = 0;
597 
598  parents = palloc(sizeof(TransactionState) * s->nestingLevel);
599  while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
600  {
601  parents[parentOffset++] = p;
602  p = p->parent;
603  }
604 
605  /*
606  * This is technically a recursive call, but the recursion will never
607  * be more than one layer deep.
608  */
609  while (parentOffset != 0)
610  AssignTransactionId(parents[--parentOffset]);
611 
612  pfree(parents);
613  }
614 
615  /*
616  * When wal_level=logical, guarantee that a subtransaction's xid can only
617  * be seen in the WAL stream if its toplevel xid has been logged before.
618  * If necessary we log an xact_assignment record with fewer than
619  * PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't set
620  * for a transaction even though it appears in a WAL record, we just might
621  * superfluously log something. That can happen when an xid is included
622  * somewhere inside a wal record, but not in XLogRecord->xl_xid, like in
623  * xl_standby_locks.
624  */
625  if (isSubXact && XLogLogicalInfoActive() &&
626  !TopTransactionStateData.didLogXid)
627  log_unknown_top = true;
628 
629  /*
630  * Generate a new FullTransactionId and record its xid in PG_PROC and
631  * pg_subtrans.
632  *
633  * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
634  * shared storage other than PG_PROC; because if there's no room for it in
635  * PG_PROC, the subtrans entry is needed to ensure that other backends see
636  * the Xid as "running". See GetNewTransactionId.
637  */
638  s->fullTransactionId = GetNewTransactionId(isSubXact);
639  if (!isSubXact)
640  XactTopFullTransactionId = s->fullTransactionId;
641 
642  if (isSubXact)
645 
646  /*
647  * If it's a top-level transaction, the predicate locking system needs to
648  * be told about it too.
649  */
650  if (!isSubXact)
652 
653  /*
654  * Acquire lock on the transaction XID. (We assume this cannot block.) We
655  * have to ensure that the lock is assigned to the transaction's own
656  * ResourceOwner.
657  */
658  currentOwner = CurrentResourceOwner;
660 
662 
663  CurrentResourceOwner = currentOwner;
664 
665  /*
666  * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
667  * top-level transaction we issue a WAL record for the assignment. We
668  * include the top-level xid and all the subxids that have not yet been
669  * reported using XLOG_XACT_ASSIGNMENT records.
670  *
671  * This is required to limit the amount of shared memory required in a hot
672  * standby server to keep track of in-progress XIDs. See notes for
673  * RecordKnownAssignedTransactionIds().
674  *
675  * We don't keep track of the immediate parent of each subxid, only the
676  * top-level transaction that each subxact belongs to. This is correct in
677  * recovery only because aborted subtransactions are separately WAL
678  * logged.
679  *
680  * This is correct even for the case where several levels above us didn't
681  * have an xid assigned as we recursed up to them beforehand.
682  */
683  if (isSubXact && XLogStandbyInfoActive())
684  {
686  nUnreportedXids++;
687 
688  /*
689  * ensure this test matches similar one in
690  * RecoverPreparedTransactions()
691  */
693  log_unknown_top)
694  {
695  xl_xact_assignment xlrec;
696 
697  /*
698  * xtop is always set by now because we recurse up transaction
699  * stack to the highest unassigned xid and then come back down
700  */
701  xlrec.xtop = GetTopTransactionId();
703  xlrec.nsubxacts = nUnreportedXids;
704 
705  XLogBeginInsert();
706  XLogRegisterData((char *) &xlrec, MinSizeOfXactAssignment);
708  nUnreportedXids * sizeof(TransactionId));
709 
710  (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
711 
712  nUnreportedXids = 0;
713  /* mark top, not current xact as having been logged */
714  TopTransactionStateData.didLogXid = true;
715  }
716  }
717 }
718 
719 /*
720  * GetCurrentSubTransactionId
721  */
724 {
726 
727  return s->subTransactionId;
728 }
729 
730 /*
731  * SubTransactionIsActive
732  *
733  * Test if the specified subxact ID is still active. Note caller is
734  * responsible for checking whether this ID is relevant to the current xact.
735  */
736 bool
738 {
740 
741  for (s = CurrentTransactionState; s != NULL; s = s->parent)
742  {
743  if (s->state == TRANS_ABORT)
744  continue;
745  if (s->subTransactionId == subxid)
746  return true;
747  }
748  return false;
749 }
750 
751 
752 /*
753  * GetCurrentCommandId
754  *
755  * "used" must be true if the caller intends to use the command ID to mark
756  * inserted/updated/deleted tuples. false means the ID is being fetched
757  * for read-only purposes (ie, as a snapshot validity cutoff). See
758  * CommandCounterIncrement() for discussion.
759  */
760 CommandId
762 {
763  /* this is global to a transaction, not subtransaction-local */
764  if (used)
765  {
766  /*
767  * Forbid setting currentCommandIdUsed in a parallel worker, because
768  * we have no provision for communicating this back to the leader. We
769  * could relax this restriction when currentCommandIdUsed was already
770  * true at the start of the parallel operation.
771  */
773  currentCommandIdUsed = true;
774  }
775  return currentCommandId;
776 }
777 
778 /*
779  * SetParallelStartTimestamps
780  *
781  * In a parallel worker, we should inherit the parent transaction's
782  * timestamps rather than setting our own. The parallel worker
783  * infrastructure must call this to provide those values before
784  * calling StartTransaction() or SetCurrentStatementStartTimestamp().
785  */
786 void
788 {
790  xactStartTimestamp = xact_ts;
791  stmtStartTimestamp = stmt_ts;
792 }
793 
794 /*
795  * GetCurrentTransactionStartTimestamp
796  */
799 {
800  return xactStartTimestamp;
801 }
802 
803 /*
804  * GetCurrentStatementStartTimestamp
805  */
808 {
809  return stmtStartTimestamp;
810 }
811 
812 /*
813  * GetCurrentTransactionStopTimestamp
814  *
815  * We return current time if the transaction stop time hasn't been set
816  * (which can happen if we decide we don't need to log an XLOG record).
817  */
820 {
821  if (xactStopTimestamp != 0)
822  return xactStopTimestamp;
823  return GetCurrentTimestamp();
824 }
825 
826 /*
827  * SetCurrentStatementStartTimestamp
828  *
829  * In a parallel worker, this should already have been provided by a call
830  * to SetParallelStartTimestamps().
831  */
832 void
834 {
835  if (!IsParallelWorker())
837  else
839 }
840 
841 /*
842  * SetCurrentTransactionStopTimestamp
843  */
844 static inline void
846 {
848 }
849 
850 /*
851  * GetCurrentTransactionNestLevel
852  *
853  * Note: this will return zero when not inside any transaction, one when
854  * inside a top-level transaction, etc.
855  */
856 int
858 {
860 
861  return s->nestingLevel;
862 }
863 
864 
865 /*
866  * TransactionIdIsCurrentTransactionId
867  */
868 bool
870 {
872 
873  /*
874  * We always say that BootstrapTransactionId is "not my transaction ID"
875  * even when it is (ie, during bootstrap). Along with the fact that
876  * transam.c always treats BootstrapTransactionId as already committed,
877  * this causes the heapam_visibility.c routines to see all tuples as
878  * committed, which is what we need during bootstrap. (Bootstrap mode
879  * only inserts tuples, it never updates or deletes them, so all tuples
880  * can be presumed good immediately.)
881  *
882  * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
883  * not my transaction ID, so we can just return "false" immediately for
884  * any non-normal XID.
885  */
886  if (!TransactionIdIsNormal(xid))
887  return false;
888 
890  return true;
891 
892  /*
893  * In parallel workers, the XIDs we must consider as current are stored in
894  * ParallelCurrentXids rather than the transaction-state stack. Note that
895  * the XIDs in this array are sorted numerically rather than according to
896  * transactionIdPrecedes order.
897  */
898  if (nParallelCurrentXids > 0)
899  {
900  int low,
901  high;
902 
903  low = 0;
904  high = nParallelCurrentXids - 1;
905  while (low <= high)
906  {
907  int middle;
908  TransactionId probe;
909 
910  middle = low + (high - low) / 2;
911  probe = ParallelCurrentXids[middle];
912  if (probe == xid)
913  return true;
914  else if (probe < xid)
915  low = middle + 1;
916  else
917  high = middle - 1;
918  }
919  return false;
920  }
921 
922  /*
923  * We will return true for the Xid of the current subtransaction, any of
924  * its subcommitted children, any of its parents, or any of their
925  * previously subcommitted children. However, a transaction being aborted
926  * is no longer "current", even though it may still have an entry on the
927  * state stack.
928  */
929  for (s = CurrentTransactionState; s != NULL; s = s->parent)
930  {
931  int low,
932  high;
933 
934  if (s->state == TRANS_ABORT)
935  continue;
937  continue; /* it can't have any child XIDs either */
939  return true;
940  /* As the childXids array is ordered, we can use binary search */
941  low = 0;
942  high = s->nChildXids - 1;
943  while (low <= high)
944  {
945  int middle;
946  TransactionId probe;
947 
948  middle = low + (high - low) / 2;
949  probe = s->childXids[middle];
950  if (TransactionIdEquals(probe, xid))
951  return true;
952  else if (TransactionIdPrecedes(probe, xid))
953  low = middle + 1;
954  else
955  high = middle - 1;
956  }
957  }
958 
959  return false;
960 }
961 
962 /*
963  * TransactionStartedDuringRecovery
964  *
965  * Returns true if the current transaction started while recovery was still
966  * in progress. Recovery might have ended since so RecoveryInProgress() might
967  * return false already.
968  */
969 bool
971 {
972  return CurrentTransactionState->startedInRecovery;
973 }
974 
975 /*
976  * EnterParallelMode
977  */
978 void
980 {
982 
983  Assert(s->parallelModeLevel >= 0);
984 
985  ++s->parallelModeLevel;
986 }
987 
988 /*
989  * ExitParallelMode
990  */
991 void
993 {
995 
996  Assert(s->parallelModeLevel > 0);
998 
999  --s->parallelModeLevel;
1000 }
1001 
1002 /*
1003  * IsInParallelMode
1004  *
1005  * Are we in a parallel operation, as either the leader or a worker? Check
1006  * this to prohibit operations that change backend-local state expected to
1007  * match across all workers. Mere caches usually don't require such a
1008  * restriction. State modified in a strict push/pop fashion, such as the
1009  * active snapshot stack, is often fine.
1010  */
1011 bool
1013 {
1014  return CurrentTransactionState->parallelModeLevel != 0;
1015 }
1016 
1017 /*
1018  * CommandCounterIncrement
1019  */
1020 void
1022 {
1023  /*
1024  * If the current value of the command counter hasn't been "used" to mark
1025  * tuples, we need not increment it, since there's no need to distinguish
1026  * a read-only command from others. This helps postpone command counter
1027  * overflow, and keeps no-op CommandCounterIncrement operations cheap.
1028  */
1030  {
1031  /*
1032  * Workers synchronize transaction state at the beginning of each
1033  * parallel operation, so we can't account for new commands after that
1034  * point.
1035  */
1037  elog(ERROR, "cannot start commands during a parallel operation");
1038 
1039  currentCommandId += 1;
1041  {
1042  currentCommandId -= 1;
1043  ereport(ERROR,
1044  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1045  errmsg("cannot have more than 2^32-2 commands in a transaction")));
1046  }
1047  currentCommandIdUsed = false;
1048 
1049  /* Propagate new command ID into static snapshots */
1051 
1052  /*
1053  * Make any catalog changes done by the just-completed command visible
1054  * in the local syscache. We obviously don't need to do this after a
1055  * read-only command. (But see hacks in inval.c to make real sure we
1056  * don't think a command that queued inval messages was read-only.)
1057  */
1058  AtCCI_LocalCache();
1059  }
1060 }
1061 
1062 /*
1063  * ForceSyncCommit
1064  *
1065  * Interface routine to allow commands to force a synchronous commit of the
1066  * current top-level transaction. Currently, two-phase commit does not
1067  * persist and restore this variable. So long as all callers use
1068  * PreventInTransactionBlock(), that omission has no consequences.
1069  */
1070 void
1072 {
1073  forceSyncCommit = true;
1074 }
1075 
1076 
1077 /* ----------------------------------------------------------------
1078  * StartTransaction stuff
1079  * ----------------------------------------------------------------
1080  */
1081 
1082 /*
1083  * AtStart_Cache
1084  */
1085 static void
1087 {
1089 }
1090 
1091 /*
1092  * AtStart_Memory
1093  */
1094 static void
1096 {
1098 
1099  /*
1100  * If this is the first time through, create a private context for
1101  * AbortTransaction to work in. By reserving some space now, we can
1102  * insulate AbortTransaction from out-of-memory scenarios. Like
1103  * ErrorContext, we set it up with slow growth rate and a nonzero minimum
1104  * size, so that space will be reserved immediately.
1105  */
1106  if (TransactionAbortContext == NULL)
1107  TransactionAbortContext =
1109  "TransactionAbortContext",
1110  32 * 1024,
1111  32 * 1024,
1112  32 * 1024);
1113 
1114  /*
1115  * We shouldn't have a transaction context already.
1116  */
1117  Assert(TopTransactionContext == NULL);
1118 
1119  /*
1120  * Create a toplevel context for the transaction.
1121  */
1124  "TopTransactionContext",
1126 
1127  /*
1128  * In a top-level transaction, CurTransactionContext is the same as
1129  * TopTransactionContext.
1130  */
1133 
1134  /* Make the CurTransactionContext active. */
1136 }
1137 
1138 /*
1139  * AtStart_ResourceOwner
1140  */
1141 static void
1143 {
1145 
1146  /*
1147  * We shouldn't have a transaction resource owner already.
1148  */
1150 
1151  /*
1152  * Create a toplevel resource owner for the transaction.
1153  */
1154  s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1155 
1159 }
1160 
1161 /* ----------------------------------------------------------------
1162  * StartSubTransaction stuff
1163  * ----------------------------------------------------------------
1164  */
1165 
1166 /*
1167  * AtSubStart_Memory
1168  */
1169 static void
1171 {
1173 
1174  Assert(CurTransactionContext != NULL);
1175 
1176  /*
1177  * Create a CurTransactionContext, which will be used to hold data that
1178  * survives subtransaction commit but disappears on subtransaction abort.
1179  * We make it a child of the immediate parent's CurTransactionContext.
1180  */
1182  "CurTransactionContext",
1185 
1186  /* Make the CurTransactionContext active. */
1188 }
1189 
1190 /*
1191  * AtSubStart_ResourceOwner
1192  */
1193 static void
1195 {
1197 
1198  Assert(s->parent != NULL);
1199 
1200  /*
1201  * Create a resource owner for the subtransaction. We make it a child of
1202  * the immediate parent's resource owner.
1203  */
1204  s->curTransactionOwner =
1206  "SubTransaction");
1207 
1210 }
1211 
1212 /* ----------------------------------------------------------------
1213  * CommitTransaction stuff
1214  * ----------------------------------------------------------------
1215  */
1216 
1217 /*
1218  * RecordTransactionCommit
1219  *
1220  * Returns latest XID among xact and its children, or InvalidTransactionId
1221  * if the xact has no XID. (We compute that here just because it's easier.)
1222  *
1223  * If you change this function, see RecordTransactionCommitPrepared also.
1224  */
1225 static TransactionId
1227 {
1229  bool markXidCommitted = TransactionIdIsValid(xid);
1230  TransactionId latestXid = InvalidTransactionId;
1231  int nrels;
1232  RelFileNode *rels;
1233  int nchildren;
1234  TransactionId *children;
1235  int nmsgs = 0;
1236  SharedInvalidationMessage *invalMessages = NULL;
1237  bool RelcacheInitFileInval = false;
1238  bool wrote_xlog;
1239 
1240  /*
1241  * Log pending invalidations for logical decoding of in-progress
1242  * transactions. Normally for DDLs, we log this at each command end,
1243  * however, for certain cases where we directly update the system table
1244  * without a transaction block, the invalidations are not logged till this
1245  * time.
1246  */
1247  if (XLogLogicalInfoActive())
1249 
1250  /* Get data needed for commit record */
1251  nrels = smgrGetPendingDeletes(true, &rels);
1252  nchildren = xactGetCommittedChildren(&children);
1253  if (XLogStandbyInfoActive())
1254  nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
1255  &RelcacheInitFileInval);
1256  wrote_xlog = (XactLastRecEnd != 0);
1257 
1258  /*
1259  * If we haven't been assigned an XID yet, we neither can, nor do we want
1260  * to write a COMMIT record.
1261  */
1262  if (!markXidCommitted)
1263  {
1264  /*
1265  * We expect that every RelationDropStorage is followed by a catalog
1266  * update, and hence XID assignment, so we shouldn't get here with any
1267  * pending deletes. Use a real test not just an Assert to check this,
1268  * since it's a bit fragile.
1269  */
1270  if (nrels != 0)
1271  elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
1272 
1273  /* Can't have child XIDs either; AssignTransactionId enforces this */
1274  Assert(nchildren == 0);
1275 
1276  /*
1277  * Transactions without an assigned xid can contain invalidation
1278  * messages (e.g. explicit relcache invalidations or catcache
1279  * invalidations for inplace updates); standbys need to process those.
1280  * We can't emit a commit record without an xid, and we don't want to
1281  * force assigning an xid, because that'd be problematic for e.g.
1282  * vacuum. Hence we emit a bespoke record for the invalidations. We
1283  * don't want to use that in case a commit record is emitted, so they
1284  * happen synchronously with commits (besides not wanting to emit more
1285  * WAL records).
1286  */
1287  if (nmsgs != 0)
1288  {
1289  LogStandbyInvalidations(nmsgs, invalMessages,
1290  RelcacheInitFileInval);
1291  wrote_xlog = true; /* not strictly necessary */
1292  }
1293 
1294  /*
1295  * If we didn't create XLOG entries, we're done here; otherwise we
1296  * should trigger flushing those entries the same as a commit record
1297  * would. This will primarily happen for HOT pruning and the like; we
1298  * want these to be flushed to disk in due time.
1299  */
1300  if (!wrote_xlog)
1301  goto cleanup;
1302  }
1303  else
1304  {
1305  bool replorigin;
1306 
1307  /*
1308  * Are we using the replication origins feature? Or, in other words,
1309  * are we replaying remote actions?
1310  */
1311  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1313 
1314  /*
1315  * Begin commit critical section and insert the commit XLOG record.
1316  */
1317  /* Tell bufmgr and smgr to prepare for commit */
1318  BufmgrCommit();
1319 
1320  /*
1321  * Mark ourselves as within our "commit critical section". This
1322  * forces any concurrent checkpoint to wait until we've updated
1323  * pg_xact. Without this, it is possible for the checkpoint to set
1324  * REDO after the XLOG record but fail to flush the pg_xact update to
1325  * disk, leading to loss of the transaction commit if the system
1326  * crashes a little later.
1327  *
1328  * Note: we could, but don't bother to, set this flag in
1329  * RecordTransactionAbort. That's because loss of a transaction abort
1330  * is noncritical; the presumption would be that it aborted, anyway.
1331  *
1332  * It's safe to change the delayChkpt flag of our own backend without
1333  * holding the ProcArrayLock, since we're the only one modifying it.
1334  * This makes checkpoint's determination of which xacts are delayChkpt
1335  * a bit fuzzy, but it doesn't matter.
1336  */
1338  MyProc->delayChkpt = true;
1339 
1341 
1343  nchildren, children, nrels, rels,
1344  nmsgs, invalMessages,
1345  RelcacheInitFileInval,
1346  MyXactFlags,
1347  InvalidTransactionId, NULL /* plain commit */ );
1348 
1349  if (replorigin)
1350  /* Move LSNs forward for this replication origin */
1352  XactLastRecEnd);
1353 
1354  /*
1355  * Record commit timestamp. The value comes from plain commit
1356  * timestamp if there's no replication origin; otherwise, the
1357  * timestamp was already set in replorigin_session_origin_timestamp by
1358  * replication.
1359  *
1360  * We don't need to WAL-log anything here, as the commit record
1361  * written above already contains the data.
1362  */
1363 
1364  if (!replorigin || replorigin_session_origin_timestamp == 0)
1366 
1367  TransactionTreeSetCommitTsData(xid, nchildren, children,
1369  replorigin_session_origin, false);
1370  }
1371 
1372  /*
1373  * Check if we want to commit asynchronously. We can allow the XLOG flush
1374  * to happen asynchronously if synchronous_commit=off, or if the current
1375  * transaction has not performed any WAL-logged operation or didn't assign
1376  * an xid. The transaction can end up not writing any WAL, even if it has
1377  * an xid, if it only wrote to temporary and/or unlogged tables. It can
1378  * end up having written WAL without an xid if it did HOT pruning. In
1379  * case of a crash, the loss of such a transaction will be irrelevant;
1380  * temp tables will be lost anyway, unlogged tables will be truncated and
1381  * HOT pruning will be done again later. (Given the foregoing, you might
1382  * think that it would be unnecessary to emit the XLOG record at all in
1383  * this case, but we don't currently try to do that. It would certainly
1384  * cause problems at least in Hot Standby mode, where the
1385  * KnownAssignedXids machinery requires tracking every XID assignment. It
1386  * might be OK to skip it only when wal_level < replica, but for now we
1387  * don't.)
1388  *
1389  * However, if we're doing cleanup of any non-temp rels or committing any
1390  * command that wanted to force sync commit, then we must flush XLOG
1391  * immediately. (We must not allow asynchronous commit if there are any
1392  * non-temp tables to be deleted, because we might delete the files before
1393  * the COMMIT record is flushed to disk. We do allow asynchronous commit
1394  * if all to-be-deleted tables are temporary though, since they are lost
1395  * anyway if we crash.)
1396  */
1397  if ((wrote_xlog && markXidCommitted &&
1399  forceSyncCommit || nrels > 0)
1400  {
1402 
1403  /*
1404  * Now we may update the CLOG, if we wrote a COMMIT record above
1405  */
1406  if (markXidCommitted)
1407  TransactionIdCommitTree(xid, nchildren, children);
1408  }
1409  else
1410  {
1411  /*
1412  * Asynchronous commit case:
1413  *
1414  * This enables possible committed transaction loss in the case of a
1415  * postmaster crash because WAL buffers are left unwritten. Ideally we
1416  * could issue the WAL write without the fsync, but some
1417  * wal_sync_methods do not allow separate write/fsync.
1418  *
1419  * Report the latest async commit LSN, so that the WAL writer knows to
1420  * flush this commit.
1421  */
1423 
1424  /*
1425  * We must not immediately update the CLOG, since we didn't flush the
1426  * XLOG. Instead, we store the LSN up to which the XLOG must be
1427  * flushed before the CLOG may be updated.
1428  */
1429  if (markXidCommitted)
1430  TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1431  }
1432 
1433  /*
1434  * If we entered a commit critical section, leave it now, and let
1435  * checkpoints proceed.
1436  */
1437  if (markXidCommitted)
1438  {
1439  MyProc->delayChkpt = false;
1440  END_CRIT_SECTION();
1441  }
1442 
1443  /* Compute latestXid while we have the child XIDs handy */
1444  latestXid = TransactionIdLatest(xid, nchildren, children);
1445 
1446  /*
1447  * Wait for synchronous replication, if required. Similar to the decision
1448  * above about using committing asynchronously we only want to wait if
1449  * this backend assigned an xid and wrote WAL. No need to wait if an xid
1450  * was assigned due to temporary/unlogged tables or due to HOT pruning.
1451  *
1452  * Note that at this stage we have marked clog, but still show as running
1453  * in the procarray and continue to hold locks.
1454  */
1455  if (wrote_xlog && markXidCommitted)
1457 
1458  /* remember end of last commit record */
1460 
1461  /* Reset XactLastRecEnd until the next transaction writes something */
1462  XactLastRecEnd = 0;
1463 cleanup:
1464  /* Clean up local data */
1465  if (rels)
1466  pfree(rels);
1467 
1468  return latestXid;
1469 }
1470 
1471 
1472 /*
1473  * AtCCI_LocalCache
1474  */
1475 static void
1477 {
1478  /*
1479  * Make any pending relation map changes visible. We must do this before
1480  * processing local sinval messages, so that the map changes will get
1481  * reflected into the relcache when relcache invals are processed.
1482  */
1484 
1485  /*
1486  * Make catalog changes visible to me for the next command.
1487  */
1489 }
1490 
1491 /*
1492  * AtCommit_Memory
1493  */
1494 static void
1496 {
1497  /*
1498  * Now that we're "out" of a transaction, have the system allocate things
1499  * in the top memory context instead of per-transaction contexts.
1500  */
1502 
1503  /*
1504  * Release all transaction-local memory.
1505  */
1506  Assert(TopTransactionContext != NULL);
1508  TopTransactionContext = NULL;
1509  CurTransactionContext = NULL;
1510  CurrentTransactionState->curTransactionContext = NULL;
1511 }
1512 
1513 /* ----------------------------------------------------------------
1514  * CommitSubTransaction stuff
1515  * ----------------------------------------------------------------
1516  */
1517 
1518 /*
1519  * AtSubCommit_Memory
1520  */
1521 static void
1523 {
1525 
1526  Assert(s->parent != NULL);
1527 
1528  /* Return to parent transaction level's memory context. */
1531 
1532  /*
1533  * Ordinarily we cannot throw away the child's CurTransactionContext,
1534  * since the data it contains will be needed at upper commit. However, if
1535  * there isn't actually anything in it, we can throw it away. This avoids
1536  * a small memory leak in the common case of "trivial" subxacts.
1537  */
1539  {
1541  s->curTransactionContext = NULL;
1542  }
1543 }
1544 
1545 /*
1546  * AtSubCommit_childXids
1547  *
1548  * Pass my own XID and my child XIDs up to my parent as committed children.
1549  */
1550 static void
1552 {
1554  int new_nChildXids;
1555 
1556  Assert(s->parent != NULL);
1557 
1558  /*
1559  * The parent childXids array will need to hold my XID and all my
1560  * childXids, in addition to the XIDs already there.
1561  */
1562  new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1563 
1564  /* Allocate or enlarge the parent array if necessary */
1565  if (s->parent->maxChildXids < new_nChildXids)
1566  {
1567  int new_maxChildXids;
1568  TransactionId *new_childXids;
1569 
1570  /*
1571  * Make it 2x what's needed right now, to avoid having to enlarge it
1572  * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1573  * is what ensures that we don't need to worry about integer overflow
1574  * here or in the calculation of new_nChildXids.)
1575  */
1576  new_maxChildXids = Min(new_nChildXids * 2,
1577  (int) (MaxAllocSize / sizeof(TransactionId)));
1578 
1579  if (new_maxChildXids < new_nChildXids)
1580  ereport(ERROR,
1581  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1582  errmsg("maximum number of committed subtransactions (%d) exceeded",
1583  (int) (MaxAllocSize / sizeof(TransactionId)))));
1584 
1585  /*
1586  * We keep the child-XID arrays in TopTransactionContext; this avoids
1587  * setting up child-transaction contexts for what might be just a few
1588  * bytes of grandchild XIDs.
1589  */
1590  if (s->parent->childXids == NULL)
1591  new_childXids =
1593  new_maxChildXids * sizeof(TransactionId));
1594  else
1595  new_childXids = repalloc(s->parent->childXids,
1596  new_maxChildXids * sizeof(TransactionId));
1597 
1598  s->parent->childXids = new_childXids;
1599  s->parent->maxChildXids = new_maxChildXids;
1600  }
1601 
1602  /*
1603  * Copy all my XIDs to parent's array.
1604  *
1605  * Note: We rely on the fact that the XID of a child always follows that
1606  * of its parent. By copying the XID of this subtransaction before the
1607  * XIDs of its children, we ensure that the array stays ordered. Likewise,
1608  * all XIDs already in the array belong to subtransactions started and
1609  * subcommitted before us, so their XIDs must precede ours.
1610  */
1612 
1613  if (s->nChildXids > 0)
1614  memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1615  s->childXids,
1616  s->nChildXids * sizeof(TransactionId));
1617 
1618  s->parent->nChildXids = new_nChildXids;
1619 
1620  /* Release child's array to avoid leakage */
1621  if (s->childXids != NULL)
1622  pfree(s->childXids);
1623  /* We must reset these to avoid double-free if fail later in commit */
1624  s->childXids = NULL;
1625  s->nChildXids = 0;
1626  s->maxChildXids = 0;
1627 }
1628 
1629 /* ----------------------------------------------------------------
1630  * AbortTransaction stuff
1631  * ----------------------------------------------------------------
1632  */
1633 
1634 /*
1635  * RecordTransactionAbort
1636  *
1637  * Returns latest XID among xact and its children, or InvalidTransactionId
1638  * if the xact has no XID. (We compute that here just because it's easier.)
1639  */
1640 static TransactionId
1641 RecordTransactionAbort(bool isSubXact)
1642 {
1644  TransactionId latestXid;
1645  int nrels;
1646  RelFileNode *rels;
1647  int nchildren;
1648  TransactionId *children;
1649  TimestampTz xact_time;
1650 
1651  /*
1652  * If we haven't been assigned an XID, nobody will care whether we aborted
1653  * or not. Hence, we're done in that case. It does not matter if we have
1654  * rels to delete (note that this routine is not responsible for actually
1655  * deleting 'em). We cannot have any child XIDs, either.
1656  */
1657  if (!TransactionIdIsValid(xid))
1658  {
1659  /* Reset XactLastRecEnd until the next transaction writes something */
1660  if (!isSubXact)
1661  XactLastRecEnd = 0;
1662  return InvalidTransactionId;
1663  }
1664 
1665  /*
1666  * We have a valid XID, so we should write an ABORT record for it.
1667  *
1668  * We do not flush XLOG to disk here, since the default assumption after a
1669  * crash would be that we aborted, anyway. For the same reason, we don't
1670  * need to worry about interlocking against checkpoint start.
1671  */
1672 
1673  /*
1674  * Check that we haven't aborted halfway through RecordTransactionCommit.
1675  */
1676  if (TransactionIdDidCommit(xid))
1677  elog(PANIC, "cannot abort transaction %u, it was already committed",
1678  xid);
1679 
1680  /* Fetch the data we need for the abort record */
1681  nrels = smgrGetPendingDeletes(false, &rels);
1682  nchildren = xactGetCommittedChildren(&children);
1683 
1684  /* XXX do we really need a critical section here? */
1686 
1687  /* Write the ABORT record */
1688  if (isSubXact)
1689  xact_time = GetCurrentTimestamp();
1690  else
1691  {
1693  xact_time = xactStopTimestamp;
1694  }
1695 
1696  XactLogAbortRecord(xact_time,
1697  nchildren, children,
1698  nrels, rels,
1700  NULL);
1701 
1702  /*
1703  * Report the latest async abort LSN, so that the WAL writer knows to
1704  * flush this abort. There's nothing to be gained by delaying this, since
1705  * WALWriter may as well do this when it can. This is important with
1706  * streaming replication because if we don't flush WAL regularly we will
1707  * find that large aborts leave us with a long backlog for when commits
1708  * occur after the abort, increasing our window of data loss should
1709  * problems occur at that point.
1710  */
1711  if (!isSubXact)
1713 
1714  /*
1715  * Mark the transaction aborted in clog. This is not absolutely necessary
1716  * but we may as well do it while we are here; also, in the subxact case
1717  * it is helpful because XactLockTableWait makes use of it to avoid
1718  * waiting for already-aborted subtransactions. It is OK to do it without
1719  * having flushed the ABORT record to disk, because in event of a crash
1720  * we'd be assumed to have aborted anyway.
1721  */
1722  TransactionIdAbortTree(xid, nchildren, children);
1723 
1724  END_CRIT_SECTION();
1725 
1726  /* Compute latestXid while we have the child XIDs handy */
1727  latestXid = TransactionIdLatest(xid, nchildren, children);
1728 
1729  /*
1730  * If we're aborting a subtransaction, we can immediately remove failed
1731  * XIDs from PGPROC's cache of running child XIDs. We do that here for
1732  * subxacts, because we already have the child XID array at hand. For
1733  * main xacts, the equivalent happens just after this function returns.
1734  */
1735  if (isSubXact)
1736  XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1737 
1738  /* Reset XactLastRecEnd until the next transaction writes something */
1739  if (!isSubXact)
1740  XactLastRecEnd = 0;
1741 
1742  /* And clean up local data */
1743  if (rels)
1744  pfree(rels);
1745 
1746  return latestXid;
1747 }
1748 
1749 /*
1750  * AtAbort_Memory
1751  */
1752 static void
1754 {
1755  /*
1756  * Switch into TransactionAbortContext, which should have some free space
1757  * even if nothing else does. We'll work in this context until we've
1758  * finished cleaning up.
1759  *
1760  * It is barely possible to get here when we've not been able to create
1761  * TransactionAbortContext yet; if so use TopMemoryContext.
1762  */
1763  if (TransactionAbortContext != NULL)
1764  MemoryContextSwitchTo(TransactionAbortContext);
1765  else
1767 }
1768 
1769 /*
1770  * AtSubAbort_Memory
1771  */
1772 static void
1774 {
1775  Assert(TransactionAbortContext != NULL);
1776 
1777  MemoryContextSwitchTo(TransactionAbortContext);
1778 }
1779 
1780 
1781 /*
1782  * AtAbort_ResourceOwner
1783  */
1784 static void
1786 {
1787  /*
1788  * Make sure we have a valid ResourceOwner, if possible (else it will be
1789  * NULL, which is OK)
1790  */
1792 }
1793 
1794 /*
1795  * AtSubAbort_ResourceOwner
1796  */
1797 static void
1799 {
1801 
1802  /* Make sure we have a valid ResourceOwner */
1804 }
1805 
1806 
1807 /*
1808  * AtSubAbort_childXids
1809  */
1810 static void
1812 {
1814 
1815  /*
1816  * We keep the child-XID arrays in TopTransactionContext (see
1817  * AtSubCommit_childXids). This means we'd better free the array
1818  * explicitly at abort to avoid leakage.
1819  */
1820  if (s->childXids != NULL)
1821  pfree(s->childXids);
1822  s->childXids = NULL;
1823  s->nChildXids = 0;
1824  s->maxChildXids = 0;
1825 
1826  /*
1827  * We could prune the unreportedXids array here. But we don't bother. That
1828  * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
1829  * would likely introduce more CPU time into the more common paths, so we
1830  * choose not to do that.
1831  */
1832 }
1833 
1834 /* ----------------------------------------------------------------
1835  * CleanupTransaction stuff
1836  * ----------------------------------------------------------------
1837  */
1838 
1839 /*
1840  * AtCleanup_Memory
1841  */
1842 static void
1844 {
1845  Assert(CurrentTransactionState->parent == NULL);
1846 
1847  /*
1848  * Now that we're "out" of a transaction, have the system allocate things
1849  * in the top memory context instead of per-transaction contexts.
1850  */
1852 
1853  /*
1854  * Clear the special abort context for next time.
1855  */
1856  if (TransactionAbortContext != NULL)
1857  MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1858 
1859  /*
1860  * Release all transaction-local memory.
1861  */
1862  if (TopTransactionContext != NULL)
1864  TopTransactionContext = NULL;
1865  CurTransactionContext = NULL;
1866  CurrentTransactionState->curTransactionContext = NULL;
1867 }
1868 
1869 
1870 /* ----------------------------------------------------------------
1871  * CleanupSubTransaction stuff
1872  * ----------------------------------------------------------------
1873  */
1874 
1875 /*
1876  * AtSubCleanup_Memory
1877  */
1878 static void
1880 {
1882 
1883  Assert(s->parent != NULL);
1884 
1885  /* Make sure we're not in an about-to-be-deleted context */
1888 
1889  /*
1890  * Clear the special abort context for next time.
1891  */
1892  if (TransactionAbortContext != NULL)
1893  MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1894 
1895  /*
1896  * Delete the subxact local memory contexts. Its CurTransactionContext can
1897  * go too (note this also kills CurTransactionContexts from any children
1898  * of the subxact).
1899  */
1900  if (s->curTransactionContext)
1902  s->curTransactionContext = NULL;
1903 }
1904 
1905 /* ----------------------------------------------------------------
1906  * interface routines
1907  * ----------------------------------------------------------------
1908  */
1909 
1910 /*
1911  * StartTransaction
1912  */
1913 static void
1915 {
1916  TransactionState s;
1917  VirtualTransactionId vxid;
1918 
1919  /*
1920  * Let's just make sure the state stack is empty
1921  */
1923  CurrentTransactionState = s;
1924 
1925  Assert(!FullTransactionIdIsValid(XactTopFullTransactionId));
1926 
1927  /* check the current transaction state */
1928  Assert(s->state == TRANS_DEFAULT);
1929 
1930  /*
1931  * Set the current transaction state information appropriately during
1932  * start processing. Note that once the transaction status is switched
1933  * this process cannot fail until the user ID and the security context
1934  * flags are fetched below.
1935  */
1936  s->state = TRANS_START;
1937  s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
1938 
1939  /* Determine if statements are logged in this transaction */
1941  (log_xact_sample_rate == 1 ||
1943 
1944  /*
1945  * initialize current transaction state fields
1946  *
1947  * note: prevXactReadOnly is not used at the outermost level
1948  */
1949  s->nestingLevel = 1;
1950  s->gucNestLevel = 1;
1951  s->childXids = NULL;
1952  s->nChildXids = 0;
1953  s->maxChildXids = 0;
1954 
1955  /*
1956  * Once the current user ID and the security context flags are fetched,
1957  * both will be properly reset even if transaction startup fails.
1958  */
1960 
1961  /* SecurityRestrictionContext should never be set outside a transaction */
1962  Assert(s->prevSecContext == 0);
1963 
1964  /*
1965  * Make sure we've reset xact state variables
1966  *
1967  * If recovery is still in progress, mark this transaction as read-only.
1968  * We have lower level defences in XLogInsert and elsewhere to stop us
1969  * from modifying data during recovery, but this gives the normal
1970  * indication to the user that the transaction is read-only.
1971  */
1972  if (RecoveryInProgress())
1973  {
1974  s->startedInRecovery = true;
1975  XactReadOnly = true;
1976  }
1977  else
1978  {
1979  s->startedInRecovery = false;
1981  }
1984  forceSyncCommit = false;
1985  MyXactFlags = 0;
1986 
1987  /*
1988  * reinitialize within-transaction counters
1989  */
1993  currentCommandIdUsed = false;
1994 
1995  /*
1996  * initialize reported xid accounting
1997  */
1998  nUnreportedXids = 0;
1999  s->didLogXid = false;
2000 
2001  /*
2002  * must initialize resource-management stuff first
2003  */
2004  AtStart_Memory();
2006 
2007  /*
2008  * Assign a new LocalTransactionId, and combine it with the backendId to
2009  * form a virtual transaction id.
2010  */
2011  vxid.backendId = MyBackendId;
2013 
2014  /*
2015  * Lock the virtual transaction id before we announce it in the proc array
2016  */
2018 
2019  /*
2020  * Advertise it in the proc array. We assume assignment of
2021  * localTransactionId is atomic, and the backendId should be set already.
2022  */
2023  Assert(MyProc->backendId == vxid.backendId);
2024  MyProc->lxid = vxid.localTransactionId;
2025 
2026  TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
2027 
2028  /*
2029  * set transaction_timestamp() (a/k/a now()). Normally, we want this to
2030  * be the same as the first command's statement_timestamp(), so don't do a
2031  * fresh GetCurrentTimestamp() call (which'd be expensive anyway). But
2032  * for transactions started inside procedures (i.e., nonatomic SPI
2033  * contexts), we do need to advance the timestamp. Also, in a parallel
2034  * worker, the timestamp should already have been provided by a call to
2035  * SetParallelStartTimestamps().
2036  */
2037  if (!IsParallelWorker())
2038  {
2041  else
2043  }
2044  else
2045  Assert(xactStartTimestamp != 0);
2047  /* Mark xactStopTimestamp as unset. */
2048  xactStopTimestamp = 0;
2049 
2050  /*
2051  * initialize other subsystems for new transaction
2052  */
2053  AtStart_GUC();
2054  AtStart_Cache();
2056 
2057  /*
2058  * done with start processing, set current transaction state to "in
2059  * progress"
2060  */
2061  s->state = TRANS_INPROGRESS;
2062 
2063  ShowTransactionState("StartTransaction");
2064 }
2065 
2066 
2067 /*
2068  * CommitTransaction
2069  *
2070  * NB: if you change this routine, better look at PrepareTransaction too!
2071  */
2072 static void
2074 {
2076  TransactionId latestXid;
2077  bool is_parallel_worker;
2078 
2079  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2080 
2081  /* Enforce parallel mode restrictions during parallel worker commit. */
2082  if (is_parallel_worker)
2084 
2085  ShowTransactionState("CommitTransaction");
2086 
2087  /*
2088  * check the current transaction state
2089  */
2090  if (s->state != TRANS_INPROGRESS)
2091  elog(WARNING, "CommitTransaction while in %s state",
2093  Assert(s->parent == NULL);
2094 
2095  /*
2096  * Do pre-commit processing that involves calling user-defined code, such
2097  * as triggers. Since closing cursors could queue trigger actions,
2098  * triggers could open cursors, etc, we have to keep looping until there's
2099  * nothing left to do.
2100  */
2101  for (;;)
2102  {
2103  /*
2104  * Fire all currently pending deferred triggers.
2105  */
2107 
2108  /*
2109  * Close open portals (converting holdable ones into static portals).
2110  * If there weren't any, we are done ... otherwise loop back to check
2111  * if they queued deferred triggers. Lather, rinse, repeat.
2112  */
2113  if (!PreCommit_Portals(false))
2114  break;
2115  }
2116 
2119 
2120  /*
2121  * The remaining actions cannot call any user-defined code, so it's safe
2122  * to start shutting down within-transaction services. But note that most
2123  * of this stuff could still throw an error, which would switch us into
2124  * the transaction-abort path.
2125  */
2126 
2127  /* If we might have parallel workers, clean them up now. */
2128  if (IsInParallelMode())
2129  AtEOXact_Parallel(true);
2130 
2131  /* Shut down the deferred-trigger manager */
2132  AfterTriggerEndXact(true);
2133 
2134  /*
2135  * Let ON COMMIT management do its thing (must happen after closing
2136  * cursors, to avoid dangling-reference problems)
2137  */
2139 
2140  /*
2141  * Synchronize files that are created and not WAL-logged during this
2142  * transaction. This must happen before AtEOXact_RelationMap(), so that we
2143  * don't see committed-but-broken files after a crash.
2144  */
2145  smgrDoPendingSyncs(true, is_parallel_worker);
2146 
2147  /* close large objects before lower-level cleanup */
2148  AtEOXact_LargeObject(true);
2149 
2150  /*
2151  * Insert notifications sent by NOTIFY commands into the queue. This
2152  * should be late in the pre-commit sequence to minimize time spent
2153  * holding the notify-insertion lock. However, this could result in
2154  * creating a snapshot, so we must do it before serializable cleanup.
2155  */
2156  PreCommit_Notify();
2157 
2158  /*
2159  * Mark serializable transaction as complete for predicate locking
2160  * purposes. This should be done as late as we can put it and still allow
2161  * errors to be raised for failure patterns found at commit. This is not
2162  * appropriate in a parallel worker however, because we aren't committing
2163  * the leader's transaction and its serializable state will live on.
2164  */
2165  if (!is_parallel_worker)
2167 
2168  /* Prevent cancel/die interrupt while cleaning up */
2169  HOLD_INTERRUPTS();
2170 
2171  /* Commit updates to the relation map --- do this as late as possible */
2172  AtEOXact_RelationMap(true, is_parallel_worker);
2173 
2174  /*
2175  * set the current transaction state information appropriately during
2176  * commit processing
2177  */
2178  s->state = TRANS_COMMIT;
2179  s->parallelModeLevel = 0;
2180 
2181  if (!is_parallel_worker)
2182  {
2183  /*
2184  * We need to mark our XIDs as committed in pg_xact. This is where we
2185  * durably commit.
2186  */
2187  latestXid = RecordTransactionCommit();
2188  }
2189  else
2190  {
2191  /*
2192  * We must not mark our XID committed; the parallel leader is
2193  * responsible for that.
2194  */
2195  latestXid = InvalidTransactionId;
2196 
2197  /*
2198  * Make sure the leader will know about any WAL we wrote before it
2199  * commits.
2200  */
2202  }
2203 
2204  TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->lxid);
2205 
2206  /*
2207  * Let others know about no transaction in progress by me. Note that this
2208  * must be done _before_ releasing locks we hold and _after_
2209  * RecordTransactionCommit.
2210  */
2211  ProcArrayEndTransaction(MyProc, latestXid);
2212 
2213  /*
2214  * This is all post-commit cleanup. Note that if an error is raised here,
2215  * it's too late to abort the transaction. This should be just
2216  * noncritical resource releasing.
2217  *
2218  * The ordering of operations is not entirely random. The idea is:
2219  * release resources visible to other backends (eg, files, buffer pins);
2220  * then release locks; then release backend-local resources. We want to
2221  * release locks at the point where any backend waiting for us will see
2222  * our transaction as being fully cleaned up.
2223  *
2224  * Resources that can be associated with individual queries are handled by
2225  * the ResourceOwner mechanism. The other calls here are for backend-wide
2226  * state.
2227  */
2228 
2229  CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2230  : XACT_EVENT_COMMIT);
2231 
2234  true, true);
2235 
2236  /* Check we've released all buffer pins */
2237  AtEOXact_Buffers(true);
2238 
2239  /* Clean up the relation cache */
2240  AtEOXact_RelationCache(true);
2241 
2242  /*
2243  * Make catalog changes visible to all backends. This has to happen after
2244  * relcache references are dropped (see comments for
2245  * AtEOXact_RelationCache), but before locks are released (if anyone is
2246  * waiting for lock on a relation we've modified, we want them to know
2247  * about the catalog change before they start using the relation).
2248  */
2249  AtEOXact_Inval(true);
2250 
2252 
2255  true, true);
2258  true, true);
2259 
2260  /*
2261  * Likewise, dropping of files deleted during the transaction is best done
2262  * after releasing relcache and buffer pins. (This is not strictly
2263  * necessary during commit, since such pins should have been released
2264  * already, but this ordering is definitely critical during abort.) Since
2265  * this may take many seconds, also delay until after releasing locks.
2266  * Other backends will observe the attendant catalog changes and not
2267  * attempt to access affected files.
2268  */
2269  smgrDoPendingDeletes(true);
2270 
2271  AtCommit_Notify();
2272  AtEOXact_GUC(true, 1);
2273  AtEOXact_SPI(true);
2274  AtEOXact_Enum();
2276  AtEOXact_Namespace(true, is_parallel_worker);
2277  AtEOXact_SMgr();
2278  AtEOXact_Files(true);
2280  AtEOXact_HashTables(true);
2281  AtEOXact_PgStat(true, is_parallel_worker);
2282  AtEOXact_Snapshot(true, false);
2283  AtEOXact_ApplyLauncher(true);
2285 
2286  CurrentResourceOwner = NULL;
2288  s->curTransactionOwner = NULL;
2291 
2292  AtCommit_Memory();
2293 
2296  s->nestingLevel = 0;
2297  s->gucNestLevel = 0;
2298  s->childXids = NULL;
2299  s->nChildXids = 0;
2300  s->maxChildXids = 0;
2301 
2302  XactTopFullTransactionId = InvalidFullTransactionId;
2304 
2305  /*
2306  * done with commit processing, set current transaction state back to
2307  * default
2308  */
2309  s->state = TRANS_DEFAULT;
2310 
2312 }
2313 
2314 
2315 /*
2316  * PrepareTransaction
2317  *
2318  * NB: if you change this routine, better look at CommitTransaction too!
2319  */
2320 static void
2322 {
2325  GlobalTransaction gxact;
2326  TimestampTz prepared_at;
2327 
2329 
2330  ShowTransactionState("PrepareTransaction");
2331 
2332  /*
2333  * check the current transaction state
2334  */
2335  if (s->state != TRANS_INPROGRESS)
2336  elog(WARNING, "PrepareTransaction while in %s state",
2338  Assert(s->parent == NULL);
2339 
2340  /*
2341  * Do pre-commit processing that involves calling user-defined code, such
2342  * as triggers. Since closing cursors could queue trigger actions,
2343  * triggers could open cursors, etc, we have to keep looping until there's
2344  * nothing left to do.
2345  */
2346  for (;;)
2347  {
2348  /*
2349  * Fire all currently pending deferred triggers.
2350  */
2352 
2353  /*
2354  * Close open portals (converting holdable ones into static portals).
2355  * If there weren't any, we are done ... otherwise loop back to check
2356  * if they queued deferred triggers. Lather, rinse, repeat.
2357  */
2358  if (!PreCommit_Portals(true))
2359  break;
2360  }
2361 
2363 
2364  /*
2365  * The remaining actions cannot call any user-defined code, so it's safe
2366  * to start shutting down within-transaction services. But note that most
2367  * of this stuff could still throw an error, which would switch us into
2368  * the transaction-abort path.
2369  */
2370 
2371  /* Shut down the deferred-trigger manager */
2372  AfterTriggerEndXact(true);
2373 
2374  /*
2375  * Let ON COMMIT management do its thing (must happen after closing
2376  * cursors, to avoid dangling-reference problems)
2377  */
2379 
2380  /*
2381  * Synchronize files that are created and not WAL-logged during this
2382  * transaction. This must happen before EndPrepare(), so that we don't see
2383  * committed-but-broken files after a crash and COMMIT PREPARED.
2384  */
2385  smgrDoPendingSyncs(true, false);
2386 
2387  /* close large objects before lower-level cleanup */
2388  AtEOXact_LargeObject(true);
2389 
2390  /* NOTIFY requires no work at this point */
2391 
2392  /*
2393  * Mark serializable transaction as complete for predicate locking
2394  * purposes. This should be done as late as we can put it and still allow
2395  * errors to be raised for failure patterns found at commit.
2396  */
2398 
2399  /*
2400  * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2401  * this transaction. Having the prepared xact hold locks on another
2402  * backend's temp table seems a bad idea --- for instance it would prevent
2403  * the backend from exiting. There are other problems too, such as how to
2404  * clean up the source backend's local buffers and ON COMMIT state if the
2405  * prepared xact includes a DROP of a temp table.
2406  *
2407  * Other objects types, like functions, operators or extensions, share the
2408  * same restriction as they should not be created, locked or dropped as
2409  * this can mess up with this session or even a follow-up session trying
2410  * to use the same temporary namespace.
2411  *
2412  * We must check this after executing any ON COMMIT actions, because they
2413  * might still access a temp relation.
2414  *
2415  * XXX In principle this could be relaxed to allow some useful special
2416  * cases, such as a temp table created and dropped all within the
2417  * transaction. That seems to require much more bookkeeping though.
2418  */
2420  ereport(ERROR,
2421  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2422  errmsg("cannot PREPARE a transaction that has operated on temporary objects")));
2423 
2424  /*
2425  * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2426  * supported if we added cleanup logic to twophase.c, but for now it
2427  * doesn't seem worth the trouble.
2428  */
2430  ereport(ERROR,
2431  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2432  errmsg("cannot PREPARE a transaction that has exported snapshots")));
2433 
2434  /*
2435  * Don't allow PREPARE but for transaction that has/might kill logical
2436  * replication workers.
2437  */
2439  ereport(ERROR,
2440  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2441  errmsg("cannot PREPARE a transaction that has manipulated logical replication workers")));
2442 
2443  /* Prevent cancel/die interrupt while cleaning up */
2444  HOLD_INTERRUPTS();
2445 
2446  /*
2447  * set the current transaction state information appropriately during
2448  * prepare processing
2449  */
2450  s->state = TRANS_PREPARE;
2451 
2452  prepared_at = GetCurrentTimestamp();
2453 
2454  /* Tell bufmgr and smgr to prepare for commit */
2455  BufmgrCommit();
2456 
2457  /*
2458  * Reserve the GID for this transaction. This could fail if the requested
2459  * GID is invalid or already in use.
2460  */
2461  gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2462  GetUserId(), MyDatabaseId);
2463  prepareGID = NULL;
2464 
2465  /*
2466  * Collect data for the 2PC state file. Note that in general, no actual
2467  * state change should happen in the called modules during this step,
2468  * since it's still possible to fail before commit, and in that case we
2469  * want transaction abort to be able to clean up. (In particular, the
2470  * AtPrepare routines may error out if they find cases they cannot
2471  * handle.) State cleanup should happen in the PostPrepare routines
2472  * below. However, some modules can go ahead and clear state here because
2473  * they wouldn't do anything with it during abort anyway.
2474  *
2475  * Note: because the 2PC state file records will be replayed in the same
2476  * order they are made, the order of these calls has to match the order in
2477  * which we want things to happen during COMMIT PREPARED or ROLLBACK
2478  * PREPARED; in particular, pay attention to whether things should happen
2479  * before or after releasing the transaction's locks.
2480  */
2481  StartPrepare(gxact);
2482 
2483  AtPrepare_Notify();
2484  AtPrepare_Locks();
2486  AtPrepare_PgStat();
2489 
2490  /*
2491  * Here is where we really truly prepare.
2492  *
2493  * We have to record transaction prepares even if we didn't make any
2494  * updates, because the transaction manager might get confused if we lose
2495  * a global transaction.
2496  */
2497  EndPrepare(gxact);
2498 
2499  /*
2500  * Now we clean up backend-internal state and release internal resources.
2501  */
2502 
2503  /* Reset XactLastRecEnd until the next transaction writes something */
2504  XactLastRecEnd = 0;
2505 
2506  /*
2507  * Let others know about no transaction in progress by me. This has to be
2508  * done *after* the prepared transaction has been marked valid, else
2509  * someone may think it is unlocked and recyclable.
2510  */
2512 
2513  /*
2514  * In normal commit-processing, this is all non-critical post-transaction
2515  * cleanup. When the transaction is prepared, however, it's important
2516  * that the locks and other per-backend resources are transferred to the
2517  * prepared transaction's PGPROC entry. Note that if an error is raised
2518  * here, it's too late to abort the transaction. XXX: This probably should
2519  * be in a critical section, to force a PANIC if any of this fails, but
2520  * that cure could be worse than the disease.
2521  */
2522 
2524 
2527  true, true);
2528 
2529  /* Check we've released all buffer pins */
2530  AtEOXact_Buffers(true);
2531 
2532  /* Clean up the relation cache */
2533  AtEOXact_RelationCache(true);
2534 
2535  /* notify doesn't need a postprepare call */
2536 
2538 
2540 
2541  PostPrepare_smgr();
2542 
2543  PostPrepare_MultiXact(xid);
2544 
2545  PostPrepare_Locks(xid);
2547 
2550  true, true);
2553  true, true);
2554 
2555  /*
2556  * Allow another backend to finish the transaction. After
2557  * PostPrepare_Twophase(), the transaction is completely detached from our
2558  * backend. The rest is just non-critical cleanup of backend-local state.
2559  */
2561 
2562  /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2563  AtEOXact_GUC(true, 1);
2564  AtEOXact_SPI(true);
2565  AtEOXact_Enum();
2567  AtEOXact_Namespace(true, false);
2568  AtEOXact_SMgr();
2569  AtEOXact_Files(true);
2571  AtEOXact_HashTables(true);
2572  /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2573  AtEOXact_Snapshot(true, true);
2575 
2576  CurrentResourceOwner = NULL;
2578  s->curTransactionOwner = NULL;
2581 
2582  AtCommit_Memory();
2583 
2586  s->nestingLevel = 0;
2587  s->gucNestLevel = 0;
2588  s->childXids = NULL;
2589  s->nChildXids = 0;
2590  s->maxChildXids = 0;
2591 
2592  XactTopFullTransactionId = InvalidFullTransactionId;
2594 
2595  /*
2596  * done with 1st phase commit processing, set current transaction state
2597  * back to default
2598  */
2599  s->state = TRANS_DEFAULT;
2600 
2602 }
2603 
2604 
2605 /*
2606  * AbortTransaction
2607  */
2608 static void
2610 {
2612  TransactionId latestXid;
2613  bool is_parallel_worker;
2614 
2615  /* Prevent cancel/die interrupt while cleaning up */
2616  HOLD_INTERRUPTS();
2617 
2618  /* Make sure we have a valid memory context and resource owner */
2619  AtAbort_Memory();
2621 
2622  /*
2623  * Release any LW locks we might be holding as quickly as possible.
2624  * (Regular locks, however, must be held till we finish aborting.)
2625  * Releasing LW locks is critical since we might try to grab them again
2626  * while cleaning up!
2627  */
2628  LWLockReleaseAll();
2629 
2630  /* Clear wait information and command progress indicator */
2633 
2634  /* Clean up buffer I/O and buffer context locks, too */
2635  AbortBufferIO();
2636  UnlockBuffers();
2637 
2638  /* Reset WAL record construction state */
2640 
2641  /* Cancel condition variable sleep */
2643 
2644  /*
2645  * Also clean up any open wait for lock, since the lock manager will choke
2646  * if we try to wait for another lock before doing this.
2647  */
2648  LockErrorCleanup();
2649 
2650  /*
2651  * If any timeout events are still active, make sure the timeout interrupt
2652  * is scheduled. This covers possible loss of a timeout interrupt due to
2653  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2654  * We delay this till after LockErrorCleanup so that we don't uselessly
2655  * reschedule lock or deadlock check timeouts.
2656  */
2658 
2659  /*
2660  * Re-enable signals, in case we got here by longjmp'ing out of a signal
2661  * handler. We do this fairly early in the sequence so that the timeout
2662  * infrastructure will be functional if needed while aborting.
2663  */
2665 
2666  /*
2667  * check the current transaction state
2668  */
2669  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2670  if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2671  elog(WARNING, "AbortTransaction while in %s state",
2673  Assert(s->parent == NULL);
2674 
2675  /*
2676  * set the current transaction state information appropriately during the
2677  * abort processing
2678  */
2679  s->state = TRANS_ABORT;
2680 
2681  /*
2682  * Reset user ID which might have been changed transiently. We need this
2683  * to clean up in case control escaped out of a SECURITY DEFINER function
2684  * or other local change of CurrentUserId; therefore, the prior value of
2685  * SecurityRestrictionContext also needs to be restored.
2686  *
2687  * (Note: it is not necessary to restore session authorization or role
2688  * settings here because those can only be changed via GUC, and GUC will
2689  * take care of rolling them back if need be.)
2690  */
2692 
2693  /* Forget about any active REINDEX. */
2695 
2696  /* Reset logical streaming state. */
2698 
2699  /* If in parallel mode, clean up workers and exit parallel mode. */
2700  if (IsInParallelMode())
2701  {
2702  AtEOXact_Parallel(false);
2703  s->parallelModeLevel = 0;
2704  }
2705 
2706  /*
2707  * do abort processing
2708  */
2709  AfterTriggerEndXact(false); /* 'false' means it's abort */
2710  AtAbort_Portals();
2711  smgrDoPendingSyncs(false, is_parallel_worker);
2712  AtEOXact_LargeObject(false);
2713  AtAbort_Notify();
2714  AtEOXact_RelationMap(false, is_parallel_worker);
2715  AtAbort_Twophase();
2716 
2717  /*
2718  * Advertise the fact that we aborted in pg_xact (assuming that we got as
2719  * far as assigning an XID to advertise). But if we're inside a parallel
2720  * worker, skip this; the user backend must be the one to write the abort
2721  * record.
2722  */
2723  if (!is_parallel_worker)
2724  latestXid = RecordTransactionAbort(false);
2725  else
2726  {
2727  latestXid = InvalidTransactionId;
2728 
2729  /*
2730  * Since the parallel leader won't get our value of XactLastRecEnd in
2731  * this case, we nudge WAL-writer ourselves in this case. See related
2732  * comments in RecordTransactionAbort for why this matters.
2733  */
2735  }
2736 
2737  TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->lxid);
2738 
2739  /*
2740  * Let others know about no transaction in progress by me. Note that this
2741  * must be done _before_ releasing locks we hold and _after_
2742  * RecordTransactionAbort.
2743  */
2744  ProcArrayEndTransaction(MyProc, latestXid);
2745 
2746  /*
2747  * Post-abort cleanup. See notes in CommitTransaction() concerning
2748  * ordering. We can skip all of it if the transaction failed before
2749  * creating a resource owner.
2750  */
2751  if (TopTransactionResourceOwner != NULL)
2752  {
2753  if (is_parallel_worker)
2755  else
2757 
2760  false, true);
2761  AtEOXact_Buffers(false);
2762  AtEOXact_RelationCache(false);
2763  AtEOXact_Inval(false);
2767  false, true);
2770  false, true);
2771  smgrDoPendingDeletes(false);
2772 
2773  AtEOXact_GUC(false, 1);
2774  AtEOXact_SPI(false);
2775  AtEOXact_Enum();
2777  AtEOXact_Namespace(false, is_parallel_worker);
2778  AtEOXact_SMgr();
2779  AtEOXact_Files(false);
2781  AtEOXact_HashTables(false);
2782  AtEOXact_PgStat(false, is_parallel_worker);
2783  AtEOXact_ApplyLauncher(false);
2785  }
2786 
2787  /*
2788  * State remains TRANS_ABORT until CleanupTransaction().
2789  */
2791 }
2792 
2793 /*
2794  * CleanupTransaction
2795  */
2796 static void
2798 {
2800 
2801  /*
2802  * State should still be TRANS_ABORT from AbortTransaction().
2803  */
2804  if (s->state != TRANS_ABORT)
2805  elog(FATAL, "CleanupTransaction: unexpected state %s",
2807 
2808  /*
2809  * do abort cleanup processing
2810  */
2811  AtCleanup_Portals(); /* now safe to release portal memory */
2812  AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
2813 
2814  CurrentResourceOwner = NULL; /* and resource owner */
2817  s->curTransactionOwner = NULL;
2820 
2821  AtCleanup_Memory(); /* and transaction memory */
2822 
2825  s->nestingLevel = 0;
2826  s->gucNestLevel = 0;
2827  s->childXids = NULL;
2828  s->nChildXids = 0;
2829  s->maxChildXids = 0;
2830  s->parallelModeLevel = 0;
2831 
2832  XactTopFullTransactionId = InvalidFullTransactionId;
2834 
2835  /*
2836  * done with abort processing, set current transaction state back to
2837  * default
2838  */
2839  s->state = TRANS_DEFAULT;
2840 }
2841 
2842 /*
2843  * StartTransactionCommand
2844  */
2845 void
2847 {
2849 
2850  switch (s->blockState)
2851  {
2852  /*
2853  * if we aren't in a transaction block, we just do our usual start
2854  * transaction.
2855  */
2856  case TBLOCK_DEFAULT:
2857  StartTransaction();
2859  break;
2860 
2861  /*
2862  * We are somewhere in a transaction block or subtransaction and
2863  * about to start a new command. For now we do nothing, but
2864  * someday we may do command-local resource initialization. (Note
2865  * that any needed CommandCounterIncrement was done by the
2866  * previous CommitTransactionCommand.)
2867  */
2868  case TBLOCK_INPROGRESS:
2870  case TBLOCK_SUBINPROGRESS:
2871  break;
2872 
2873  /*
2874  * Here we are in a failed transaction block (one of the commands
2875  * caused an abort) so we do nothing but remain in the abort
2876  * state. Eventually we will get a ROLLBACK command which will
2877  * get us out of this state. (It is up to other code to ensure
2878  * that no commands other than ROLLBACK will be processed in these
2879  * states.)
2880  */
2881  case TBLOCK_ABORT:
2882  case TBLOCK_SUBABORT:
2883  break;
2884 
2885  /* These cases are invalid. */
2886  case TBLOCK_STARTED:
2887  case TBLOCK_BEGIN:
2889  case TBLOCK_SUBBEGIN:
2890  case TBLOCK_END:
2891  case TBLOCK_SUBRELEASE:
2892  case TBLOCK_SUBCOMMIT:
2893  case TBLOCK_ABORT_END:
2894  case TBLOCK_SUBABORT_END:
2895  case TBLOCK_ABORT_PENDING:
2897  case TBLOCK_SUBRESTART:
2899  case TBLOCK_PREPARE:
2900  elog(ERROR, "StartTransactionCommand: unexpected state %s",
2902  break;
2903  }
2904 
2905  /*
2906  * We must switch to CurTransactionContext before returning. This is
2907  * already done if we called StartTransaction, otherwise not.
2908  */
2909  Assert(CurTransactionContext != NULL);
2911 }
2912 
2913 
2914 /*
2915  * Simple system for saving and restoring transaction characteristics
2916  * (isolation level, read only, deferrable). We need this for transaction
2917  * chaining, so that we can set the characteristics of the new transaction to
2918  * be the same as the previous one. (We need something like this because the
2919  * GUC system resets the characteristics at transaction end, so for example
2920  * just skipping the reset in StartTransaction() won't work.)
2921  */
2923 static bool save_XactReadOnly;
2925 
2926 void
2928 {
2932 }
2933 
2934 void
2936 {
2940 }
2941 
2942 
2943 /*
2944  * CommitTransactionCommand
2945  */
2946 void
2948 {
2950 
2951  if (s->chain)
2953 
2954  switch (s->blockState)
2955  {
2956  /*
2957  * These shouldn't happen. TBLOCK_DEFAULT means the previous
2958  * StartTransactionCommand didn't set the STARTED state
2959  * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
2960  * by EndParallelWorkerTransaction(), not this function.
2961  */
2962  case TBLOCK_DEFAULT:
2964  elog(FATAL, "CommitTransactionCommand: unexpected state %s",
2966  break;
2967 
2968  /*
2969  * If we aren't in a transaction block, just do our usual
2970  * transaction commit, and return to the idle state.
2971  */
2972  case TBLOCK_STARTED:
2975  break;
2976 
2977  /*
2978  * We are completing a "BEGIN TRANSACTION" command, so we change
2979  * to the "transaction block in progress" state and return. (We
2980  * assume the BEGIN did nothing to the database, so we need no
2981  * CommandCounterIncrement.)
2982  */
2983  case TBLOCK_BEGIN:
2985  break;
2986 
2987  /*
2988  * This is the case when we have finished executing a command
2989  * someplace within a transaction block. We increment the command
2990  * counter and return.
2991  */
2992  case TBLOCK_INPROGRESS:
2994  case TBLOCK_SUBINPROGRESS:
2996  break;
2997 
2998  /*
2999  * We are completing a "COMMIT" command. Do it and return to the
3000  * idle state.
3001  */
3002  case TBLOCK_END:
3005  if (s->chain)
3006  {
3007  StartTransaction();
3009  s->chain = false;
3011  }
3012  break;
3013 
3014  /*
3015  * Here we are in the middle of a transaction block but one of the
3016  * commands caused an abort so we do nothing but remain in the
3017  * abort state. Eventually we will get a ROLLBACK command.
3018  */
3019  case TBLOCK_ABORT:
3020  case TBLOCK_SUBABORT:
3021  break;
3022 
3023  /*
3024  * Here we were in an aborted transaction block and we just got
3025  * the ROLLBACK command from the user, so clean up the
3026  * already-aborted transaction and return to the idle state.
3027  */
3028  case TBLOCK_ABORT_END:
3031  if (s->chain)
3032  {
3033  StartTransaction();
3035  s->chain = false;
3037  }
3038  break;
3039 
3040  /*
3041  * Here we were in a perfectly good transaction block but the user
3042  * told us to ROLLBACK anyway. We have to abort the transaction
3043  * and then clean up.
3044  */
3045  case TBLOCK_ABORT_PENDING:
3046  AbortTransaction();
3049  if (s->chain)
3050  {
3051  StartTransaction();
3053  s->chain = false;
3055  }
3056  break;
3057 
3058  /*
3059  * We are completing a "PREPARE TRANSACTION" command. Do it and
3060  * return to the idle state.
3061  */
3062  case TBLOCK_PREPARE:
3065  break;
3066 
3067  /*
3068  * We were just issued a SAVEPOINT inside a transaction block.
3069  * Start a subtransaction. (DefineSavepoint already did
3070  * PushTransaction, so as to have someplace to put the SUBBEGIN
3071  * state.)
3072  */
3073  case TBLOCK_SUBBEGIN:
3076  break;
3077 
3078  /*
3079  * We were issued a RELEASE command, so we end the current
3080  * subtransaction and return to the parent transaction. The parent
3081  * might be ended too, so repeat till we find an INPROGRESS
3082  * transaction or subtransaction.
3083  */
3084  case TBLOCK_SUBRELEASE:
3085  do
3086  {
3088  s = CurrentTransactionState; /* changed by pop */
3089  } while (s->blockState == TBLOCK_SUBRELEASE);
3090 
3093  break;
3094 
3095  /*
3096  * We were issued a COMMIT, so we end the current subtransaction
3097  * hierarchy and perform final commit. We do this by rolling up
3098  * any subtransactions into their parent, which leads to O(N^2)
3099  * operations with respect to resource owners - this isn't that
3100  * bad until we approach a thousands of savepoints but is
3101  * necessary for correctness should after triggers create new
3102  * resource owners.
3103  */
3104  case TBLOCK_SUBCOMMIT:
3105  do
3106  {
3108  s = CurrentTransactionState; /* changed by pop */
3109  } while (s->blockState == TBLOCK_SUBCOMMIT);
3110  /* If we had a COMMIT command, finish off the main xact too */
3111  if (s->blockState == TBLOCK_END)
3112  {
3113  Assert(s->parent == NULL);
3116  }
3117  else if (s->blockState == TBLOCK_PREPARE)
3118  {
3119  Assert(s->parent == NULL);
3122  }
3123  else
3124  elog(ERROR, "CommitTransactionCommand: unexpected state %s",
3126  break;
3127 
3128  /*
3129  * The current already-failed subtransaction is ending due to a
3130  * ROLLBACK or ROLLBACK TO command, so pop it and recursively
3131  * examine the parent (which could be in any of several states).
3132  */
3133  case TBLOCK_SUBABORT_END:
3136  break;
3137 
3138  /*
3139  * As above, but it's not dead yet, so abort first.
3140  */
3145  break;
3146 
3147  /*
3148  * The current subtransaction is the target of a ROLLBACK TO
3149  * command. Abort and pop it, then start a new subtransaction
3150  * with the same name.
3151  */
3152  case TBLOCK_SUBRESTART:
3153  {
3154  char *name;
3155  int savepointLevel;
3156 
3157  /* save name and keep Cleanup from freeing it */
3158  name = s->name;
3159  s->name = NULL;
3160  savepointLevel = s->savepointLevel;
3161 
3164 
3165  DefineSavepoint(NULL);
3166  s = CurrentTransactionState; /* changed by push */
3167  s->name = name;
3169 
3170  /* This is the same as TBLOCK_SUBBEGIN case */
3174  }
3175  break;
3176 
3177  /*
3178  * Same as above, but the subtransaction had already failed, so we
3179  * don't need AbortSubTransaction.
3180  */
3182  {
3183  char *name;
3184  int savepointLevel;
3185 
3186  /* save name and keep Cleanup from freeing it */
3187  name = s->name;
3188  s->name = NULL;
3189  savepointLevel = s->savepointLevel;
3190 
3192 
3193  DefineSavepoint(NULL);
3194  s = CurrentTransactionState; /* changed by push */
3195  s->name = name;
3197 
3198  /* This is the same as TBLOCK_SUBBEGIN case */
3202  }
3203  break;
3204  }
3205 }
3206 
3207 /*
3208  * AbortCurrentTransaction
3209  */
3210 void
3212 {
3214 
3215  switch (s->blockState)
3216  {
3217  case TBLOCK_DEFAULT:
3218  if (s->state == TRANS_DEFAULT)
3219  {
3220  /* we are idle, so nothing to do */
3221  }
3222  else
3223  {
3224  /*
3225  * We can get here after an error during transaction start
3226  * (state will be TRANS_START). Need to clean up the
3227  * incompletely started transaction. First, adjust the
3228  * low-level state to suppress warning message from
3229  * AbortTransaction.
3230  */
3231  if (s->state == TRANS_START)
3232  s->state = TRANS_INPROGRESS;
3233  AbortTransaction();
3235  }
3236  break;
3237 
3238  /*
3239  * If we aren't in a transaction block, we just do the basic abort
3240  * & cleanup transaction. For this purpose, we treat an implicit
3241  * transaction block as if it were a simple statement.
3242  */
3243  case TBLOCK_STARTED:
3245  AbortTransaction();
3248  break;
3249 
3250  /*
3251  * If we are in TBLOCK_BEGIN it means something screwed up right
3252  * after reading "BEGIN TRANSACTION". We assume that the user
3253  * will interpret the error as meaning the BEGIN failed to get him
3254  * into a transaction block, so we should abort and return to idle
3255  * state.
3256  */
3257  case TBLOCK_BEGIN:
3258  AbortTransaction();
3261  break;
3262 
3263  /*
3264  * We are somewhere in a transaction block and we've gotten a
3265  * failure, so we abort the transaction and set up the persistent
3266  * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3267  */
3268  case TBLOCK_INPROGRESS:
3270  AbortTransaction();
3271  s->blockState = TBLOCK_ABORT;
3272  /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
3273  break;
3274 
3275  /*
3276  * Here, we failed while trying to COMMIT. Clean up the
3277  * transaction and return to idle state (we do not want to stay in
3278  * the transaction).
3279  */
3280  case TBLOCK_END:
3281  AbortTransaction();
3284  break;
3285 
3286  /*
3287  * Here, we are already in an aborted transaction state and are
3288  * waiting for a ROLLBACK, but for some reason we failed again! So
3289  * we just remain in the abort state.
3290  */
3291  case TBLOCK_ABORT:
3292  case TBLOCK_SUBABORT:
3293  break;
3294 
3295  /*
3296  * We are in a failed transaction and we got the ROLLBACK command.
3297  * We have already aborted, we just need to cleanup and go to idle
3298  * state.
3299  */
3300  case TBLOCK_ABORT_END:
3303  break;
3304 
3305  /*
3306  * We are in a live transaction and we got a ROLLBACK command.
3307  * Abort, cleanup, go to idle state.
3308  */
3309  case TBLOCK_ABORT_PENDING:
3310  AbortTransaction();
3313  break;
3314 
3315  /*
3316  * Here, we failed while trying to PREPARE. Clean up the
3317  * transaction and return to idle state (we do not want to stay in
3318  * the transaction).
3319  */
3320  case TBLOCK_PREPARE:
3321  AbortTransaction();
3324  break;
3325 
3326  /*
3327  * We got an error inside a subtransaction. Abort just the
3328  * subtransaction, and go to the persistent SUBABORT state until
3329  * we get ROLLBACK.
3330  */
3331  case TBLOCK_SUBINPROGRESS:
3334  break;
3335 
3336  /*
3337  * If we failed while trying to create a subtransaction, clean up
3338  * the broken subtransaction and abort the parent. The same
3339  * applies if we get a failure while ending a subtransaction.
3340  */
3341  case TBLOCK_SUBBEGIN:
3342  case TBLOCK_SUBRELEASE:
3343  case TBLOCK_SUBCOMMIT:
3345  case TBLOCK_SUBRESTART:
3349  break;
3350 
3351  /*
3352  * Same as above, except the Abort() was already done.
3353  */
3354  case TBLOCK_SUBABORT_END:
3358  break;
3359  }
3360 }
3361 
3362 /*
3363  * PreventInTransactionBlock
3364  *
3365  * This routine is to be called by statements that must not run inside
3366  * a transaction block, typically because they have non-rollback-able
3367  * side effects or do internal commits.
3368  *
3369  * If we have already started a transaction block, issue an error; also issue
3370  * an error if we appear to be running inside a user-defined function (which
3371  * could issue more commands and possibly cause a failure after the statement
3372  * completes). Subtransactions are verboten too.
3373  *
3374  * isTopLevel: passed down from ProcessUtility to determine whether we are
3375  * inside a function. (We will always fail if this is false, but it's
3376  * convenient to centralize the check here instead of making callers do it.)
3377  * stmtType: statement type name, for error messages.
3378  */
3379 void
3380 PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
3381 {
3382  /*
3383  * xact block already started?
3384  */
3385  if (IsTransactionBlock())
3386  ereport(ERROR,
3387  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3388  /* translator: %s represents an SQL statement name */
3389  errmsg("%s cannot run inside a transaction block",
3390  stmtType)));
3391 
3392  /*
3393  * subtransaction?
3394  */
3395  if (IsSubTransaction())
3396  ereport(ERROR,
3397  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3398  /* translator: %s represents an SQL statement name */
3399  errmsg("%s cannot run inside a subtransaction",
3400  stmtType)));
3401 
3402  /*
3403  * inside a function call?
3404  */
3405  if (!isTopLevel)
3406  ereport(ERROR,
3407  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3408  /* translator: %s represents an SQL statement name */
3409  errmsg("%s cannot be executed from a function", stmtType)));
3410 
3411  /* If we got past IsTransactionBlock test, should be in default state */
3412  if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3413  CurrentTransactionState->blockState != TBLOCK_STARTED)
3414  elog(FATAL, "cannot prevent transaction chain");
3415  /* all okay */
3416 }
3417 
3418 /*
3419  * WarnNoTransactionBlock
3420  * RequireTransactionBlock
3421  *
3422  * These two functions allow for warnings or errors if a command is executed
3423  * outside of a transaction block. This is useful for commands that have no
3424  * effects that persist past transaction end (and so calling them outside a
3425  * transaction block is presumably an error). DECLARE CURSOR is an example.
3426  * While top-level transaction control commands (BEGIN/COMMIT/ABORT) and SET
3427  * that have no effect issue warnings, all other no-effect commands generate
3428  * errors.
3429  *
3430  * If we appear to be running inside a user-defined function, we do not
3431  * issue anything, since the function could issue more commands that make
3432  * use of the current statement's results. Likewise subtransactions.
3433  * Thus these are inverses for PreventInTransactionBlock.
3434  *
3435  * isTopLevel: passed down from ProcessUtility to determine whether we are
3436  * inside a function.
3437  * stmtType: statement type name, for warning or error messages.
3438  */
3439 void
3440 WarnNoTransactionBlock(bool isTopLevel, const char *stmtType)
3441 {
3442  CheckTransactionBlock(isTopLevel, false, stmtType);
3443 }
3444 
3445 void
3446 RequireTransactionBlock(bool isTopLevel, const char *stmtType)
3447 {
3448  CheckTransactionBlock(isTopLevel, true, stmtType);
3449 }
3450 
3451 /*
3452  * This is the implementation of the above two.
3453  */
3454 static void
3455 CheckTransactionBlock(bool isTopLevel, bool throwError, const char *stmtType)
3456 {
3457  /*
3458  * xact block already started?
3459  */
3460  if (IsTransactionBlock())
3461  return;
3462 
3463  /*
3464  * subtransaction?
3465  */
3466  if (IsSubTransaction())
3467  return;
3468 
3469  /*
3470  * inside a function call?
3471  */
3472  if (!isTopLevel)
3473  return;
3474 
3475  ereport(throwError ? ERROR : WARNING,
3476  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3477  /* translator: %s represents an SQL statement name */
3478  errmsg("%s can only be used in transaction blocks",
3479  stmtType)));
3480 }
3481 
3482 /*
3483  * IsInTransactionBlock
3484  *
3485  * This routine is for statements that need to behave differently inside
3486  * a transaction block than when running as single commands. ANALYZE is
3487  * currently the only example.
3488  *
3489  * isTopLevel: passed down from ProcessUtility to determine whether we are
3490  * inside a function.
3491  */
3492 bool
3493 IsInTransactionBlock(bool isTopLevel)
3494 {
3495  /*
3496  * Return true on same conditions that would make
3497  * PreventInTransactionBlock error out
3498  */
3499  if (IsTransactionBlock())
3500  return true;
3501 
3502  if (IsSubTransaction())
3503  return true;
3504 
3505  if (!isTopLevel)
3506  return true;
3507 
3508  if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3509  CurrentTransactionState->blockState != TBLOCK_STARTED)
3510  return true;
3511 
3512  return false;
3513 }
3514 
3515 
3516 /*
3517  * Register or deregister callback functions for start- and end-of-xact
3518  * operations.
3519  *
3520  * These functions are intended for use by dynamically loaded modules.
3521  * For built-in modules we generally just hardwire the appropriate calls
3522  * (mainly because it's easier to control the order that way, where needed).
3523  *
3524  * At transaction end, the callback occurs post-commit or post-abort, so the
3525  * callback functions can only do noncritical cleanup.
3526  */
3527 void
3529 {
3530  XactCallbackItem *item;
3531 
3532  item = (XactCallbackItem *)
3534  item->callback = callback;
3535  item->arg = arg;
3536  item->next = Xact_callbacks;
3537  Xact_callbacks = item;
3538 }
3539 
3540 void
3542 {
3543  XactCallbackItem *item;
3544  XactCallbackItem *prev;
3545 
3546  prev = NULL;
3547  for (item = Xact_callbacks; item; prev = item, item = item->next)
3548  {
3549  if (item->callback == callback && item->arg == arg)
3550  {
3551  if (prev)
3552  prev->next = item->next;
3553  else
3554  Xact_callbacks = item->next;
3555  pfree(item);
3556  break;
3557  }
3558  }
3559 }
3560 
3561 static void
3563 {
3564  XactCallbackItem *item;
3565 
3566  for (item = Xact_callbacks; item; item = item->next)
3567  item->callback(event, item->arg);
3568 }
3569 
3570 
3571 /*
3572  * Register or deregister callback functions for start- and end-of-subxact
3573  * operations.
3574  *
3575  * Pretty much same as above, but for subtransaction events.
3576  *
3577  * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3578  * so the callback functions can only do noncritical cleanup. At
3579  * subtransaction start, the callback is called when the subtransaction has
3580  * finished initializing.
3581  */
3582 void
3584 {
3585  SubXactCallbackItem *item;
3586 
3587  item = (SubXactCallbackItem *)
3589  item->callback = callback;
3590  item->arg = arg;
3591  item->next = SubXact_callbacks;
3592  SubXact_callbacks = item;
3593 }
3594 
3595 void
3597 {
3598  SubXactCallbackItem *item;
3599  SubXactCallbackItem *prev;
3600 
3601  prev = NULL;
3602  for (item = SubXact_callbacks; item; prev = item, item = item->next)
3603  {
3604  if (item->callback == callback && item->arg == arg)
3605  {
3606  if (prev)
3607  prev->next = item->next;
3608  else
3609  SubXact_callbacks = item->next;
3610  pfree(item);
3611  break;
3612  }
3613  }
3614 }
3615 
3616 static void
3618  SubTransactionId mySubid,
3619  SubTransactionId parentSubid)
3620 {
3621  SubXactCallbackItem *item;
3622 
3623  for (item = SubXact_callbacks; item; item = item->next)
3624  item->callback(event, mySubid, parentSubid, item->arg);
3625 }
3626 
3627 
3628 /* ----------------------------------------------------------------
3629  * transaction block support
3630  * ----------------------------------------------------------------
3631  */
3632 
3633 /*
3634  * BeginTransactionBlock
3635  * This executes a BEGIN command.
3636  */
3637 void
3639 {
3641 
3642  switch (s->blockState)
3643  {
3644  /*
3645  * We are not inside a transaction block, so allow one to begin.
3646  */
3647  case TBLOCK_STARTED:
3648  s->blockState = TBLOCK_BEGIN;
3649  break;
3650 
3651  /*
3652  * BEGIN converts an implicit transaction block to a regular one.
3653  * (Note that we allow this even if we've already done some
3654  * commands, which is a bit odd but matches historical practice.)
3655  */
3657  s->blockState = TBLOCK_BEGIN;
3658  break;
3659 
3660  /*
3661  * Already a transaction block in progress.
3662  */
3663  case TBLOCK_INPROGRESS:
3665  case TBLOCK_SUBINPROGRESS:
3666  case TBLOCK_ABORT:
3667  case TBLOCK_SUBABORT:
3668  ereport(WARNING,
3669  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3670  errmsg("there is already a transaction in progress")));
3671  break;
3672 
3673  /* These cases are invalid. */
3674  case TBLOCK_DEFAULT:
3675  case TBLOCK_BEGIN:
3676  case TBLOCK_SUBBEGIN:
3677  case TBLOCK_END:
3678  case TBLOCK_SUBRELEASE:
3679  case TBLOCK_SUBCOMMIT:
3680  case TBLOCK_ABORT_END:
3681  case TBLOCK_SUBABORT_END:
3682  case TBLOCK_ABORT_PENDING:
3684  case TBLOCK_SUBRESTART:
3686  case TBLOCK_PREPARE:
3687  elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3689  break;
3690  }
3691 }
3692 
3693 /*
3694  * PrepareTransactionBlock
3695  * This executes a PREPARE command.
3696  *
3697  * Since PREPARE may actually do a ROLLBACK, the result indicates what
3698  * happened: true for PREPARE, false for ROLLBACK.
3699  *
3700  * Note that we don't actually do anything here except change blockState.
3701  * The real work will be done in the upcoming PrepareTransaction().
3702  * We do it this way because it's not convenient to change memory context,
3703  * resource owner, etc while executing inside a Portal.
3704  */
3705 bool
3706 PrepareTransactionBlock(const char *gid)
3707 {
3708  TransactionState s;
3709  bool result;
3710 
3711  /* Set up to commit the current transaction */
3712  result = EndTransactionBlock(false);
3713 
3714  /* If successful, change outer tblock state to PREPARE */
3715  if (result)
3716  {
3718 
3719  while (s->parent != NULL)
3720  s = s->parent;
3721 
3722  if (s->blockState == TBLOCK_END)
3723  {
3724  /* Save GID where PrepareTransaction can find it again */
3726 
3728  }
3729  else
3730  {
3731  /*
3732  * ignore case where we are not in a transaction;
3733  * EndTransactionBlock already issued a warning.
3734  */
3737  /* Don't send back a PREPARE result tag... */
3738  result = false;
3739  }
3740  }
3741 
3742  return result;
3743 }
3744 
3745 /*
3746  * EndTransactionBlock
3747  * This executes a COMMIT command.
3748  *
3749  * Since COMMIT may actually do a ROLLBACK, the result indicates what
3750  * happened: true for COMMIT, false for ROLLBACK.
3751  *
3752  * Note that we don't actually do anything here except change blockState.
3753  * The real work will be done in the upcoming CommitTransactionCommand().
3754  * We do it this way because it's not convenient to change memory context,
3755  * resource owner, etc while executing inside a Portal.
3756  */
3757 bool
3759 {
3761  bool result = false;
3762 
3763  switch (s->blockState)
3764  {
3765  /*
3766  * We are in a transaction block, so tell CommitTransactionCommand
3767  * to COMMIT.
3768  */
3769  case TBLOCK_INPROGRESS:
3770  s->blockState = TBLOCK_END;
3771  result = true;
3772  break;
3773 
3774  /*
3775  * We are in an implicit transaction block. If AND CHAIN was
3776  * specified, error. Otherwise commit, but issue a warning
3777  * because there was no explicit BEGIN before this.
3778  */
3780  if (chain)
3781  ereport(ERROR,
3782  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3783  /* translator: %s represents an SQL statement name */
3784  errmsg("%s can only be used in transaction blocks",
3785  "COMMIT AND CHAIN")));
3786  else
3787  ereport(WARNING,
3788  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3789  errmsg("there is no transaction in progress")));
3790  s->blockState = TBLOCK_END;
3791  result = true;
3792  break;
3793 
3794  /*
3795  * We are in a failed transaction block. Tell
3796  * CommitTransactionCommand it's time to exit the block.
3797  */
3798  case TBLOCK_ABORT:
3800  break;
3801 
3802  /*
3803  * We are in a live subtransaction block. Set up to subcommit all
3804  * open subtransactions and then commit the main transaction.
3805  */
3806  case TBLOCK_SUBINPROGRESS:
3807  while (s->parent != NULL)
3808  {
3809  if (s->blockState == TBLOCK_SUBINPROGRESS)
3811  else
3812  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3814  s = s->parent;
3815  }
3816  if (s->blockState == TBLOCK_INPROGRESS)
3817  s->blockState = TBLOCK_END;
3818  else
3819  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3821  result = true;
3822  break;
3823 
3824  /*
3825  * Here we are inside an aborted subtransaction. Treat the COMMIT
3826  * as ROLLBACK: set up to abort everything and exit the main
3827  * transaction.
3828  */
3829  case TBLOCK_SUBABORT:
3830  while (s->parent != NULL)
3831  {
3832  if (s->blockState == TBLOCK_SUBINPROGRESS)
3834  else if (s->blockState == TBLOCK_SUBABORT)
3836  else
3837  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3839  s = s->parent;
3840  }
3841  if (s->blockState == TBLOCK_INPROGRESS)
3843  else if (s->blockState == TBLOCK_ABORT)
3845  else
3846  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3848  break;
3849 
3850  /*
3851  * The user issued COMMIT when not inside a transaction. For
3852  * COMMIT without CHAIN, issue a WARNING, staying in
3853  * TBLOCK_STARTED state. The upcoming call to
3854  * CommitTransactionCommand() will then close the transaction and
3855  * put us back into the default state. For COMMIT AND CHAIN,
3856  * error.
3857  */
3858  case TBLOCK_STARTED:
3859  if (chain)
3860  ereport(ERROR,
3861  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3862  /* translator: %s represents an SQL statement name */
3863  errmsg("%s can only be used in transaction blocks",
3864  "COMMIT AND CHAIN")));
3865  else
3866  ereport(WARNING,
3867  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3868  errmsg("there is no transaction in progress")));
3869  result = true;
3870  break;
3871 
3872  /*
3873  * The user issued a COMMIT that somehow ran inside a parallel
3874  * worker. We can't cope with that.
3875  */
3877  ereport(FATAL,
3878  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3879  errmsg("cannot commit during a parallel operation")));
3880  break;
3881 
3882  /* These cases are invalid. */
3883  case TBLOCK_DEFAULT:
3884  case TBLOCK_BEGIN:
3885  case TBLOCK_SUBBEGIN:
3886  case TBLOCK_END:
3887  case TBLOCK_SUBRELEASE:
3888  case TBLOCK_SUBCOMMIT:
3889  case TBLOCK_ABORT_END:
3890  case TBLOCK_SUBABORT_END:
3891  case TBLOCK_ABORT_PENDING:
3893  case TBLOCK_SUBRESTART:
3895  case TBLOCK_PREPARE:
3896  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3898  break;
3899  }
3900 
3902  s->blockState == TBLOCK_END ||
3903  s->blockState == TBLOCK_ABORT_END ||
3905 
3906  s->chain = chain;
3907 
3908  return result;
3909 }
3910 
3911 /*
3912  * UserAbortTransactionBlock
3913  * This executes a ROLLBACK command.
3914  *
3915  * As above, we don't actually do anything here except change blockState.
3916  */
3917 void
3919 {
3921 
3922  switch (s->blockState)
3923  {
3924  /*
3925  * We are inside a transaction block and we got a ROLLBACK command
3926  * from the user, so tell CommitTransactionCommand to abort and
3927  * exit the transaction block.
3928  */
3929  case TBLOCK_INPROGRESS:
3931  break;
3932 
3933  /*
3934  * We are inside a failed transaction block and we got a ROLLBACK
3935  * command from the user. Abort processing is already done, so
3936  * CommitTransactionCommand just has to cleanup and go back to
3937  * idle state.
3938  */
3939  case TBLOCK_ABORT:
3941  break;
3942 
3943  /*
3944  * We are inside a subtransaction. Mark everything up to top
3945  * level as exitable.
3946  */
3947  case TBLOCK_SUBINPROGRESS:
3948  case TBLOCK_SUBABORT:
3949  while (s->parent != NULL)
3950  {
3951  if (s->blockState == TBLOCK_SUBINPROGRESS)
3953  else if (s->blockState == TBLOCK_SUBABORT)
3955  else
3956  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3958  s = s->parent;
3959  }
3960  if (s->blockState == TBLOCK_INPROGRESS)
3962  else if (s->blockState == TBLOCK_ABORT)
3964  else
3965  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3967  break;
3968 
3969  /*
3970  * The user issued ABORT when not inside a transaction. For
3971  * ROLLBACK without CHAIN, issue a WARNING and go to abort state.
3972  * The upcoming call to CommitTransactionCommand() will then put
3973  * us back into the default state. For ROLLBACK AND CHAIN, error.
3974  *
3975  * We do the same thing with ABORT inside an implicit transaction,
3976  * although in this case we might be rolling back actual database
3977  * state changes. (It's debatable whether we should issue a
3978  * WARNING in this case, but we have done so historically.)
3979  */
3980  case TBLOCK_STARTED:
3982  if (chain)
3983  ereport(ERROR,
3984  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3985  /* translator: %s represents an SQL statement name */
3986  errmsg("%s can only be used in transaction blocks",
3987  "ROLLBACK AND CHAIN")));
3988  else
3989  ereport(WARNING,
3990  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3991  errmsg("there is no transaction in progress")));
3993  break;
3994 
3995  /*
3996  * The user issued an ABORT that somehow ran inside a parallel
3997  * worker. We can't cope with that.
3998  */
4000  ereport(FATAL,
4001  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4002  errmsg("cannot abort during a parallel operation")));
4003  break;
4004 
4005  /* These cases are invalid. */
4006  case TBLOCK_DEFAULT:
4007  case TBLOCK_BEGIN:
4008  case TBLOCK_SUBBEGIN:
4009  case TBLOCK_END:
4010  case TBLOCK_SUBRELEASE:
4011  case TBLOCK_SUBCOMMIT:
4012  case TBLOCK_ABORT_END:
4013  case TBLOCK_SUBABORT_END:
4014  case TBLOCK_ABORT_PENDING:
4016  case TBLOCK_SUBRESTART:
4018  case TBLOCK_PREPARE:
4019  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4021  break;
4022  }
4023 
4026 
4027  s->chain = chain;
4028 }
4029 
4030 /*
4031  * BeginImplicitTransactionBlock
4032  * Start an implicit transaction block if we're not already in one.
4033  *
4034  * Unlike BeginTransactionBlock, this is called directly from the main loop
4035  * in postgres.c, not within a Portal. So we can just change blockState
4036  * without a lot of ceremony. We do not expect caller to do
4037  * CommitTransactionCommand/StartTransactionCommand.
4038  */
4039 void
4041 {
4043 
4044  /*
4045  * If we are in STARTED state (that is, no transaction block is open),
4046  * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
4047  * block.
4048  *
4049  * For caller convenience, we consider all other transaction states as
4050  * legal here; otherwise the caller would need its own state check, which
4051  * seems rather pointless.
4052  */
4053  if (s->blockState == TBLOCK_STARTED)
4055 }
4056 
4057 /*
4058  * EndImplicitTransactionBlock
4059  * End an implicit transaction block, if we're in one.
4060  *
4061  * Like EndTransactionBlock, we just make any needed blockState change here.
4062  * The real work will be done in the upcoming CommitTransactionCommand().
4063  */
4064 void
4066 {
4068 
4069  /*
4070  * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
4071  * allowing CommitTransactionCommand to commit whatever happened during
4072  * the implicit transaction block as though it were a single statement.
4073  *
4074  * For caller convenience, we consider all other transaction states as
4075  * legal here; otherwise the caller would need its own state check, which
4076  * seems rather pointless.
4077  */
4080 }
4081 
4082 /*
4083  * DefineSavepoint
4084  * This executes a SAVEPOINT command.
4085  */
4086 void
4087 DefineSavepoint(const char *name)
4088 {
4090 
4091  /*
4092  * Workers synchronize transaction state at the beginning of each parallel
4093  * operation, so we can't account for new subtransactions after that
4094  * point. (Note that this check will certainly error out if s->blockState
4095  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4096  * below.)
4097  */
4098  if (IsInParallelMode())
4099  ereport(ERROR,
4100  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4101  errmsg("cannot define savepoints during a parallel operation")));
4102 
4103  switch (s->blockState)
4104  {
4105  case TBLOCK_INPROGRESS:
4106  case TBLOCK_SUBINPROGRESS:
4107  /* Normal subtransaction start */
4108  PushTransaction();
4109  s = CurrentTransactionState; /* changed by push */
4110 
4111  /*
4112  * Savepoint names, like the TransactionState block itself, live
4113  * in TopTransactionContext.
4114  */
4115  if (name)
4117  break;
4118 
4119  /*
4120  * We disallow savepoint commands in implicit transaction blocks.
4121  * There would be no great difficulty in allowing them so far as
4122  * this module is concerned, but a savepoint seems inconsistent
4123  * with exec_simple_query's behavior of abandoning the whole query
4124  * string upon error. Also, the point of an implicit transaction
4125  * block (as opposed to a regular one) is to automatically close
4126  * after an error, so it's hard to see how a savepoint would fit
4127  * into that.
4128  *
4129  * The error messages for this are phrased as if there were no
4130  * active transaction block at all, which is historical but
4131  * perhaps could be improved.
4132  */
4134  ereport(ERROR,
4135  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4136  /* translator: %s represents an SQL statement name */
4137  errmsg("%s can only be used in transaction blocks",
4138  "SAVEPOINT")));
4139  break;
4140 
4141  /* These cases are invalid. */
4142  case TBLOCK_DEFAULT:
4143  case TBLOCK_STARTED:
4144  case TBLOCK_BEGIN:
4146  case TBLOCK_SUBBEGIN:
4147  case TBLOCK_END:
4148  case TBLOCK_SUBRELEASE:
4149  case TBLOCK_SUBCOMMIT:
4150  case TBLOCK_ABORT:
4151  case TBLOCK_SUBABORT:
4152  case TBLOCK_ABORT_END:
4153  case TBLOCK_SUBABORT_END:
4154  case TBLOCK_ABORT_PENDING:
4156  case TBLOCK_SUBRESTART:
4158  case TBLOCK_PREPARE:
4159  elog(FATAL, "DefineSavepoint: unexpected state %s",
4161  break;
4162  }
4163 }
4164 
4165 /*
4166  * ReleaseSavepoint
4167  * This executes a RELEASE command.
4168  *
4169  * As above, we don't actually do anything here except change blockState.
4170  */
4171 void
4173 {
4175  TransactionState target,
4176  xact;
4177 
4178  /*
4179  * Workers synchronize transaction state at the beginning of each parallel
4180  * operation, so we can't account for transaction state change after that
4181  * point. (Note that this check will certainly error out if s->blockState
4182  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4183  * below.)
4184  */
4185  if (IsInParallelMode())
4186  ereport(ERROR,
4187  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4188  errmsg("cannot release savepoints during a parallel operation")));
4189 
4190  switch (s->blockState)
4191  {
4192  /*
4193  * We can't release a savepoint if there is no savepoint defined.
4194  */
4195  case TBLOCK_INPROGRESS:
4196  ereport(ERROR,
4197  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4198  errmsg("savepoint \"%s\" does not exist", name)));
4199  break;
4200 
4202  /* See comment about implicit transactions in DefineSavepoint */
4203  ereport(ERROR,
4204  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4205  /* translator: %s represents an SQL statement name */
4206  errmsg("%s can only be used in transaction blocks",
4207  "RELEASE SAVEPOINT")));
4208  break;
4209 
4210  /*
4211  * We are in a non-aborted subtransaction. This is the only valid
4212  * case.
4213  */
4214  case TBLOCK_SUBINPROGRESS:
4215  break;
4216 
4217  /* These cases are invalid. */
4218  case TBLOCK_DEFAULT:
4219  case TBLOCK_STARTED:
4220  case TBLOCK_BEGIN:
4222  case TBLOCK_SUBBEGIN:
4223  case TBLOCK_END:
4224  case TBLOCK_SUBRELEASE:
4225  case TBLOCK_SUBCOMMIT:
4226  case TBLOCK_ABORT:
4227  case TBLOCK_SUBABORT:
4228  case TBLOCK_ABORT_END:
4229  case TBLOCK_SUBABORT_END:
4230  case TBLOCK_ABORT_PENDING:
4232  case TBLOCK_SUBRESTART:
4234  case TBLOCK_PREPARE:
4235  elog(FATAL, "ReleaseSavepoint: unexpected state %s",
4237  break;
4238  }
4239 
4240  for (target = s; PointerIsValid(target); target = target->parent)
4241  {
4242  if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
4243  break;
4244  }
4245 
4246  if (!PointerIsValid(target))
4247  ereport(ERROR,
4248  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4249  errmsg("savepoint \"%s\" does not exist", name)));
4250 
4251  /* disallow crossing savepoint level boundaries */
4252  if (target->savepointLevel != s->savepointLevel)
4253  ereport(ERROR,
4254  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4255  errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4256 
4257  /*
4258  * Mark "commit pending" all subtransactions up to the target
4259  * subtransaction. The actual commits will happen when control gets to
4260  * CommitTransactionCommand.
4261  */
4262  xact = CurrentTransactionState;
4263  for (;;)
4264  {
4266  xact->blockState = TBLOCK_SUBRELEASE;
4267  if (xact == target)
4268  break;
4269  xact = xact->parent;
4270  Assert(PointerIsValid(xact));
4271  }
4272 }
4273 
4274 /*
4275  * RollbackToSavepoint
4276  * This executes a ROLLBACK TO <savepoint> command.
4277  *
4278  * As above, we don't actually do anything here except change blockState.
4279  */
4280 void
4282 {
4284  TransactionState target,
4285  xact;
4286 
4287  /*
4288  * Workers synchronize transaction state at the beginning of each parallel
4289  * operation, so we can't account for transaction state change after that
4290  * point. (Note that this check will certainly error out if s->blockState
4291  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4292  * below.)
4293  */
4294  if (IsInParallelMode())
4295  ereport(ERROR,
4296  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4297  errmsg("cannot rollback to savepoints during a parallel operation")));
4298 
4299  switch (s->blockState)
4300  {
4301  /*
4302  * We can't rollback to a savepoint if there is no savepoint
4303  * defined.
4304  */
4305  case TBLOCK_INPROGRESS:
4306  case TBLOCK_ABORT:
4307  ereport(ERROR,
4308  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4309  errmsg("savepoint \"%s\" does not exist", name)));
4310  break;
4311 
4313  /* See comment about implicit transactions in DefineSavepoint */
4314  ereport(ERROR,
4315  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4316  /* translator: %s represents an SQL statement name */
4317  errmsg("%s can only be used in transaction blocks",
4318  "ROLLBACK TO SAVEPOINT")));
4319  break;
4320 
4321  /*
4322  * There is at least one savepoint, so proceed.
4323  */
4324  case TBLOCK_SUBINPROGRESS:
4325  case TBLOCK_SUBABORT:
4326  break;
4327 
4328  /* These cases are invalid. */
4329  case TBLOCK_DEFAULT:
4330  case TBLOCK_STARTED:
4331  case TBLOCK_BEGIN:
4333  case TBLOCK_SUBBEGIN:
4334  case TBLOCK_END:
4335  case TBLOCK_SUBRELEASE:
4336  case TBLOCK_SUBCOMMIT:
4337  case TBLOCK_ABORT_END:
4338  case TBLOCK_SUBABORT_END:
4339  case TBLOCK_ABORT_PENDING:
4341  case TBLOCK_SUBRESTART:
4343  case TBLOCK_PREPARE:
4344  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4346  break;
4347  }
4348 
4349  for (target = s; PointerIsValid(target); target = target->parent)
4350  {
4351  if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
4352  break;
4353  }
4354 
4355  if (!PointerIsValid(target))
4356  ereport(ERROR,
4357  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4358  errmsg("savepoint \"%s\" does not exist", name)));
4359 
4360  /* disallow crossing savepoint level boundaries */
4361  if (target->savepointLevel != s->savepointLevel)
4362  ereport(ERROR,
4363  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4364  errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4365 
4366  /*
4367  * Mark "abort pending" all subtransactions up to the target
4368  * subtransaction. The actual aborts will happen when control gets to
4369  * CommitTransactionCommand.
4370  */
4371  xact = CurrentTransactionState;
4372  for (;;)
4373  {
4374  if (xact == target)
4375  break;
4376  if (xact->blockState == TBLOCK_SUBINPROGRESS)
4378  else if (xact->blockState == TBLOCK_SUBABORT)
4380  else
4381  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4383  xact = xact->parent;
4384  Assert(PointerIsValid(xact));
4385  }
4386 
4387  /* And mark the target as "restart pending" */
4388  if (xact->blockState == TBLOCK_SUBINPROGRESS)
4389  xact->blockState = TBLOCK_SUBRESTART;
4390  else if (xact->blockState == TBLOCK_SUBABORT)
4392  else
4393  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4395 }
4396 
4397 /*
4398  * BeginInternalSubTransaction
4399  * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
4400  * TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_END, and TBLOCK_PREPARE states,
4401  * and therefore it can safely be used in functions that might be called
4402  * when not inside a BEGIN block or when running deferred triggers at
4403  * COMMIT/PREPARE time. Also, it automatically does
4404  * CommitTransactionCommand/StartTransactionCommand instead of expecting
4405  * the caller to do it.
4406  */
4407 void
4409 {
4411 
4412  /*
4413  * Workers synchronize transaction state at the beginning of each parallel
4414  * operation, so we can't account for new subtransactions after that
4415  * point. We might be able to make an exception for the type of
4416  * subtransaction established by this function, which is typically used in
4417  * contexts where we're going to release or roll back the subtransaction
4418  * before proceeding further, so that no enduring change to the
4419  * transaction state occurs. For now, however, we prohibit this case along
4420  * with all the others.
4421  */
4422  if (IsInParallelMode())
4423  ereport(ERROR,
4424  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4425  errmsg("cannot start subtransactions during a parallel operation")));
4426 
4427  switch (s->blockState)
4428  {
4429  case TBLOCK_STARTED:
4430  case TBLOCK_INPROGRESS:
4432  case TBLOCK_END:
4433  case TBLOCK_PREPARE:
4434  case TBLOCK_SUBINPROGRESS:
4435  /* Normal subtransaction start */
4436  PushTransaction();
4437  s = CurrentTransactionState; /* changed by push */
4438 
4439  /*
4440  * Savepoint names, like the TransactionState block itself, live
4441  * in TopTransactionContext.
4442  */
4443  if (name)
4445  break;
4446 
4447  /* These cases are invalid. */
4448  case TBLOCK_DEFAULT:
4449  case TBLOCK_BEGIN:
4451  case TBLOCK_SUBBEGIN:
4452  case TBLOCK_SUBRELEASE:
4453  case TBLOCK_SUBCOMMIT:
4454  case TBLOCK_ABORT:
4455  case TBLOCK_SUBABORT:
4456  case TBLOCK_ABORT_END:
4457  case TBLOCK_SUBABORT_END:
4458  case TBLOCK_ABORT_PENDING:
4460  case TBLOCK_SUBRESTART:
4462  elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4464  break;
4465  }
4466 
4469 }
4470 
4471 /*
4472  * ReleaseCurrentSubTransaction
4473  *
4474  * RELEASE (ie, commit) the innermost subtransaction, regardless of its
4475  * savepoint name (if any).
4476  * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4477  */
4478 void
4480 {
4482 
4483  /*
4484  * Workers synchronize transaction state at the beginning of each parallel
4485  * operation, so we can't account for commit of subtransactions after that
4486  * point. This should not happen anyway. Code calling this would
4487  * typically have called BeginInternalSubTransaction() first, failing
4488  * there.
4489  */
4490  if (IsInParallelMode())
4491  ereport(ERROR,
4492  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4493  errmsg("cannot commit subtransactions during a parallel operation")));
4494 
4495  if (s->blockState != TBLOCK_SUBINPROGRESS)
4496  elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
4498  Assert(s->state == TRANS_INPROGRESS);
4501  s = CurrentTransactionState; /* changed by pop */
4502  Assert(s->state == TRANS_INPROGRESS);
4503 }
4504 
4505 /*
4506  * RollbackAndReleaseCurrentSubTransaction
4507  *
4508  * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
4509  * of its savepoint name (if any).
4510  * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4511  */
4512 void
4514 {
4516 
4517  /*
4518  * Unlike ReleaseCurrentSubTransaction(), this is nominally permitted
4519  * during parallel operations. That's because we may be in the leader,
4520  * recovering from an error thrown while we were in parallel mode. We
4521  * won't reach here in a worker, because BeginInternalSubTransaction()
4522  * will have failed.
4523  */
4524 
4525  switch (s->blockState)
4526  {
4527  /* Must be in a subtransaction */
4528  case TBLOCK_SUBINPROGRESS:
4529  case TBLOCK_SUBABORT:
4530  break;
4531 
4532  /* These cases are invalid. */
4533  case TBLOCK_DEFAULT:
4534  case TBLOCK_STARTED:
4535  case TBLOCK_BEGIN:
4538  case TBLOCK_SUBBEGIN:
4539  case TBLOCK_INPROGRESS:
4540  case TBLOCK_END:
4541  case TBLOCK_SUBRELEASE:
4542  case TBLOCK_SUBCOMMIT:
4543  case TBLOCK_ABORT:
4544  case TBLOCK_ABORT_END:
4545  case TBLOCK_SUBABORT_END:
4546  case TBLOCK_ABORT_PENDING:
4548  case TBLOCK_SUBRESTART:
4550  case TBLOCK_PREPARE:
4551  elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
4553  break;
4554  }
4555 
4556  /*
4557  * Abort the current subtransaction, if needed.
4558  */
4559  if (s->blockState == TBLOCK_SUBINPROGRESS)
4561 
4562  /* And clean it up, too */
4564 
4565  s = CurrentTransactionState; /* changed by pop */
4567  s->blockState == TBLOCK_INPROGRESS ||
4569  s->blockState == TBLOCK_STARTED);
4570 }
4571 
4572 /*
4573  * AbortOutOfAnyTransaction
4574  *
4575  * This routine is provided for error recovery purposes. It aborts any
4576  * active transaction or transaction block, leaving the system in a known
4577  * idle state.
4578  */
4579 void
4581 {
4583 
4584  /* Ensure we're not running in a doomed memory context */
4585  AtAbort_Memory();
4586 
4587  /*
4588  * Get out of any transaction or nested transaction
4589  */
4590  do
4591  {
4592  switch (s->blockState)
4593  {
4594  case TBLOCK_DEFAULT:
4595  if (s->state == TRANS_DEFAULT)
4596  {
4597  /* Not in a transaction, do nothing */
4598  }
4599  else
4600  {
4601  /*
4602  * We can get here after an error during transaction start
4603  * (state will be TRANS_START). Need to clean up the
4604  * incompletely started transaction. First, adjust the
4605  * low-level state to suppress warning message from
4606  * AbortTransaction.
4607  */
4608  if (s->state == TRANS_START)
4609  s->state = TRANS_INPROGRESS;
4610  AbortTransaction();
4612  }
4613  break;
4614  case TBLOCK_STARTED:
4615  case TBLOCK_BEGIN:
4616  case TBLOCK_INPROGRESS:
4619  case TBLOCK_END:
4620  case TBLOCK_ABORT_PENDING:
4621  case TBLOCK_PREPARE:
4622  /* In a transaction, so clean up */
4623  AbortTransaction();
4626  break;
4627  case TBLOCK_ABORT:
4628  case TBLOCK_ABORT_END:
4629 
4630  /*
4631  * AbortTransaction is already done, still need Cleanup.
4632  * However, if we failed partway through running ROLLBACK,
4633  * there will be an active portal running that command, which
4634  * we need to shut down before doing CleanupTransaction.
4635  */
4636  AtAbort_Portals();
4639  break;
4640 
4641  /*
4642  * In a subtransaction, so clean it up and abort parent too
4643  */
4644  case TBLOCK_SUBBEGIN:
4645  case TBLOCK_SUBINPROGRESS:
4646  case TBLOCK_SUBRELEASE:
4647  case TBLOCK_SUBCOMMIT:
4649  case TBLOCK_SUBRESTART:
4652  s = CurrentTransactionState; /* changed by pop */
4653  break;
4654 
4655  case TBLOCK_SUBABORT:
4656  case TBLOCK_SUBABORT_END:
4658  /* As above, but AbortSubTransaction already done */
4659  if (s->curTransactionOwner)
4660  {
4661  /* As in TBLOCK_ABORT, might have a live portal to zap */
4666  }
4668  s = CurrentTransactionState; /* changed by pop */
4669  break;
4670  }
4671  } while (s->blockState != TBLOCK_DEFAULT);
4672 
4673  /* Should be out of all subxacts now */
4674  Assert(s->parent == NULL);
4675 
4676  /* If we didn't actually have anything to do, revert to TopMemoryContext */
4677  AtCleanup_Memory();
4678 }
4679 
4680 /*
4681  * IsTransactionBlock --- are we within a transaction block?
4682  */
4683 bool
4685 {
4687 
4689  return false;
4690 
4691  return true;
4692 }
4693 
4694 /*
4695  * IsTransactionOrTransactionBlock --- are we within either a transaction
4696  * or a transaction block? (The backend is only really "idle" when this
4697  * returns false.)
4698  *
4699  * This should match up with IsTransactionBlock and IsTransactionState.
4700  */
4701 bool
4703 {
4705 
4706  if (s->blockState == TBLOCK_DEFAULT)
4707  return false;
4708 
4709  return true;
4710 }
4711 
4712 /*
4713  * TransactionBlockStatusCode - return status code to send in ReadyForQuery
4714  */
4715 char
4717 {
4719 
4720  switch (s->blockState)
4721  {
4722  case TBLOCK_DEFAULT:
4723  case TBLOCK_STARTED:
4724  return 'I'; /* idle --- not in transaction */
4725  case TBLOCK_BEGIN:
4726  case TBLOCK_SUBBEGIN:
4727  case TBLOCK_INPROGRESS:
4730  case TBLOCK_SUBINPROGRESS:
4731  case TBLOCK_END:
4732  case TBLOCK_SUBRELEASE:
4733  case TBLOCK_SUBCOMMIT:
4734  case TBLOCK_PREPARE:
4735  return 'T'; /* in transaction */
4736  case TBLOCK_ABORT:
4737  case TBLOCK_SUBABORT:
4738  case TBLOCK_ABORT_END:
4739  case TBLOCK_SUBABORT_END:
4740  case TBLOCK_ABORT_PENDING:
4742  case TBLOCK_SUBRESTART:
4744  return 'E'; /* in failed transaction */
4745  }
4746 
4747  /* should never get here */
4748  elog(FATAL, "invalid transaction block state: %s",
4750  return 0; /* keep compiler quiet */
4751 }
4752 
4753 /*
4754  * IsSubTransaction
4755  */
4756 bool
4758 {
4760 
4761  if (s->nestingLevel >= 2)
4762  return true;
4763 
4764  return false;
4765 }
4766 
4767 /*
4768  * StartSubTransaction
4769  *
4770  * If you're wondering why this is separate from PushTransaction: it's because
4771  * we can't conveniently do this stuff right inside DefineSavepoint. The
4772  * SAVEPOINT utility command will be executed inside a Portal, and if we
4773  * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
4774  * the Portal will undo those settings. So we make DefineSavepoint just
4775  * push a dummy transaction block, and when control returns to the main
4776  * idle loop, CommitTransactionCommand will be called, and we'll come here
4777  * to finish starting the subtransaction.
4778  */
4779 static void
4781 {
4783 
4784  if (s->state != TRANS_DEFAULT)
4785  elog(WARNING, "StartSubTransaction while in %s state",
4787 
4788  s->state = TRANS_START;
4789 
4790  /*
4791  * Initialize subsystems for new subtransaction
4792  *
4793  * must initialize resource-management stuff first
4794  */
4798 
4799  s->state = TRANS_INPROGRESS;
4800 
4801  /*
4802  * Call start-of-subxact callbacks
4803  */
4805  s->parent->subTransactionId);
4806 
4807  ShowTransactionState("StartSubTransaction");
4808 }
4809 
4810 /*
4811  * CommitSubTransaction
4812  *
4813  * The caller has to make sure to always reassign CurrentTransactionState
4814  * if it has a local pointer to it after calling this function.
4815  */
4816 static void
4818 {
4820 
4821  ShowTransactionState("CommitSubTransaction");
4822 
4823  if (s->state != TRANS_INPROGRESS)
4824  elog(WARNING, "CommitSubTransaction while in %s state",
4826 
4827  /* Pre-commit processing goes here */
4828 
4830  s->parent->subTransactionId);
4831 
4832  /* If in parallel mode, clean up workers and exit parallel mode. */
4833  if (IsInParallelMode())
4834  {
4836  s->parallelModeLevel = 0;
4837  }
4838 
4839  /* Do the actual "commit", such as it is */
4840  s->state = TRANS_COMMIT;
4841 
4842  /* Must CCI to ensure commands of subtransaction are seen as done */
4844 
4845  /*
4846  * Prior to 8.4 we marked subcommit in clog at this point. We now only
4847  * perform that step, if required, as part of the atomic update of the
4848  * whole transaction tree at top level commit or abort.
4849  */
4850 
4851  /* Post-commit cleanup */
4854  AfterTriggerEndSubXact(true);
4859  s->parent->subTransactionId);
4861 
4863  s->parent->subTransactionId);
4864 
4867  true, false);
4869  s->parent->subTransactionId);
4870  AtEOSubXact_Inval(true);
4871  AtSubCommit_smgr();
4872 
4873  /*
4874  * The only lock we actually release here is the subtransaction XID lock.
4875  */
4879 
4880  /*
4881  * Other locks should get transferred to their parent resource owner.
4882  */
4885  true, false);
4888  true, false);
4889 
4890  AtEOXact_GUC(true, s->gucNestLevel);
4893  s->parent->subTransactionId);
4895  s->parent->subTransactionId);
4897  s->parent->subTransactionId);
4899  AtEOSubXact_PgStat(true, s->nestingLevel);
4902 
4903  /*
4904  * We need to restore the upper transaction's read-only state, in case the
4905  * upper is read-write while the child is read-only; GUC will incorrectly
4906  * think it should leave the child state in place.
4907  */
4909 
4913  s->curTransactionOwner = NULL;
4914 
4916 
4917  s->state = TRANS_DEFAULT;
4918 
4919  PopTransaction();
4920 }
4921 
4922 /*
4923  * AbortSubTransaction
4924  */
4925 static void
4927 {
4929 
4930  /* Prevent cancel/die interrupt while cleaning up */
4931  HOLD_INTERRUPTS();
4932 
4933  /* Make sure we have a valid memory context and resource owner */
4936 
4937  /*
4938  * Release any LW locks we might be holding as quickly as possible.
4939  * (Regular locks, however, must be held till we finish aborting.)
4940  * Releasing LW locks is critical since we might try to grab them again
4941  * while cleaning up!
4942  *
4943  * FIXME This may be incorrect --- Are there some locks we should keep?
4944  * Buffer locks, for example? I don't think so but I'm not sure.
4945  */
4946  LWLockReleaseAll();
4947 
4950  AbortBufferIO();
4951  UnlockBuffers();
4952 
4953  /* Reset WAL record construction state */
4955 
4956  /* Cancel condition variable sleep */
4958 
4959  /*
4960  * Also clean up any open wait for lock, since the lock manager will choke
4961  * if we try to wait for another lock before doing this.
4962  */
4963  LockErrorCleanup();
4964 
4965  /*
4966  * If any timeout events are still active, make sure the timeout interrupt
4967  * is scheduled. This covers possible loss of a timeout interrupt due to
4968  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
4969  * We delay this till after LockErrorCleanup so that we don't uselessly
4970  * reschedule lock or deadlock check timeouts.
4971  */
4973 
4974  /*
4975  * Re-enable signals, in case we got here by longjmp'ing out of a signal
4976  * handler. We do this fairly early in the sequence so that the timeout
4977  * infrastructure will be functional if needed while aborting.
4978  */
4980 
4981  /*
4982  * check the current transaction state
4983  */
4984  ShowTransactionState("AbortSubTransaction");
4985 
4986  if (s->state != TRANS_INPROGRESS)
4987  elog(WARNING, "AbortSubTransaction while in %s state",
4989 
4990  s->state = TRANS_ABORT;
4991 
4992  /*
4993  * Reset user ID which might have been changed transiently. (See notes in
4994  * AbortTransaction.)
4995  */
4997 
4998  /* Forget about any active REINDEX. */
5000 
5001  /* Reset logical streaming state. */
5003 
5004  /* Exit from parallel mode, if necessary. */
5005  if (IsInParallelMode())
5006  {
5008  s->parallelModeLevel = 0;
5009  }
5010 
5011  /*
5012  * We can skip all this stuff if the subxact failed before creating a
5013  * ResourceOwner...
5014  */
5015  if (s->curTransactionOwner)
5016  {
5017  AfterTriggerEndSubXact(false);
5023  s->parent->subTransactionId);
5025 
5026  /* Advertise the fact that we aborted in pg_xact. */
5027  (void) RecordTransactionAbort(true);
5028 
5029  /* Post-abort cleanup */
5032 
5034  s->parent->subTransactionId);
5035 
5038  false, false);
5040  s->parent->subTransactionId);
5041  AtEOSubXact_Inval(false);
5044  false, false);
5047  false, false);
5048  AtSubAbort_smgr();
5049 
5050  AtEOXact_GUC(false, s->gucNestLevel);
5051  AtEOSubXact_SPI(false, s->subTransactionId);
5053  s->parent->subTransactionId);
5055  s->parent->subTransactionId);
5057  s->parent->subTransactionId);
5059  AtEOSubXact_PgStat(false, s->nestingLevel);
5062  }
5063 
5064  /*
5065  * Restore the upper transaction's read-only state, too. This should be
5066  * redundant with GUC's cleanup but we may as well do it for consistency
5067  * with the commit case.
5068  */
5070 
5072 }
5073 
5074 /*
5075  * CleanupSubTransaction
5076  *
5077  * The caller has to make sure to always reassign CurrentTransactionState
5078  * if it has a local pointer to it after calling this function.
5079  */
5080 static void
5082 {
5084 
5085  ShowTransactionState("CleanupSubTransaction");
5086 
5087  if (s->state != TRANS_ABORT)
5088  elog(WARNING, "CleanupSubTransaction while in %s state",
5090 
5092 
5095  if (s->curTransactionOwner)
5097  s->curTransactionOwner = NULL;
5098 
5100 
5101  s->state = TRANS_DEFAULT;
5102 
5103  PopTransaction();
5104 }
5105 
5106 /*
5107  * PushTransaction
5108  * Create transaction state stack entry for a subtransaction
5109  *
5110  * The caller has to make sure to always reassign CurrentTransactionState
5111  * if it has a local pointer to it after calling this function.
5112  */
5113 static void
5115 {
5117  TransactionState s;
5118 
5119  /*
5120  * We keep subtransaction state nodes in TopTransactionContext.
5121  */
5122  s = (TransactionState)
5124  sizeof(TransactionStateData));
5125 
5126  /*
5127  * Assign a subtransaction ID, watching out for counter wraparound.
5128  */
5131  {
5133  pfree(s);
5134  ereport(ERROR,
5135  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5136  errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
5137  }
5138 
5139  /*
5140  * We can now stack a minimally valid subtransaction without fear of
5141  * failure.
5142  */
5143  s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
5145  s->parent = p;
5146  s->nestingLevel = p->nestingLevel + 1;
5149  s->state = TRANS_DEFAULT;
5153  s->parallelModeLevel = 0;
5154  s->assigned = false;
5155 
5156  CurrentTransactionState = s;
5157 
5158  /*
5159  * AbortSubTransaction and CleanupSubTransaction have to be able to cope
5160  * with the subtransaction from here on out; in particular they should not
5161  * assume that it necessarily has a transaction context, resource owner,
5162  * or XID.
5163  */
5164 }
5165 
5166 /*
5167  * PopTransaction
5168  * Pop back to parent transaction state
5169  *
5170  * The caller has to make sure to always reassign CurrentTransactionState
5171  * if it has a local pointer to it after calling this function.
5172  */
5173 static void
5175 {
5177 
5178  if (s->state != TRANS_DEFAULT)
5179  elog(WARNING, "PopTransaction while in %s state",
5181 
5182  if (s->parent == NULL)
5183  elog(FATAL, "PopTransaction with no parent");
5184 
5185  CurrentTransactionState = s->parent;
5186 
5187  /* Let's just make sure CurTransactionContext is good */
5190 
5191  /* Ditto for ResourceOwner links */
5194 
5195  /* Free the old child structure */
5196  if (s->name)
5197  pfree(s->name);
5198  pfree(s);
5199 }
5200 
5201 /*
5202  * EstimateTransactionStateSpace
5203  * Estimate the amount of space that will be needed by
5204  * SerializeTransactionState. It would be OK to overestimate slightly,
5205  * but it's simple for us to work out the precise value, so we do.
5206  */
5207 Size
5209 {
5210  TransactionState s;
5211  Size nxids = 0;
5213 
5214  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5215  {
5217  nxids = add_size(nxids, 1);
5218  nxids = add_size(nxids, s->nChildXids);
5219  }
5220 
5221  return add_size(size, mul_size(sizeof(TransactionId), nxids));
5222 }
5223 
5224 /*
5225  * SerializeTransactionState
5226  * Write out relevant details of our transaction state that will be
5227  * needed by a parallel worker.
5228  *
5229  * We need to save and restore XactDeferrable, XactIsoLevel, and the XIDs
5230  * associated with this transaction. These are serialized into a
5231  * caller-supplied buffer big enough to hold the number of bytes reported by
5232  * EstimateTransactionStateSpace(). We emit the XIDs in sorted order for the
5233  * convenience of the receiving process.
5234  */
5235 void
5236 SerializeTransactionState(Size maxsize, char *start_address)
5237 {
5238  TransactionState s;
5239  Size nxids = 0;
5240  Size i = 0;
5241  TransactionId *workspace;
5243 
5244  result = (SerializedTransactionState *) start_address;
5245 
5246  result->xactIsoLevel = XactIsoLevel;
5247  result->xactDeferrable = XactDeferrable;
5249  result->currentFullTransactionId =
5250  CurrentTransactionState->fullTransactionId;
5252 
5253  /*
5254  * If we're running in a parallel worker and launching a parallel worker
5255  * of our own, we can just pass along the information that was passed to
5256  * us.
5257  */
5258  if (nParallelCurrentXids > 0)
5259  {
5261  memcpy(&result->parallelCurrentXids[0], ParallelCurrentXids,
5263  return;
5264  }
5265 
5266  /*
5267  * OK, we need to generate a sorted list of XIDs that our workers should
5268  * view as current. First, figure out how many there are.
5269  */
5270  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5271  {
5273  nxids = add_size(nxids, 1);
5274  nxids = add_size(nxids, s->nChildXids);
5275  }
5277  <= maxsize);
5278 
5279  /* Copy them to our scratch space. */
5280  workspace = palloc(nxids * sizeof(TransactionId));
5281  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5282  {
5284  workspace[i++] = XidFromFullTransactionId(s->fullTransactionId);
5285  memcpy(&workspace[i], s->childXids,
5286  s->nChildXids * sizeof(TransactionId));
5287  i += s->nChildXids;
5288  }
5289  Assert(i == nxids);
5290 
5291  /* Sort them. */
5292  qsort(workspace, nxids, sizeof(TransactionId), xidComparator);
5293 
5294  /* Copy data into output area. */
5295  result->nParallelCurrentXids = nxids;
5296  memcpy(&result->parallelCurrentXids[0], workspace,
5297  nxids * sizeof(TransactionId));
5298 }
5299 
5300 /*
5301  * StartParallelWorkerTransaction
5302  * Start a parallel worker transaction, restoring the relevant
5303  * transaction state serialized by SerializeTransactionState.
5304  */
5305 void
5307 {
5309 
5310  Assert(CurrentTransactionState->blockState == TBLOCK_DEFAULT);
5311  StartTransaction();
5312 
5313  tstate = (SerializedTransactionState *) tstatespace;
5314  XactIsoLevel = tstate->xactIsoLevel;
5315  XactDeferrable = tstate->xactDeferrable;
5316  XactTopFullTransactionId = tstate->topFullTransactionId;
5317  CurrentTransactionState->fullTransactionId =
5318  tstate->currentFullTransactionId;
5322 
5323  CurrentTransactionState->blockState = TBLOCK_PARALLEL_INPROGRESS;
5324 }
5325 
5326 /*
5327  * EndParallelWorkerTransaction
5328  * End a parallel worker transaction.
5329  */
5330 void
5332 {
5333  Assert(CurrentTransactionState->blockState == TBLOCK_PARALLEL_INPROGRESS);
5335  CurrentTransactionState->blockState = TBLOCK_DEFAULT;
5336 }
5337 
5338 /*
5339  * ShowTransactionState
5340  * Debug support
5341  */
5342 static void
5344 {
5345  /* skip work if message will definitely not be printed */
5347  ShowTransactionStateRec(str, CurrentTransactionState);
5348 }
5349 
5350 /*
5351  * ShowTransactionStateRec
5352  * Recursive subroutine for ShowTransactionState
5353  */
5354 static void
5356 {
5358 
5359  initStringInfo(&buf);
5360 
5361  if (s->nChildXids > 0)
5362  {
5363  int i;
5364 
5365  appendStringInfo(&buf, ", children: %u", s->childXids[0]);
5366  for (i = 1; i < s->nChildXids; i++)
5367  appendStringInfo(&buf, " %u", s->childXids[i]);
5368  }
5369 
5370  if (s->parent)
5372 
5373  /* use ereport to suppress computation if msg will not be printed */
5374  ereport(DEBUG5,
5375  (errmsg_internal("%s(%d) name: %s; blockState: %s; state: %s, xid/subid/cid: %u/%u/%u%s%s",
5376  str, s->nestingLevel,
5377  PointerIsValid(s->name) ? s->name : "unnamed",
5380  (unsigned int) XidFromFullTransactionId(s->fullTransactionId),
5381  (unsigned int) s->subTransactionId,
5382  (unsigned int) currentCommandId,
5383  currentCommandIdUsed ? " (used)" : "",
5384  buf.data)));
5385 
5386  pfree(buf.data);
5387 }
5388 
5389 /*
5390  * BlockStateAsString
5391  * Debug support
5392  */
5393 static const char *
5395 {
5396  switch (blockState)
5397  {
5398  case TBLOCK_DEFAULT:
5399  return "DEFAULT";
5400  case TBLOCK_STARTED:
5401  return "STARTED";
5402  case TBLOCK_BEGIN:
5403  return "BEGIN";
5404  case TBLOCK_INPROGRESS:
5405  return "INPROGRESS";
5407  return "IMPLICIT_INPROGRESS";
5409  return "PARALLEL_INPROGRESS";
5410  case TBLOCK_END:
5411  return "END";
5412  case TBLOCK_ABORT:
5413  return "ABORT";
5414  case TBLOCK_ABORT_END:
5415  return "ABORT_END";
5416  case TBLOCK_ABORT_PENDING:
5417  return "ABORT_PENDING";
5418  case TBLOCK_PREPARE:
5419  return "PREPARE";
5420  case TBLOCK_SUBBEGIN:
5421  return "SUBBEGIN";
5422  case TBLOCK_SUBINPROGRESS:
5423  return "SUBINPROGRESS";
5424  case TBLOCK_SUBRELEASE:
5425  return "SUBRELEASE";
5426  case TBLOCK_SUBCOMMIT:
5427  return "SUBCOMMIT";
5428  case TBLOCK_SUBABORT:
5429  return "SUBABORT";
5430  case TBLOCK_SUBABORT_END:
5431  return "SUBABORT_END";
5433  return "SUBABORT_PENDING";
5434  case TBLOCK_SUBRESTART:
5435  return "SUBRESTART";
5437  return "SUBABORT_RESTART";
5438  }
5439  return "UNRECOGNIZED";
5440 }
5441 
5442 /*
5443  * TransStateAsString
5444  * Debug support
5445  */
5446 static const char *
5448 {
5449  switch (state)
5450  {
5451  case TRANS_DEFAULT:
5452  return "DEFAULT";
5453  case TRANS_START:
5454  return "START";
5455  case TRANS_INPROGRESS:
5456  return "INPROGRESS";
5457  case TRANS_COMMIT:
5458  return "COMMIT";
5459  case TRANS_ABORT:
5460  return "ABORT";
5461  case TRANS_PREPARE:
5462  return "PREPARE";
5463  }
5464  return "UNRECOGNIZED";
5465 }
5466 
5467 /*
5468  * xactGetCommittedChildren
5469  *
5470  * Gets the list of committed children of the current transaction. The return
5471  * value is the number of child transactions. *ptr is set to point to an
5472  * array of TransactionIds. The array is allocated in TopTransactionContext;
5473  * the caller should *not* pfree() it (this is a change from pre-8.4 code!).
5474  * If there are no subxacts, *ptr is set to NULL.
5475  */
5476 int
5478 {
5480 
5481  if (s->nChildXids == 0)
5482  *ptr = NULL;
5483  else
5484  *ptr = s->childXids;
5485 
5486  return s->nChildXids;
5487 }
5488 
5489 /*
5490  * XLOG support routines
5491  */
5492 
5493 
5494 /*
5495  * Log the commit record for a plain or twophase transaction commit.
5496  *
5497  * A 2pc commit will be emitted when twophase_xid is valid, a plain one
5498  * otherwise.
5499  */
5500 XLogRecPtr
5502  int nsubxacts, TransactionId *subxacts,
5503  int nrels, RelFileNode *rels,
5504  int nmsgs, SharedInvalidationMessage *msgs,
5505  bool relcacheInval,
5506  int xactflags, TransactionId twophase_xid,
5507  const char *twophase_gid)
5508 {
5509  xl_xact_commit xlrec;
5510  xl_xact_xinfo xl_xinfo;
5511  xl_xact_dbinfo xl_dbinfo;
5512  xl_xact_subxacts xl_subxacts;
5513  xl_xact_relfilenodes xl_relfilenodes;
5514  xl_xact_invals xl_invals;
5515  xl_xact_twophase xl_twophase;
5516  xl_xact_origin xl_origin;
5517  uint8 info;
5518 
5519  Assert(CritSectionCount > 0);
5520 
5521  xl_xinfo.xinfo = 0;
5522 
5523  /* decide between a plain and 2pc commit */
5524  if (!TransactionIdIsValid(twophase_xid))
5525  info = XLOG_XACT_COMMIT;
5526  else
5528 
5529  /* First figure out and collect all the information needed */
5530 
5531  xlrec.xact_time = commit_time;
5532 
5533  if (relcacheInval)
5535  if (forceSyncCommit)
5537  if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
5538  xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
5539 
5540  /*
5541  * Check if the caller would like to ask standbys for immediate feedback
5542  * once this commit is applied.
5543  */
5546 
5547  /*
5548  * Relcache invalidations requires information about the current database
5549  * and so does logical decoding.
5550  */
5551  if (nmsgs > 0 || XLogLogicalInfoActive())
5552  {
5553  xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
5554  xl_dbinfo.dbId = MyDatabaseId;
5555  xl_dbinfo.tsId = MyDatabaseTableSpace;
5556  }
5557 
5558  if (nsubxacts > 0)
5559  {
5560  xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
5561  xl_subxacts.nsubxacts = nsubxacts;
5562  }
5563 
5564  if (nrels > 0)
5565  {
5566  xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILENODES;
5567  xl_relfilenodes.nrels = nrels;
5568  info |= XLR_SPECIAL_REL_UPDATE;
5569  }
5570 
5571  if (nmsgs > 0)
5572  {
5573  xl_xinfo.xinfo |= XACT_XINFO_HAS_INVALS;
5574  xl_invals.nmsgs = nmsgs;
5575  }
5576 
5577  if (TransactionIdIsValid(twophase_xid))
5578  {
5579  xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
5580  xl_twophase.xid = twophase_xid;
5581  Assert(twophase_gid != NULL);
5582 
5583  if (XLogLogicalInfoActive())
5584  xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
5585  }
5586 
5587  /* dump transaction origin information */
5589  {
5590  xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
5591 
5594  }
5595 
5596  if (xl_xinfo.xinfo != 0)
5597  info |= XLOG_XACT_HAS_INFO;
5598 
5599  /* Then include all the collected data into the commit record. */
5600 
5601  XLogBeginInsert();
5602 
5603  XLogRegisterData((char *) (&xlrec), sizeof(xl_xact_commit));
5604 
5605  if (xl_xinfo.xinfo != 0)
5606  XLogRegisterData((char *) (&xl_xinfo.xinfo), sizeof(xl_xinfo.xinfo));
5607 
5608  if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
5609  XLogRegisterData((char *) (&xl_dbinfo), sizeof(xl_dbinfo));
5610 
5611  if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
5612  {
5613  XLogRegisterData((char *) (&xl_subxacts),
5615  XLogRegisterData((char *) subxacts,
5616  nsubxacts * sizeof(TransactionId));
5617  }
5618 
5619  if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILENODES)
5620  {
5621  XLogRegisterData((char *) (&xl_relfilenodes),
5623  XLogRegisterData((char *) rels,
5624  nrels * sizeof(RelFileNode));
5625  }
5626 
5627  if (xl_xinfo.xinfo & XACT_XINFO_HAS_INVALS)
5628  {
5629  XLogRegisterData((char *) (&xl_invals), MinSizeOfXactInvals);
5630  XLogRegisterData((char *) msgs,
5631  nmsgs * sizeof(SharedInvalidationMessage));
5632  }
5633 
5634  if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
5635  {
5636  XLogRegisterData((char *) (&xl_twophase), sizeof(xl_xact_twophase));
5637  if (xl_xinfo.xinfo & XACT_XINFO_HAS_GID)
5638  XLogRegisterData(unconstify(char *, twophase_gid), strlen(twophase_gid) + 1);
5639  }
5640 
5641  if (xl_xinfo.xinfo & XACT_XINFO_HAS_ORIGIN)
5642  XLogRegisterData((char *) (&xl_origin), sizeof(xl_xact_origin));
5643 
5644  /* we allow filtering by xacts */
5646 
5647  return XLogInsert(RM_XACT_ID, info);
5648 }
5649 
5650 /*
5651  * Log the commit record for a plain or twophase transaction abort.
5652  *
5653  * A 2pc abort will be emitted when twophase_xid is valid, a plain one
5654  * otherwise.
5655  */
5656 XLogRecPtr
5658  int nsubxacts, TransactionId *subxacts,
5659  int nrels, RelFileNode *rels,
5660  int xactflags, TransactionId twophase_xid,
5661  const char *twophase_gid)
5662 {
5663  xl_xact_abort xlrec;
5664  xl_xact_xinfo xl_xinfo;
5665  xl_xact_subxacts xl_subxacts;
5666  xl_xact_relfilenodes xl_relfilenodes;
5667  xl_xact_twophase xl_twophase;
5668  xl_xact_dbinfo xl_dbinfo;
5669  xl_xact_origin xl_origin;
5670 
5671  uint8 info;
5672 
5673  Assert(CritSectionCount > 0);
5674 
5675  xl_xinfo.xinfo = 0;
5676 
5677  /* decide between a plain and 2pc abort */
5678  if (!TransactionIdIsValid(twophase_xid))
5679  info = XLOG_XACT_ABORT;
5680  else
5681  info = XLOG_XACT_ABORT_PREPARED;
5682 
5683 
5684  /* First figure out and collect all the information needed */
5685 
5686  xlrec.xact_time = abort_time;
5687 
5688  if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
5689  xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
5690 
5691  if (nsubxacts > 0)
5692  {
5693  xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
5694  xl_subxacts.nsubxacts = nsubxacts;
5695  }
5696 
5697  if (nrels > 0)
5698  {
5699  xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILENODES;
5700  xl_relfilenodes.nrels = nrels;
5701  info |= XLR_SPECIAL_REL_UPDATE;
5702  }
5703 
5704  if (TransactionIdIsValid(twophase_xid))
5705  {
5706  xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
5707  xl_twophase.xid = twophase_xid;
5708  Assert(twophase_gid != NULL);
5709 
5710  if (XLogLogicalInfoActive())
5711  xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
5712  }
5713 
5714  if (TransactionIdIsValid(twophase_xid) && XLogLogicalInfoActive())
5715  {
5716  xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
5717  xl_dbinfo.dbId = MyDatabaseId;
5718  xl_dbinfo.tsId = MyDatabaseTableSpace;
5719  }
5720 
5721  /* dump transaction origin information only for abort prepared */
5723  TransactionIdIsValid(twophase_xid) &&
5725  {
5726  xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
5727 
5730  }
5731 
5732  if (xl_xinfo.xinfo != 0)
5733  info |= XLOG_XACT_HAS_INFO;
5734 
5735  /* Then include all the collected data into the abort record. */
5736 
5737  XLogBeginInsert();
5738 
5739  XLogRegisterData((char *) (&xlrec), MinSizeOfXactAbort);
5740 
5741  if (xl_xinfo.xinfo != 0)
5742  XLogRegisterData((char *) (&xl_xinfo), sizeof(xl_xinfo));