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-2021, 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. SECURITY_RESTRICTED_OPERATION contexts must not queue an
2098  * action that would run here, because that would bypass the sandbox.
2099  * Since closing cursors could queue trigger actions, triggers could open
2100  * cursors, etc, we have to keep looping until there's nothing left to do.
2101  */
2102  for (;;)
2103  {
2104  /*
2105  * Fire all currently pending deferred triggers.
2106  */
2108 
2109  /*
2110  * Close open portals (converting holdable ones into static portals).
2111  * If there weren't any, we are done ... otherwise loop back to check
2112  * if they queued deferred triggers. Lather, rinse, repeat.
2113  */
2114  if (!PreCommit_Portals(false))
2115  break;
2116  }
2117 
2118  /*
2119  * The remaining actions cannot call any user-defined code, so it's safe
2120  * to start shutting down within-transaction services. But note that most
2121  * of this stuff could still throw an error, which would switch us into
2122  * the transaction-abort path.
2123  */
2124 
2127 
2128  /* If we might have parallel workers, clean them up now. */
2129  if (IsInParallelMode())
2130  AtEOXact_Parallel(true);
2131 
2132  /* Shut down the deferred-trigger manager */
2133  AfterTriggerEndXact(true);
2134 
2135  /*
2136  * Let ON COMMIT management do its thing (must happen after closing
2137  * cursors, to avoid dangling-reference problems)
2138  */
2140 
2141  /*
2142  * Synchronize files that are created and not WAL-logged during this
2143  * transaction. This must happen before AtEOXact_RelationMap(), so that we
2144  * don't see committed-but-broken files after a crash.
2145  */
2146  smgrDoPendingSyncs(true, is_parallel_worker);
2147 
2148  /* close large objects before lower-level cleanup */
2149  AtEOXact_LargeObject(true);
2150 
2151  /*
2152  * Insert notifications sent by NOTIFY commands into the queue. This
2153  * should be late in the pre-commit sequence to minimize time spent
2154  * holding the notify-insertion lock. However, this could result in
2155  * creating a snapshot, so we must do it before serializable cleanup.
2156  */
2157  PreCommit_Notify();
2158 
2159  /*
2160  * Mark serializable transaction as complete for predicate locking
2161  * purposes. This should be done as late as we can put it and still allow
2162  * errors to be raised for failure patterns found at commit. This is not
2163  * appropriate in a parallel worker however, because we aren't committing
2164  * the leader's transaction and its serializable state will live on.
2165  */
2166  if (!is_parallel_worker)
2168 
2169  /* Prevent cancel/die interrupt while cleaning up */
2170  HOLD_INTERRUPTS();
2171 
2172  /* Commit updates to the relation map --- do this as late as possible */
2173  AtEOXact_RelationMap(true, is_parallel_worker);
2174 
2175  /*
2176  * set the current transaction state information appropriately during
2177  * commit processing
2178  */
2179  s->state = TRANS_COMMIT;
2180  s->parallelModeLevel = 0;
2181 
2182  if (!is_parallel_worker)
2183  {
2184  /*
2185  * We need to mark our XIDs as committed in pg_xact. This is where we
2186  * durably commit.
2187  */
2188  latestXid = RecordTransactionCommit();
2189  }
2190  else
2191  {
2192  /*
2193  * We must not mark our XID committed; the parallel leader is
2194  * responsible for that.
2195  */
2196  latestXid = InvalidTransactionId;
2197 
2198  /*
2199  * Make sure the leader will know about any WAL we wrote before it
2200  * commits.
2201  */
2203  }
2204 
2205  TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->lxid);
2206 
2207  /*
2208  * Let others know about no transaction in progress by me. Note that this
2209  * must be done _before_ releasing locks we hold and _after_
2210  * RecordTransactionCommit.
2211  */
2212  ProcArrayEndTransaction(MyProc, latestXid);
2213 
2214  /*
2215  * This is all post-commit cleanup. Note that if an error is raised here,
2216  * it's too late to abort the transaction. This should be just
2217  * noncritical resource releasing.
2218  *
2219  * The ordering of operations is not entirely random. The idea is:
2220  * release resources visible to other backends (eg, files, buffer pins);
2221  * then release locks; then release backend-local resources. We want to
2222  * release locks at the point where any backend waiting for us will see
2223  * our transaction as being fully cleaned up.
2224  *
2225  * Resources that can be associated with individual queries are handled by
2226  * the ResourceOwner mechanism. The other calls here are for backend-wide
2227  * state.
2228  */
2229 
2230  CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2231  : XACT_EVENT_COMMIT);
2232 
2235  true, true);
2236 
2237  /* Check we've released all buffer pins */
2238  AtEOXact_Buffers(true);
2239 
2240  /* Clean up the relation cache */
2241  AtEOXact_RelationCache(true);
2242 
2243  /*
2244  * Make catalog changes visible to all backends. This has to happen after
2245  * relcache references are dropped (see comments for
2246  * AtEOXact_RelationCache), but before locks are released (if anyone is
2247  * waiting for lock on a relation we've modified, we want them to know
2248  * about the catalog change before they start using the relation).
2249  */
2250  AtEOXact_Inval(true);
2251 
2253 
2256  true, true);
2259  true, true);
2260 
2261  /*
2262  * Likewise, dropping of files deleted during the transaction is best done
2263  * after releasing relcache and buffer pins. (This is not strictly
2264  * necessary during commit, since such pins should have been released
2265  * already, but this ordering is definitely critical during abort.) Since
2266  * this may take many seconds, also delay until after releasing locks.
2267  * Other backends will observe the attendant catalog changes and not
2268  * attempt to access affected files.
2269  */
2270  smgrDoPendingDeletes(true);
2271 
2272  AtCommit_Notify();
2273  AtEOXact_GUC(true, 1);
2274  AtEOXact_SPI(true);
2275  AtEOXact_Enum();
2277  AtEOXact_Namespace(true, is_parallel_worker);
2278  AtEOXact_SMgr();
2279  AtEOXact_Files(true);
2281  AtEOXact_HashTables(true);
2282  AtEOXact_PgStat(true, is_parallel_worker);
2283  AtEOXact_Snapshot(true, false);
2284  AtEOXact_ApplyLauncher(true);
2286 
2287  CurrentResourceOwner = NULL;
2289  s->curTransactionOwner = NULL;
2292 
2293  AtCommit_Memory();
2294 
2297  s->nestingLevel = 0;
2298  s->gucNestLevel = 0;
2299  s->childXids = NULL;
2300  s->nChildXids = 0;
2301  s->maxChildXids = 0;
2302 
2303  XactTopFullTransactionId = InvalidFullTransactionId;
2305 
2306  /*
2307  * done with commit processing, set current transaction state back to
2308  * default
2309  */
2310  s->state = TRANS_DEFAULT;
2311 
2313 }
2314 
2315 
2316 /*
2317  * PrepareTransaction
2318  *
2319  * NB: if you change this routine, better look at CommitTransaction too!
2320  */
2321 static void
2323 {
2326  GlobalTransaction gxact;
2327  TimestampTz prepared_at;
2328 
2330 
2331  ShowTransactionState("PrepareTransaction");
2332 
2333  /*
2334  * check the current transaction state
2335  */
2336  if (s->state != TRANS_INPROGRESS)
2337  elog(WARNING, "PrepareTransaction while in %s state",
2339  Assert(s->parent == NULL);
2340 
2341  /*
2342  * Do pre-commit processing that involves calling user-defined code, such
2343  * as triggers. Since closing cursors could queue trigger actions,
2344  * triggers could open cursors, etc, we have to keep looping until there's
2345  * nothing left to do.
2346  */
2347  for (;;)
2348  {
2349  /*
2350  * Fire all currently pending deferred triggers.
2351  */
2353 
2354  /*
2355  * Close open portals (converting holdable ones into static portals).
2356  * If there weren't any, we are done ... otherwise loop back to check
2357  * if they queued deferred triggers. Lather, rinse, repeat.
2358  */
2359  if (!PreCommit_Portals(true))
2360  break;
2361  }
2362 
2364 
2365  /*
2366  * The remaining actions cannot call any user-defined code, so it's safe
2367  * to start shutting down within-transaction services. But note that most
2368  * of this stuff could still throw an error, which would switch us into
2369  * the transaction-abort path.
2370  */
2371 
2372  /* Shut down the deferred-trigger manager */
2373  AfterTriggerEndXact(true);
2374 
2375  /*
2376  * Let ON COMMIT management do its thing (must happen after closing
2377  * cursors, to avoid dangling-reference problems)
2378  */
2380 
2381  /*
2382  * Synchronize files that are created and not WAL-logged during this
2383  * transaction. This must happen before EndPrepare(), so that we don't see
2384  * committed-but-broken files after a crash and COMMIT PREPARED.
2385  */
2386  smgrDoPendingSyncs(true, false);
2387 
2388  /* close large objects before lower-level cleanup */
2389  AtEOXact_LargeObject(true);
2390 
2391  /* NOTIFY requires no work at this point */
2392 
2393  /*
2394  * Mark serializable transaction as complete for predicate locking
2395  * purposes. This should be done as late as we can put it and still allow
2396  * errors to be raised for failure patterns found at commit.
2397  */
2399 
2400  /*
2401  * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2402  * this transaction. Having the prepared xact hold locks on another
2403  * backend's temp table seems a bad idea --- for instance it would prevent
2404  * the backend from exiting. There are other problems too, such as how to
2405  * clean up the source backend's local buffers and ON COMMIT state if the
2406  * prepared xact includes a DROP of a temp table.
2407  *
2408  * Other objects types, like functions, operators or extensions, share the
2409  * same restriction as they should not be created, locked or dropped as
2410  * this can mess up with this session or even a follow-up session trying
2411  * to use the same temporary namespace.
2412  *
2413  * We must check this after executing any ON COMMIT actions, because they
2414  * might still access a temp relation.
2415  *
2416  * XXX In principle this could be relaxed to allow some useful special
2417  * cases, such as a temp table created and dropped all within the
2418  * transaction. That seems to require much more bookkeeping though.
2419  */
2421  ereport(ERROR,
2422  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2423  errmsg("cannot PREPARE a transaction that has operated on temporary objects")));
2424 
2425  /*
2426  * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2427  * supported if we added cleanup logic to twophase.c, but for now it
2428  * doesn't seem worth the trouble.
2429  */
2431  ereport(ERROR,
2432  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2433  errmsg("cannot PREPARE a transaction that has exported snapshots")));
2434 
2435  /*
2436  * Don't allow PREPARE but for transaction that has/might kill logical
2437  * replication workers.
2438  */
2440  ereport(ERROR,
2441  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2442  errmsg("cannot PREPARE a transaction that has manipulated logical replication workers")));
2443 
2444  /* Prevent cancel/die interrupt while cleaning up */
2445  HOLD_INTERRUPTS();
2446 
2447  /*
2448  * set the current transaction state information appropriately during
2449  * prepare processing
2450  */
2451  s->state = TRANS_PREPARE;
2452 
2453  prepared_at = GetCurrentTimestamp();
2454 
2455  /* Tell bufmgr and smgr to prepare for commit */
2456  BufmgrCommit();
2457 
2458  /*
2459  * Reserve the GID for this transaction. This could fail if the requested
2460  * GID is invalid or already in use.
2461  */
2462  gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2463  GetUserId(), MyDatabaseId);
2464  prepareGID = NULL;
2465 
2466  /*
2467  * Collect data for the 2PC state file. Note that in general, no actual
2468  * state change should happen in the called modules during this step,
2469  * since it's still possible to fail before commit, and in that case we
2470  * want transaction abort to be able to clean up. (In particular, the
2471  * AtPrepare routines may error out if they find cases they cannot
2472  * handle.) State cleanup should happen in the PostPrepare routines
2473  * below. However, some modules can go ahead and clear state here because
2474  * they wouldn't do anything with it during abort anyway.
2475  *
2476  * Note: because the 2PC state file records will be replayed in the same
2477  * order they are made, the order of these calls has to match the order in
2478  * which we want things to happen during COMMIT PREPARED or ROLLBACK
2479  * PREPARED; in particular, pay attention to whether things should happen
2480  * before or after releasing the transaction's locks.
2481  */
2482  StartPrepare(gxact);
2483 
2484  AtPrepare_Notify();
2485  AtPrepare_Locks();
2487  AtPrepare_PgStat();
2490 
2491  /*
2492  * Here is where we really truly prepare.
2493  *
2494  * We have to record transaction prepares even if we didn't make any
2495  * updates, because the transaction manager might get confused if we lose
2496  * a global transaction.
2497  */
2498  EndPrepare(gxact);
2499 
2500  /*
2501  * Now we clean up backend-internal state and release internal resources.
2502  */
2503 
2504  /* Reset XactLastRecEnd until the next transaction writes something */
2505  XactLastRecEnd = 0;
2506 
2507  /*
2508  * Let others know about no transaction in progress by me. This has to be
2509  * done *after* the prepared transaction has been marked valid, else
2510  * someone may think it is unlocked and recyclable.
2511  */
2513 
2514  /*
2515  * In normal commit-processing, this is all non-critical post-transaction
2516  * cleanup. When the transaction is prepared, however, it's important
2517  * that the locks and other per-backend resources are transferred to the
2518  * prepared transaction's PGPROC entry. Note that if an error is raised
2519  * here, it's too late to abort the transaction. XXX: This probably should
2520  * be in a critical section, to force a PANIC if any of this fails, but
2521  * that cure could be worse than the disease.
2522  */
2523 
2525 
2528  true, true);
2529 
2530  /* Check we've released all buffer pins */
2531  AtEOXact_Buffers(true);
2532 
2533  /* Clean up the relation cache */
2534  AtEOXact_RelationCache(true);
2535 
2536  /* notify doesn't need a postprepare call */
2537 
2539 
2541 
2542  PostPrepare_smgr();
2543 
2544  PostPrepare_MultiXact(xid);
2545 
2546  PostPrepare_Locks(xid);
2548 
2551  true, true);
2554  true, true);
2555 
2556  /*
2557  * Allow another backend to finish the transaction. After
2558  * PostPrepare_Twophase(), the transaction is completely detached from our
2559  * backend. The rest is just non-critical cleanup of backend-local state.
2560  */
2562 
2563  /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2564  AtEOXact_GUC(true, 1);
2565  AtEOXact_SPI(true);
2566  AtEOXact_Enum();
2568  AtEOXact_Namespace(true, false);
2569  AtEOXact_SMgr();
2570  AtEOXact_Files(true);
2572  AtEOXact_HashTables(true);
2573  /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2574  AtEOXact_Snapshot(true, true);
2576 
2577  CurrentResourceOwner = NULL;
2579  s->curTransactionOwner = NULL;
2582 
2583  AtCommit_Memory();
2584 
2587  s->nestingLevel = 0;
2588  s->gucNestLevel = 0;
2589  s->childXids = NULL;
2590  s->nChildXids = 0;
2591  s->maxChildXids = 0;
2592 
2593  XactTopFullTransactionId = InvalidFullTransactionId;
2595 
2596  /*
2597  * done with 1st phase commit processing, set current transaction state
2598  * back to default
2599  */
2600  s->state = TRANS_DEFAULT;
2601 
2603 }
2604 
2605 
2606 /*
2607  * AbortTransaction
2608  */
2609 static void
2611 {
2613  TransactionId latestXid;
2614  bool is_parallel_worker;
2615 
2616  /* Prevent cancel/die interrupt while cleaning up */
2617  HOLD_INTERRUPTS();
2618 
2619  /* Make sure we have a valid memory context and resource owner */
2620  AtAbort_Memory();
2622 
2623  /*
2624  * Release any LW locks we might be holding as quickly as possible.
2625  * (Regular locks, however, must be held till we finish aborting.)
2626  * Releasing LW locks is critical since we might try to grab them again
2627  * while cleaning up!
2628  */
2629  LWLockReleaseAll();
2630 
2631  /* Clear wait information and command progress indicator */
2634 
2635  /* Clean up buffer I/O and buffer context locks, too */
2636  AbortBufferIO();
2637  UnlockBuffers();
2638 
2639  /* Reset WAL record construction state */
2641 
2642  /* Cancel condition variable sleep */
2644 
2645  /*
2646  * Also clean up any open wait for lock, since the lock manager will choke
2647  * if we try to wait for another lock before doing this.
2648  */
2649  LockErrorCleanup();
2650 
2651  /*
2652  * If any timeout events are still active, make sure the timeout interrupt
2653  * is scheduled. This covers possible loss of a timeout interrupt due to
2654  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2655  * We delay this till after LockErrorCleanup so that we don't uselessly
2656  * reschedule lock or deadlock check timeouts.
2657  */
2659 
2660  /*
2661  * Re-enable signals, in case we got here by longjmp'ing out of a signal
2662  * handler. We do this fairly early in the sequence so that the timeout
2663  * infrastructure will be functional if needed while aborting.
2664  */
2666 
2667  /*
2668  * check the current transaction state
2669  */
2670  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2671  if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2672  elog(WARNING, "AbortTransaction while in %s state",
2674  Assert(s->parent == NULL);
2675 
2676  /*
2677  * set the current transaction state information appropriately during the
2678  * abort processing
2679  */
2680  s->state = TRANS_ABORT;
2681 
2682  /*
2683  * Reset user ID which might have been changed transiently. We need this
2684  * to clean up in case control escaped out of a SECURITY DEFINER function
2685  * or other local change of CurrentUserId; therefore, the prior value of
2686  * SecurityRestrictionContext also needs to be restored.
2687  *
2688  * (Note: it is not necessary to restore session authorization or role
2689  * settings here because those can only be changed via GUC, and GUC will
2690  * take care of rolling them back if need be.)
2691  */
2693 
2694  /* Forget about any active REINDEX. */
2696 
2697  /* Reset logical streaming state. */
2699 
2700  /* If in parallel mode, clean up workers and exit parallel mode. */
2701  if (IsInParallelMode())
2702  {
2703  AtEOXact_Parallel(false);
2704  s->parallelModeLevel = 0;
2705  }
2706 
2707  /*
2708  * do abort processing
2709  */
2710  AfterTriggerEndXact(false); /* 'false' means it's abort */
2711  AtAbort_Portals();
2712  smgrDoPendingSyncs(false, is_parallel_worker);
2713  AtEOXact_LargeObject(false);
2714  AtAbort_Notify();
2715  AtEOXact_RelationMap(false, is_parallel_worker);
2716  AtAbort_Twophase();
2717 
2718  /*
2719  * Advertise the fact that we aborted in pg_xact (assuming that we got as
2720  * far as assigning an XID to advertise). But if we're inside a parallel
2721  * worker, skip this; the user backend must be the one to write the abort
2722  * record.
2723  */
2724  if (!is_parallel_worker)
2725  latestXid = RecordTransactionAbort(false);
2726  else
2727  {
2728  latestXid = InvalidTransactionId;
2729 
2730  /*
2731  * Since the parallel leader won't get our value of XactLastRecEnd in
2732  * this case, we nudge WAL-writer ourselves in this case. See related
2733  * comments in RecordTransactionAbort for why this matters.
2734  */
2736  }
2737 
2738  TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->lxid);
2739 
2740  /*
2741  * Let others know about no transaction in progress by me. Note that this
2742  * must be done _before_ releasing locks we hold and _after_
2743  * RecordTransactionAbort.
2744  */
2745  ProcArrayEndTransaction(MyProc, latestXid);
2746 
2747  /*
2748  * Post-abort cleanup. See notes in CommitTransaction() concerning
2749  * ordering. We can skip all of it if the transaction failed before
2750  * creating a resource owner.
2751  */
2752  if (TopTransactionResourceOwner != NULL)
2753  {
2754  if (is_parallel_worker)
2756  else
2758 
2761  false, true);
2762  AtEOXact_Buffers(false);
2763  AtEOXact_RelationCache(false);
2764  AtEOXact_Inval(false);
2768  false, true);
2771  false, true);
2772  smgrDoPendingDeletes(false);
2773 
2774  AtEOXact_GUC(false, 1);
2775  AtEOXact_SPI(false);
2776  AtEOXact_Enum();
2778  AtEOXact_Namespace(false, is_parallel_worker);
2779  AtEOXact_SMgr();
2780  AtEOXact_Files(false);
2782  AtEOXact_HashTables(false);
2783  AtEOXact_PgStat(false, is_parallel_worker);
2784  AtEOXact_ApplyLauncher(false);
2786  }
2787 
2788  /*
2789  * State remains TRANS_ABORT until CleanupTransaction().
2790  */
2792 }
2793 
2794 /*
2795  * CleanupTransaction
2796  */
2797 static void
2799 {
2801 
2802  /*
2803  * State should still be TRANS_ABORT from AbortTransaction().
2804  */
2805  if (s->state != TRANS_ABORT)
2806  elog(FATAL, "CleanupTransaction: unexpected state %s",
2808 
2809  /*
2810  * do abort cleanup processing
2811  */
2812  AtCleanup_Portals(); /* now safe to release portal memory */
2813  AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
2814 
2815  CurrentResourceOwner = NULL; /* and resource owner */
2818  s->curTransactionOwner = NULL;
2821 
2822  AtCleanup_Memory(); /* and transaction memory */
2823 
2826  s->nestingLevel = 0;
2827  s->gucNestLevel = 0;
2828  s->childXids = NULL;
2829  s->nChildXids = 0;
2830  s->maxChildXids = 0;
2831  s->parallelModeLevel = 0;
2832 
2833  XactTopFullTransactionId = InvalidFullTransactionId;
2835 
2836  /*
2837  * done with abort processing, set current transaction state back to
2838  * default
2839  */
2840  s->state = TRANS_DEFAULT;
2841 }
2842 
2843 /*
2844  * StartTransactionCommand
2845  */
2846 void
2848 {
2850 
2851  switch (s->blockState)
2852  {
2853  /*
2854  * if we aren't in a transaction block, we just do our usual start
2855  * transaction.
2856  */
2857  case TBLOCK_DEFAULT:
2858  StartTransaction();
2860  break;
2861 
2862  /*
2863  * We are somewhere in a transaction block or subtransaction and
2864  * about to start a new command. For now we do nothing, but
2865  * someday we may do command-local resource initialization. (Note
2866  * that any needed CommandCounterIncrement was done by the
2867  * previous CommitTransactionCommand.)
2868  */
2869  case TBLOCK_INPROGRESS:
2871  case TBLOCK_SUBINPROGRESS:
2872  break;
2873 
2874  /*
2875  * Here we are in a failed transaction block (one of the commands
2876  * caused an abort) so we do nothing but remain in the abort
2877  * state. Eventually we will get a ROLLBACK command which will
2878  * get us out of this state. (It is up to other code to ensure
2879  * that no commands other than ROLLBACK will be processed in these
2880  * states.)
2881  */
2882  case TBLOCK_ABORT:
2883  case TBLOCK_SUBABORT:
2884  break;
2885 
2886  /* These cases are invalid. */
2887  case TBLOCK_STARTED:
2888  case TBLOCK_BEGIN:
2890  case TBLOCK_SUBBEGIN:
2891  case TBLOCK_END:
2892  case TBLOCK_SUBRELEASE:
2893  case TBLOCK_SUBCOMMIT:
2894  case TBLOCK_ABORT_END:
2895  case TBLOCK_SUBABORT_END:
2896  case TBLOCK_ABORT_PENDING:
2898  case TBLOCK_SUBRESTART:
2900  case TBLOCK_PREPARE:
2901  elog(ERROR, "StartTransactionCommand: unexpected state %s",
2903  break;
2904  }
2905 
2906  /*
2907  * We must switch to CurTransactionContext before returning. This is
2908  * already done if we called StartTransaction, otherwise not.
2909  */
2910  Assert(CurTransactionContext != NULL);
2912 }
2913 
2914 
2915 /*
2916  * Simple system for saving and restoring transaction characteristics
2917  * (isolation level, read only, deferrable). We need this for transaction
2918  * chaining, so that we can set the characteristics of the new transaction to
2919  * be the same as the previous one. (We need something like this because the
2920  * GUC system resets the characteristics at transaction end, so for example
2921  * just skipping the reset in StartTransaction() won't work.)
2922  */
2924 static bool save_XactReadOnly;
2926 
2927 void
2929 {
2933 }
2934 
2935 void
2937 {
2941 }
2942 
2943 
2944 /*
2945  * CommitTransactionCommand
2946  */
2947 void
2949 {
2951 
2952  if (s->chain)
2954 
2955  switch (s->blockState)
2956  {
2957  /*
2958  * These shouldn't happen. TBLOCK_DEFAULT means the previous
2959  * StartTransactionCommand didn't set the STARTED state
2960  * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
2961  * by EndParallelWorkerTransaction(), not this function.
2962  */
2963  case TBLOCK_DEFAULT:
2965  elog(FATAL, "CommitTransactionCommand: unexpected state %s",
2967  break;
2968 
2969  /*
2970  * If we aren't in a transaction block, just do our usual
2971  * transaction commit, and return to the idle state.
2972  */
2973  case TBLOCK_STARTED:
2976  break;
2977 
2978  /*
2979  * We are completing a "BEGIN TRANSACTION" command, so we change
2980  * to the "transaction block in progress" state and return. (We
2981  * assume the BEGIN did nothing to the database, so we need no
2982  * CommandCounterIncrement.)
2983  */
2984  case TBLOCK_BEGIN:
2986  break;
2987 
2988  /*
2989  * This is the case when we have finished executing a command
2990  * someplace within a transaction block. We increment the command
2991  * counter and return.
2992  */
2993  case TBLOCK_INPROGRESS:
2995  case TBLOCK_SUBINPROGRESS:
2997  break;
2998 
2999  /*
3000  * We are completing a "COMMIT" command. Do it and return to the
3001  * idle state.
3002  */
3003  case TBLOCK_END:
3006  if (s->chain)
3007  {
3008  StartTransaction();
3010  s->chain = false;
3012  }
3013  break;
3014 
3015  /*
3016  * Here we are in the middle of a transaction block but one of the
3017  * commands caused an abort so we do nothing but remain in the
3018  * abort state. Eventually we will get a ROLLBACK command.
3019  */
3020  case TBLOCK_ABORT:
3021  case TBLOCK_SUBABORT:
3022  break;
3023 
3024  /*
3025  * Here we were in an aborted transaction block and we just got
3026  * the ROLLBACK command from the user, so clean up the
3027  * already-aborted transaction and return to the idle state.
3028  */
3029  case TBLOCK_ABORT_END:
3032  if (s->chain)
3033  {
3034  StartTransaction();
3036  s->chain = false;
3038  }
3039  break;
3040 
3041  /*
3042  * Here we were in a perfectly good transaction block but the user
3043  * told us to ROLLBACK anyway. We have to abort the transaction
3044  * and then clean up.
3045  */
3046  case TBLOCK_ABORT_PENDING:
3047  AbortTransaction();
3050  if (s->chain)
3051  {
3052  StartTransaction();
3054  s->chain = false;
3056  }
3057  break;
3058 
3059  /*
3060  * We are completing a "PREPARE TRANSACTION" command. Do it and
3061  * return to the idle state.
3062  */
3063  case TBLOCK_PREPARE:
3066  break;
3067 
3068  /*
3069  * We were just issued a SAVEPOINT inside a transaction block.
3070  * Start a subtransaction. (DefineSavepoint already did
3071  * PushTransaction, so as to have someplace to put the SUBBEGIN
3072  * state.)
3073  */
3074  case TBLOCK_SUBBEGIN:
3077  break;
3078 
3079  /*
3080  * We were issued a RELEASE command, so we end the current
3081  * subtransaction and return to the parent transaction. The parent
3082  * might be ended too, so repeat till we find an INPROGRESS
3083  * transaction or subtransaction.
3084  */
3085  case TBLOCK_SUBRELEASE:
3086  do
3087  {
3089  s = CurrentTransactionState; /* changed by pop */
3090  } while (s->blockState == TBLOCK_SUBRELEASE);
3091 
3094  break;
3095 
3096  /*
3097  * We were issued a COMMIT, so we end the current subtransaction
3098  * hierarchy and perform final commit. We do this by rolling up
3099  * any subtransactions into their parent, which leads to O(N^2)
3100  * operations with respect to resource owners - this isn't that
3101  * bad until we approach a thousands of savepoints but is
3102  * necessary for correctness should after triggers create new
3103  * resource owners.
3104  */
3105  case TBLOCK_SUBCOMMIT:
3106  do
3107  {
3109  s = CurrentTransactionState; /* changed by pop */
3110  } while (s->blockState == TBLOCK_SUBCOMMIT);
3111  /* If we had a COMMIT command, finish off the main xact too */
3112  if (s->blockState == TBLOCK_END)
3113  {
3114  Assert(s->parent == NULL);
3117  }
3118  else if (s->blockState == TBLOCK_PREPARE)
3119  {
3120  Assert(s->parent == NULL);
3123  }
3124  else
3125  elog(ERROR, "CommitTransactionCommand: unexpected state %s",
3127  break;
3128 
3129  /*
3130  * The current already-failed subtransaction is ending due to a
3131  * ROLLBACK or ROLLBACK TO command, so pop it and recursively
3132  * examine the parent (which could be in any of several states).
3133  */
3134  case TBLOCK_SUBABORT_END:
3137  break;
3138 
3139  /*
3140  * As above, but it's not dead yet, so abort first.
3141  */
3146  break;
3147 
3148  /*
3149  * The current subtransaction is the target of a ROLLBACK TO
3150  * command. Abort and pop it, then start a new subtransaction
3151  * with the same name.
3152  */
3153  case TBLOCK_SUBRESTART:
3154  {
3155  char *name;
3156  int savepointLevel;
3157 
3158  /* save name and keep Cleanup from freeing it */
3159  name = s->name;
3160  s->name = NULL;
3161  savepointLevel = s->savepointLevel;
3162 
3165 
3166  DefineSavepoint(NULL);
3167  s = CurrentTransactionState; /* changed by push */
3168  s->name = name;
3170 
3171  /* This is the same as TBLOCK_SUBBEGIN case */
3175  }
3176  break;
3177 
3178  /*
3179  * Same as above, but the subtransaction had already failed, so we
3180  * don't need AbortSubTransaction.
3181  */
3183  {
3184  char *name;
3185  int savepointLevel;
3186 
3187  /* save name and keep Cleanup from freeing it */
3188  name = s->name;
3189  s->name = NULL;
3190  savepointLevel = s->savepointLevel;
3191 
3193 
3194  DefineSavepoint(NULL);
3195  s = CurrentTransactionState; /* changed by push */
3196  s->name = name;
3198 
3199  /* This is the same as TBLOCK_SUBBEGIN case */
3203  }
3204  break;
3205  }
3206 }
3207 
3208 /*
3209  * AbortCurrentTransaction
3210  */
3211 void
3213 {
3215 
3216  switch (s->blockState)
3217  {
3218  case TBLOCK_DEFAULT:
3219  if (s->state == TRANS_DEFAULT)
3220  {
3221  /* we are idle, so nothing to do */
3222  }
3223  else
3224  {
3225  /*
3226  * We can get here after an error during transaction start
3227  * (state will be TRANS_START). Need to clean up the
3228  * incompletely started transaction. First, adjust the
3229  * low-level state to suppress warning message from
3230  * AbortTransaction.
3231  */
3232  if (s->state == TRANS_START)
3233  s->state = TRANS_INPROGRESS;
3234  AbortTransaction();
3236  }
3237  break;
3238 
3239  /*
3240  * If we aren't in a transaction block, we just do the basic abort
3241  * & cleanup transaction. For this purpose, we treat an implicit
3242  * transaction block as if it were a simple statement.
3243  */
3244  case TBLOCK_STARTED:
3246  AbortTransaction();
3249  break;
3250 
3251  /*
3252  * If we are in TBLOCK_BEGIN it means something screwed up right
3253  * after reading "BEGIN TRANSACTION". We assume that the user
3254  * will interpret the error as meaning the BEGIN failed to get him
3255  * into a transaction block, so we should abort and return to idle
3256  * state.
3257  */
3258  case TBLOCK_BEGIN:
3259  AbortTransaction();
3262  break;
3263 
3264  /*
3265  * We are somewhere in a transaction block and we've gotten a
3266  * failure, so we abort the transaction and set up the persistent
3267  * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3268  */
3269  case TBLOCK_INPROGRESS:
3271  AbortTransaction();
3272  s->blockState = TBLOCK_ABORT;
3273  /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
3274  break;
3275 
3276  /*
3277  * Here, we failed while trying to COMMIT. Clean up the
3278  * transaction and return to idle state (we do not want to stay in
3279  * the transaction).
3280  */
3281  case TBLOCK_END:
3282  AbortTransaction();
3285  break;
3286 
3287  /*
3288  * Here, we are already in an aborted transaction state and are
3289  * waiting for a ROLLBACK, but for some reason we failed again! So
3290  * we just remain in the abort state.
3291  */
3292  case TBLOCK_ABORT:
3293  case TBLOCK_SUBABORT:
3294  break;
3295 
3296  /*
3297  * We are in a failed transaction and we got the ROLLBACK command.
3298  * We have already aborted, we just need to cleanup and go to idle
3299  * state.
3300  */
3301  case TBLOCK_ABORT_END:
3304  break;
3305 
3306  /*
3307  * We are in a live transaction and we got a ROLLBACK command.
3308  * Abort, cleanup, go to idle state.
3309  */
3310  case TBLOCK_ABORT_PENDING:
3311  AbortTransaction();
3314  break;
3315 
3316  /*
3317  * Here, we failed while trying to PREPARE. Clean up the
3318  * transaction and return to idle state (we do not want to stay in
3319  * the transaction).
3320  */
3321  case TBLOCK_PREPARE:
3322  AbortTransaction();
3325  break;
3326 
3327  /*
3328  * We got an error inside a subtransaction. Abort just the
3329  * subtransaction, and go to the persistent SUBABORT state until
3330  * we get ROLLBACK.
3331  */
3332  case TBLOCK_SUBINPROGRESS:
3335  break;
3336 
3337  /*
3338  * If we failed while trying to create a subtransaction, clean up
3339  * the broken subtransaction and abort the parent. The same
3340  * applies if we get a failure while ending a subtransaction.
3341  */
3342  case TBLOCK_SUBBEGIN:
3343  case TBLOCK_SUBRELEASE:
3344  case TBLOCK_SUBCOMMIT:
3346  case TBLOCK_SUBRESTART:
3350  break;
3351 
3352  /*
3353  * Same as above, except the Abort() was already done.
3354  */
3355  case TBLOCK_SUBABORT_END:
3359  break;
3360  }
3361 }
3362 
3363 /*
3364  * PreventInTransactionBlock
3365  *
3366  * This routine is to be called by statements that must not run inside
3367  * a transaction block, typically because they have non-rollback-able
3368  * side effects or do internal commits.
3369  *
3370  * If we have already started a transaction block, issue an error; also issue
3371  * an error if we appear to be running inside a user-defined function (which
3372  * could issue more commands and possibly cause a failure after the statement
3373  * completes). Subtransactions are verboten too.
3374  *
3375  * isTopLevel: passed down from ProcessUtility to determine whether we are
3376  * inside a function. (We will always fail if this is false, but it's
3377  * convenient to centralize the check here instead of making callers do it.)
3378  * stmtType: statement type name, for error messages.
3379  */
3380 void
3381 PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
3382 {
3383  /*
3384  * xact block already started?
3385  */
3386  if (IsTransactionBlock())
3387  ereport(ERROR,
3388  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3389  /* translator: %s represents an SQL statement name */
3390  errmsg("%s cannot run inside a transaction block",
3391  stmtType)));
3392 
3393  /*
3394  * subtransaction?
3395  */
3396  if (IsSubTransaction())
3397  ereport(ERROR,
3398  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3399  /* translator: %s represents an SQL statement name */
3400  errmsg("%s cannot run inside a subtransaction",
3401  stmtType)));
3402 
3403  /*
3404  * inside a function call?
3405  */
3406  if (!isTopLevel)
3407  ereport(ERROR,
3408  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3409  /* translator: %s represents an SQL statement name */
3410  errmsg("%s cannot be executed from a function", stmtType)));
3411 
3412  /* If we got past IsTransactionBlock test, should be in default state */
3413  if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3414  CurrentTransactionState->blockState != TBLOCK_STARTED)
3415  elog(FATAL, "cannot prevent transaction chain");
3416  /* all okay */
3417 }
3418 
3419 /*
3420  * WarnNoTransactionBlock
3421  * RequireTransactionBlock
3422  *
3423  * These two functions allow for warnings or errors if a command is executed
3424  * outside of a transaction block. This is useful for commands that have no
3425  * effects that persist past transaction end (and so calling them outside a
3426  * transaction block is presumably an error). DECLARE CURSOR is an example.
3427  * While top-level transaction control commands (BEGIN/COMMIT/ABORT) and SET
3428  * that have no effect issue warnings, all other no-effect commands generate
3429  * errors.
3430  *
3431  * If we appear to be running inside a user-defined function, we do not
3432  * issue anything, since the function could issue more commands that make
3433  * use of the current statement's results. Likewise subtransactions.
3434  * Thus these are inverses for PreventInTransactionBlock.
3435  *
3436  * isTopLevel: passed down from ProcessUtility to determine whether we are
3437  * inside a function.
3438  * stmtType: statement type name, for warning or error messages.
3439  */
3440 void
3441 WarnNoTransactionBlock(bool isTopLevel, const char *stmtType)
3442 {
3443  CheckTransactionBlock(isTopLevel, false, stmtType);
3444 }
3445 
3446 void
3447 RequireTransactionBlock(bool isTopLevel, const char *stmtType)
3448 {
3449  CheckTransactionBlock(isTopLevel, true, stmtType);
3450 }
3451 
3452 /*
3453  * This is the implementation of the above two.
3454  */
3455 static void
3456 CheckTransactionBlock(bool isTopLevel, bool throwError, const char *stmtType)
3457 {
3458  /*
3459  * xact block already started?
3460  */
3461  if (IsTransactionBlock())
3462  return;
3463 
3464  /*
3465  * subtransaction?
3466  */
3467  if (IsSubTransaction())
3468  return;
3469 
3470  /*
3471  * inside a function call?
3472  */
3473  if (!isTopLevel)
3474  return;
3475 
3476  ereport(throwError ? ERROR : WARNING,
3477  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3478  /* translator: %s represents an SQL statement name */
3479  errmsg("%s can only be used in transaction blocks",
3480  stmtType)));
3481 }
3482 
3483 /*
3484  * IsInTransactionBlock
3485  *
3486  * This routine is for statements that need to behave differently inside
3487  * a transaction block than when running as single commands. ANALYZE is
3488  * currently the only example.
3489  *
3490  * isTopLevel: passed down from ProcessUtility to determine whether we are
3491  * inside a function.
3492  */
3493 bool
3494 IsInTransactionBlock(bool isTopLevel)
3495 {
3496  /*
3497  * Return true on same conditions that would make
3498  * PreventInTransactionBlock error out
3499  */
3500  if (IsTransactionBlock())
3501  return true;
3502 
3503  if (IsSubTransaction())
3504  return true;
3505 
3506  if (!isTopLevel)
3507  return true;
3508 
3509  if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3510  CurrentTransactionState->blockState != TBLOCK_STARTED)
3511  return true;
3512 
3513  return false;
3514 }
3515 
3516 
3517 /*
3518  * Register or deregister callback functions for start- and end-of-xact
3519  * operations.
3520  *
3521  * These functions are intended for use by dynamically loaded modules.
3522  * For built-in modules we generally just hardwire the appropriate calls
3523  * (mainly because it's easier to control the order that way, where needed).
3524  *
3525  * At transaction end, the callback occurs post-commit or post-abort, so the
3526  * callback functions can only do noncritical cleanup.
3527  */
3528 void
3530 {
3531  XactCallbackItem *item;
3532 
3533  item = (XactCallbackItem *)
3535  item->callback = callback;
3536  item->arg = arg;
3537  item->next = Xact_callbacks;
3538  Xact_callbacks = item;
3539 }
3540 
3541 void
3543 {
3544  XactCallbackItem *item;
3545  XactCallbackItem *prev;
3546 
3547  prev = NULL;
3548  for (item = Xact_callbacks; item; prev = item, item = item->next)
3549  {
3550  if (item->callback == callback && item->arg == arg)
3551  {
3552  if (prev)
3553  prev->next = item->next;
3554  else
3555  Xact_callbacks = item->next;
3556  pfree(item);
3557  break;
3558  }
3559  }
3560 }
3561 
3562 static void
3564 {
3565  XactCallbackItem *item;
3566 
3567  for (item = Xact_callbacks; item; item = item->next)
3568  item->callback(event, item->arg);
3569 }
3570 
3571 
3572 /*
3573  * Register or deregister callback functions for start- and end-of-subxact
3574  * operations.
3575  *
3576  * Pretty much same as above, but for subtransaction events.
3577  *
3578  * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3579  * so the callback functions can only do noncritical cleanup. At
3580  * subtransaction start, the callback is called when the subtransaction has
3581  * finished initializing.
3582  */
3583 void
3585 {
3586  SubXactCallbackItem *item;
3587 
3588  item = (SubXactCallbackItem *)
3590  item->callback = callback;
3591  item->arg = arg;
3592  item->next = SubXact_callbacks;
3593  SubXact_callbacks = item;
3594 }
3595 
3596 void
3598 {
3599  SubXactCallbackItem *item;
3600  SubXactCallbackItem *prev;
3601 
3602  prev = NULL;
3603  for (item = SubXact_callbacks; item; prev = item, item = item->next)
3604  {
3605  if (item->callback == callback && item->arg == arg)
3606  {
3607  if (prev)
3608  prev->next = item->next;
3609  else
3610  SubXact_callbacks = item->next;
3611  pfree(item);
3612  break;
3613  }
3614  }
3615 }
3616 
3617 static void
3619  SubTransactionId mySubid,
3620  SubTransactionId parentSubid)
3621 {
3622  SubXactCallbackItem *item;
3623 
3624  for (item = SubXact_callbacks; item; item = item->next)
3625  item->callback(event, mySubid, parentSubid, item->arg);
3626 }
3627 
3628 
3629 /* ----------------------------------------------------------------
3630  * transaction block support
3631  * ----------------------------------------------------------------
3632  */
3633 
3634 /*
3635  * BeginTransactionBlock
3636  * This executes a BEGIN command.
3637  */
3638 void
3640 {
3642 
3643  switch (s->blockState)
3644  {
3645  /*
3646  * We are not inside a transaction block, so allow one to begin.
3647  */
3648  case TBLOCK_STARTED:
3649  s->blockState = TBLOCK_BEGIN;
3650  break;
3651 
3652  /*
3653  * BEGIN converts an implicit transaction block to a regular one.
3654  * (Note that we allow this even if we've already done some
3655  * commands, which is a bit odd but matches historical practice.)
3656  */
3658  s->blockState = TBLOCK_BEGIN;
3659  break;
3660 
3661  /*
3662  * Already a transaction block in progress.
3663  */
3664  case TBLOCK_INPROGRESS:
3666  case TBLOCK_SUBINPROGRESS:
3667  case TBLOCK_ABORT:
3668  case TBLOCK_SUBABORT:
3669  ereport(WARNING,
3670  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3671  errmsg("there is already a transaction in progress")));
3672  break;
3673 
3674  /* These cases are invalid. */
3675  case TBLOCK_DEFAULT:
3676  case TBLOCK_BEGIN:
3677  case TBLOCK_SUBBEGIN:
3678  case TBLOCK_END:
3679  case TBLOCK_SUBRELEASE:
3680  case TBLOCK_SUBCOMMIT:
3681  case TBLOCK_ABORT_END:
3682  case TBLOCK_SUBABORT_END:
3683  case TBLOCK_ABORT_PENDING:
3685  case TBLOCK_SUBRESTART:
3687  case TBLOCK_PREPARE:
3688  elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3690  break;
3691  }
3692 }
3693 
3694 /*
3695  * PrepareTransactionBlock
3696  * This executes a PREPARE command.
3697  *
3698  * Since PREPARE may actually do a ROLLBACK, the result indicates what
3699  * happened: true for PREPARE, false for ROLLBACK.
3700  *
3701  * Note that we don't actually do anything here except change blockState.
3702  * The real work will be done in the upcoming PrepareTransaction().
3703  * We do it this way because it's not convenient to change memory context,
3704  * resource owner, etc while executing inside a Portal.
3705  */
3706 bool
3707 PrepareTransactionBlock(const char *gid)
3708 {
3709  TransactionState s;
3710  bool result;
3711 
3712  /* Set up to commit the current transaction */
3713  result = EndTransactionBlock(false);
3714 
3715  /* If successful, change outer tblock state to PREPARE */
3716  if (result)
3717  {
3719 
3720  while (s->parent != NULL)
3721  s = s->parent;
3722 
3723  if (s->blockState == TBLOCK_END)
3724  {
3725  /* Save GID where PrepareTransaction can find it again */
3727 
3729  }
3730  else
3731  {
3732  /*
3733  * ignore case where we are not in a transaction;
3734  * EndTransactionBlock already issued a warning.
3735  */
3738  /* Don't send back a PREPARE result tag... */
3739  result = false;
3740  }
3741  }
3742 
3743  return result;
3744 }
3745 
3746 /*
3747  * EndTransactionBlock
3748  * This executes a COMMIT command.
3749  *
3750  * Since COMMIT may actually do a ROLLBACK, the result indicates what
3751  * happened: true for COMMIT, false for ROLLBACK.
3752  *
3753  * Note that we don't actually do anything here except change blockState.
3754  * The real work will be done in the upcoming CommitTransactionCommand().
3755  * We do it this way because it's not convenient to change memory context,
3756  * resource owner, etc while executing inside a Portal.
3757  */
3758 bool
3760 {
3762  bool result = false;
3763 
3764  switch (s->blockState)
3765  {
3766  /*
3767  * We are in a transaction block, so tell CommitTransactionCommand
3768  * to COMMIT.
3769  */
3770  case TBLOCK_INPROGRESS:
3771  s->blockState = TBLOCK_END;
3772  result = true;
3773  break;
3774 
3775  /*
3776  * We are in an implicit transaction block. If AND CHAIN was
3777  * specified, error. Otherwise commit, but issue a warning
3778  * because there was no explicit BEGIN before this.
3779  */
3781  if (chain)
3782  ereport(ERROR,
3783  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3784  /* translator: %s represents an SQL statement name */
3785  errmsg("%s can only be used in transaction blocks",
3786  "COMMIT AND CHAIN")));
3787  else
3788  ereport(WARNING,
3789  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3790  errmsg("there is no transaction in progress")));
3791  s->blockState = TBLOCK_END;
3792  result = true;
3793  break;
3794 
3795  /*
3796  * We are in a failed transaction block. Tell
3797  * CommitTransactionCommand it's time to exit the block.
3798  */
3799  case TBLOCK_ABORT:
3801  break;
3802 
3803  /*
3804  * We are in a live subtransaction block. Set up to subcommit all
3805  * open subtransactions and then commit the main transaction.
3806  */
3807  case TBLOCK_SUBINPROGRESS:
3808  while (s->parent != NULL)
3809  {
3810  if (s->blockState == TBLOCK_SUBINPROGRESS)
3812  else
3813  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3815  s = s->parent;
3816  }
3817  if (s->blockState == TBLOCK_INPROGRESS)
3818  s->blockState = TBLOCK_END;
3819  else
3820  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3822  result = true;
3823  break;
3824 
3825  /*
3826  * Here we are inside an aborted subtransaction. Treat the COMMIT
3827  * as ROLLBACK: set up to abort everything and exit the main
3828  * transaction.
3829  */
3830  case TBLOCK_SUBABORT:
3831  while (s->parent != NULL)
3832  {
3833  if (s->blockState == TBLOCK_SUBINPROGRESS)
3835  else if (s->blockState == TBLOCK_SUBABORT)
3837  else
3838  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3840  s = s->parent;
3841  }
3842  if (s->blockState == TBLOCK_INPROGRESS)
3844  else if (s->blockState == TBLOCK_ABORT)
3846  else
3847  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3849  break;
3850 
3851  /*
3852  * The user issued COMMIT when not inside a transaction. For
3853  * COMMIT without CHAIN, issue a WARNING, staying in
3854  * TBLOCK_STARTED state. The upcoming call to
3855  * CommitTransactionCommand() will then close the transaction and
3856  * put us back into the default state. For COMMIT AND CHAIN,
3857  * error.
3858  */
3859  case TBLOCK_STARTED:
3860  if (chain)
3861  ereport(ERROR,
3862  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3863  /* translator: %s represents an SQL statement name */
3864  errmsg("%s can only be used in transaction blocks",
3865  "COMMIT AND CHAIN")));
3866  else
3867  ereport(WARNING,
3868  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3869  errmsg("there is no transaction in progress")));
3870  result = true;
3871  break;
3872 
3873  /*
3874  * The user issued a COMMIT that somehow ran inside a parallel
3875  * worker. We can't cope with that.
3876  */
3878  ereport(FATAL,
3879  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3880  errmsg("cannot commit during a parallel operation")));
3881  break;
3882 
3883  /* These cases are invalid. */
3884  case TBLOCK_DEFAULT:
3885  case TBLOCK_BEGIN:
3886  case TBLOCK_SUBBEGIN:
3887  case TBLOCK_END:
3888  case TBLOCK_SUBRELEASE:
3889  case TBLOCK_SUBCOMMIT:
3890  case TBLOCK_ABORT_END:
3891  case TBLOCK_SUBABORT_END:
3892  case TBLOCK_ABORT_PENDING:
3894  case TBLOCK_SUBRESTART:
3896  case TBLOCK_PREPARE:
3897  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3899  break;
3900  }
3901 
3903  s->blockState == TBLOCK_END ||
3904  s->blockState == TBLOCK_ABORT_END ||
3906 
3907  s->chain = chain;
3908 
3909  return result;
3910 }
3911 
3912 /*
3913  * UserAbortTransactionBlock
3914  * This executes a ROLLBACK command.
3915  *
3916  * As above, we don't actually do anything here except change blockState.
3917  */
3918 void
3920 {
3922 
3923  switch (s->blockState)
3924  {
3925  /*
3926  * We are inside a transaction block and we got a ROLLBACK command
3927  * from the user, so tell CommitTransactionCommand to abort and
3928  * exit the transaction block.
3929  */
3930  case TBLOCK_INPROGRESS:
3932  break;
3933 
3934  /*
3935  * We are inside a failed transaction block and we got a ROLLBACK
3936  * command from the user. Abort processing is already done, so
3937  * CommitTransactionCommand just has to cleanup and go back to
3938  * idle state.
3939  */
3940  case TBLOCK_ABORT:
3942  break;
3943 
3944  /*
3945  * We are inside a subtransaction. Mark everything up to top
3946  * level as exitable.
3947  */
3948  case TBLOCK_SUBINPROGRESS:
3949  case TBLOCK_SUBABORT:
3950  while (s->parent != NULL)
3951  {
3952  if (s->blockState == TBLOCK_SUBINPROGRESS)
3954  else if (s->blockState == TBLOCK_SUBABORT)
3956  else
3957  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3959  s = s->parent;
3960  }
3961  if (s->blockState == TBLOCK_INPROGRESS)
3963  else if (s->blockState == TBLOCK_ABORT)
3965  else
3966  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3968  break;
3969 
3970  /*
3971  * The user issued ABORT when not inside a transaction. For
3972  * ROLLBACK without CHAIN, issue a WARNING and go to abort state.
3973  * The upcoming call to CommitTransactionCommand() will then put
3974  * us back into the default state. For ROLLBACK AND CHAIN, error.
3975  *
3976  * We do the same thing with ABORT inside an implicit transaction,
3977  * although in this case we might be rolling back actual database
3978  * state changes. (It's debatable whether we should issue a
3979  * WARNING in this case, but we have done so historically.)
3980  */
3981  case TBLOCK_STARTED:
3983  if (chain)
3984  ereport(ERROR,
3985  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3986  /* translator: %s represents an SQL statement name */
3987  errmsg("%s can only be used in transaction blocks",
3988  "ROLLBACK AND CHAIN")));
3989  else
3990  ereport(WARNING,
3991  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3992  errmsg("there is no transaction in progress")));
3994  break;
3995 
3996  /*
3997  * The user issued an ABORT that somehow ran inside a parallel
3998  * worker. We can't cope with that.
3999  */
4001  ereport(FATAL,
4002  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4003  errmsg("cannot abort during a parallel operation")));
4004  break;
4005 
4006  /* These cases are invalid. */
4007  case TBLOCK_DEFAULT:
4008  case TBLOCK_BEGIN:
4009  case TBLOCK_SUBBEGIN:
4010  case TBLOCK_END:
4011  case TBLOCK_SUBRELEASE:
4012  case TBLOCK_SUBCOMMIT:
4013  case TBLOCK_ABORT_END:
4014  case TBLOCK_SUBABORT_END:
4015  case TBLOCK_ABORT_PENDING:
4017  case TBLOCK_SUBRESTART:
4019  case TBLOCK_PREPARE:
4020  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4022  break;
4023  }
4024 
4027 
4028  s->chain = chain;
4029 }
4030 
4031 /*
4032  * BeginImplicitTransactionBlock
4033  * Start an implicit transaction block if we're not already in one.
4034  *
4035  * Unlike BeginTransactionBlock, this is called directly from the main loop
4036  * in postgres.c, not within a Portal. So we can just change blockState
4037  * without a lot of ceremony. We do not expect caller to do
4038  * CommitTransactionCommand/StartTransactionCommand.
4039  */
4040 void
4042 {
4044 
4045  /*
4046  * If we are in STARTED state (that is, no transaction block is open),
4047  * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
4048  * block.
4049  *
4050  * For caller convenience, we consider all other transaction states as
4051  * legal here; otherwise the caller would need its own state check, which
4052  * seems rather pointless.
4053  */
4054  if (s->blockState == TBLOCK_STARTED)
4056 }
4057 
4058 /*
4059  * EndImplicitTransactionBlock
4060  * End an implicit transaction block, if we're in one.
4061  *
4062  * Like EndTransactionBlock, we just make any needed blockState change here.
4063  * The real work will be done in the upcoming CommitTransactionCommand().
4064  */
4065 void
4067 {
4069 
4070  /*
4071  * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
4072  * allowing CommitTransactionCommand to commit whatever happened during
4073  * the implicit transaction block as though it were a single statement.
4074  *
4075  * For caller convenience, we consider all other transaction states as
4076  * legal here; otherwise the caller would need its own state check, which
4077  * seems rather pointless.
4078  */
4081 }
4082 
4083 /*
4084  * DefineSavepoint
4085  * This executes a SAVEPOINT command.
4086  */
4087 void
4088 DefineSavepoint(const char *name)
4089 {
4091 
4092  /*
4093  * Workers synchronize transaction state at the beginning of each parallel
4094  * operation, so we can't account for new subtransactions after that
4095  * point. (Note that this check will certainly error out if s->blockState
4096  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4097  * below.)
4098  */
4099  if (IsInParallelMode())
4100  ereport(ERROR,
4101  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4102  errmsg("cannot define savepoints during a parallel operation")));
4103 
4104  switch (s->blockState)
4105  {
4106  case TBLOCK_INPROGRESS:
4107  case TBLOCK_SUBINPROGRESS:
4108  /* Normal subtransaction start */
4109  PushTransaction();
4110  s = CurrentTransactionState; /* changed by push */
4111 
4112  /*
4113  * Savepoint names, like the TransactionState block itself, live
4114  * in TopTransactionContext.
4115  */
4116  if (name)
4118  break;
4119 
4120  /*
4121  * We disallow savepoint commands in implicit transaction blocks.
4122  * There would be no great difficulty in allowing them so far as
4123  * this module is concerned, but a savepoint seems inconsistent
4124  * with exec_simple_query's behavior of abandoning the whole query
4125  * string upon error. Also, the point of an implicit transaction
4126  * block (as opposed to a regular one) is to automatically close
4127  * after an error, so it's hard to see how a savepoint would fit
4128  * into that.
4129  *
4130  * The error messages for this are phrased as if there were no
4131  * active transaction block at all, which is historical but
4132  * perhaps could be improved.
4133  */
4135  ereport(ERROR,
4136  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4137  /* translator: %s represents an SQL statement name */
4138  errmsg("%s can only be used in transaction blocks",
4139  "SAVEPOINT")));
4140  break;
4141 
4142  /* These cases are invalid. */
4143  case TBLOCK_DEFAULT:
4144  case TBLOCK_STARTED:
4145  case TBLOCK_BEGIN:
4147  case TBLOCK_SUBBEGIN:
4148  case TBLOCK_END:
4149  case TBLOCK_SUBRELEASE:
4150  case TBLOCK_SUBCOMMIT:
4151  case TBLOCK_ABORT:
4152  case TBLOCK_SUBABORT:
4153  case TBLOCK_ABORT_END:
4154  case TBLOCK_SUBABORT_END:
4155  case TBLOCK_ABORT_PENDING:
4157  case TBLOCK_SUBRESTART:
4159  case TBLOCK_PREPARE:
4160  elog(FATAL, "DefineSavepoint: unexpected state %s",
4162  break;
4163  }
4164 }
4165 
4166 /*
4167  * ReleaseSavepoint
4168  * This executes a RELEASE command.
4169  *
4170  * As above, we don't actually do anything here except change blockState.
4171  */
4172 void
4174 {
4176  TransactionState target,
4177  xact;
4178 
4179  /*
4180  * Workers synchronize transaction state at the beginning of each parallel
4181  * operation, so we can't account for transaction state change after that
4182  * point. (Note that this check will certainly error out if s->blockState
4183  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4184  * below.)
4185  */
4186  if (IsInParallelMode())
4187  ereport(ERROR,
4188  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4189  errmsg("cannot release savepoints during a parallel operation")));
4190 
4191  switch (s->blockState)
4192  {
4193  /*
4194  * We can't release a savepoint if there is no savepoint defined.
4195  */
4196  case TBLOCK_INPROGRESS:
4197  ereport(ERROR,
4198  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4199  errmsg("savepoint \"%s\" does not exist", name)));
4200  break;
4201 
4203  /* See comment about implicit transactions in DefineSavepoint */
4204  ereport(ERROR,
4205  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4206  /* translator: %s represents an SQL statement name */
4207  errmsg("%s can only be used in transaction blocks",
4208  "RELEASE SAVEPOINT")));
4209  break;
4210 
4211  /*
4212  * We are in a non-aborted subtransaction. This is the only valid
4213  * case.
4214  */
4215  case TBLOCK_SUBINPROGRESS:
4216  break;
4217 
4218  /* These cases are invalid. */
4219  case TBLOCK_DEFAULT:
4220  case TBLOCK_STARTED:
4221  case TBLOCK_BEGIN:
4223  case TBLOCK_SUBBEGIN:
4224  case TBLOCK_END:
4225  case TBLOCK_SUBRELEASE:
4226  case TBLOCK_SUBCOMMIT:
4227  case TBLOCK_ABORT:
4228  case TBLOCK_SUBABORT:
4229  case TBLOCK_ABORT_END:
4230  case TBLOCK_SUBABORT_END:
4231  case TBLOCK_ABORT_PENDING:
4233  case TBLOCK_SUBRESTART:
4235  case TBLOCK_PREPARE:
4236  elog(FATAL, "ReleaseSavepoint: unexpected state %s",
4238  break;
4239  }
4240 
4241  for (target = s; PointerIsValid(target); target = target->parent)
4242  {
4243  if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
4244  break;
4245  }
4246 
4247  if (!PointerIsValid(target))
4248  ereport(ERROR,
4249  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4250  errmsg("savepoint \"%s\" does not exist", name)));
4251 
4252  /* disallow crossing savepoint level boundaries */
4253  if (target->savepointLevel != s->savepointLevel)
4254  ereport(ERROR,
4255  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4256  errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4257 
4258  /*
4259  * Mark "commit pending" all subtransactions up to the target
4260  * subtransaction. The actual commits will happen when control gets to
4261  * CommitTransactionCommand.
4262  */
4263  xact = CurrentTransactionState;
4264  for (;;)
4265  {
4267  xact->blockState = TBLOCK_SUBRELEASE;
4268  if (xact == target)
4269  break;
4270  xact = xact->parent;
4271  Assert(PointerIsValid(xact));
4272  }
4273 }
4274 
4275 /*
4276  * RollbackToSavepoint
4277  * This executes a ROLLBACK TO <savepoint> command.
4278  *
4279  * As above, we don't actually do anything here except change blockState.
4280  */
4281 void
4283 {
4285  TransactionState target,
4286  xact;
4287 
4288  /*
4289  * Workers synchronize transaction state at the beginning of each parallel
4290  * operation, so we can't account for transaction state change after that
4291  * point. (Note that this check will certainly error out if s->blockState
4292  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4293  * below.)
4294  */
4295  if (IsInParallelMode())
4296  ereport(ERROR,
4297  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4298  errmsg("cannot rollback to savepoints during a parallel operation")));
4299 
4300  switch (s->blockState)
4301  {
4302  /*
4303  * We can't rollback to a savepoint if there is no savepoint
4304  * defined.
4305  */
4306  case TBLOCK_INPROGRESS:
4307  case TBLOCK_ABORT:
4308  ereport(ERROR,
4309  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4310  errmsg("savepoint \"%s\" does not exist", name)));
4311  break;
4312 
4314  /* See comment about implicit transactions in DefineSavepoint */
4315  ereport(ERROR,
4316  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4317  /* translator: %s represents an SQL statement name */
4318  errmsg("%s can only be used in transaction blocks",
4319  "ROLLBACK TO SAVEPOINT")));
4320  break;
4321 
4322  /*
4323  * There is at least one savepoint, so proceed.
4324  */
4325  case TBLOCK_SUBINPROGRESS:
4326  case TBLOCK_SUBABORT:
4327  break;
4328 
4329  /* These cases are invalid. */
4330  case TBLOCK_DEFAULT:
4331  case TBLOCK_STARTED:
4332  case TBLOCK_BEGIN:
4334  case TBLOCK_SUBBEGIN:
4335  case TBLOCK_END:
4336  case TBLOCK_SUBRELEASE:
4337  case TBLOCK_SUBCOMMIT:
4338  case TBLOCK_ABORT_END:
4339  case TBLOCK_SUBABORT_END:
4340  case TBLOCK_ABORT_PENDING:
4342  case TBLOCK_SUBRESTART:
4344  case TBLOCK_PREPARE:
4345  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4347  break;
4348  }
4349 
4350  for (target = s; PointerIsValid(target); target = target->parent)
4351  {
4352  if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
4353  break;
4354  }
4355 
4356  if (!PointerIsValid(target))
4357  ereport(ERROR,
4358  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4359  errmsg("savepoint \"%s\" does not exist", name)));
4360 
4361  /* disallow crossing savepoint level boundaries */
4362  if (target->savepointLevel != s->savepointLevel)
4363  ereport(ERROR,
4364  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4365  errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4366 
4367  /*
4368  * Mark "abort pending" all subtransactions up to the target
4369  * subtransaction. The actual aborts will happen when control gets to
4370  * CommitTransactionCommand.
4371  */
4372  xact = CurrentTransactionState;
4373  for (;;)
4374  {
4375  if (xact == target)
4376  break;
4377  if (xact->blockState == TBLOCK_SUBINPROGRESS)
4379  else if (xact->blockState == TBLOCK_SUBABORT)
4381  else
4382  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4384  xact = xact->parent;
4385  Assert(PointerIsValid(xact));
4386  }
4387 
4388  /* And mark the target as "restart pending" */
4389  if (xact->blockState == TBLOCK_SUBINPROGRESS)
4390  xact->blockState = TBLOCK_SUBRESTART;
4391  else if (xact->blockState == TBLOCK_SUBABORT)
4393  else
4394  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4396 }
4397 
4398 /*
4399  * BeginInternalSubTransaction
4400  * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
4401  * TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_END, and TBLOCK_PREPARE states,
4402  * and therefore it can safely be used in functions that might be called
4403  * when not inside a BEGIN block or when running deferred triggers at
4404  * COMMIT/PREPARE time. Also, it automatically does
4405  * CommitTransactionCommand/StartTransactionCommand instead of expecting
4406  * the caller to do it.
4407  */
4408 void
4410 {
4412 
4413  /*
4414  * Workers synchronize transaction state at the beginning of each parallel
4415  * operation, so we can't account for new subtransactions after that
4416  * point. We might be able to make an exception for the type of
4417  * subtransaction established by this function, which is typically used in
4418  * contexts where we're going to release or roll back the subtransaction
4419  * before proceeding further, so that no enduring change to the
4420  * transaction state occurs. For now, however, we prohibit this case along
4421  * with all the others.
4422  */
4423  if (IsInParallelMode())
4424  ereport(ERROR,
4425  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4426  errmsg("cannot start subtransactions during a parallel operation")));
4427 
4428  switch (s->blockState)
4429  {
4430  case TBLOCK_STARTED:
4431  case TBLOCK_INPROGRESS:
4433  case TBLOCK_END:
4434  case TBLOCK_PREPARE:
4435  case TBLOCK_SUBINPROGRESS:
4436  /* Normal subtransaction start */
4437  PushTransaction();
4438  s = CurrentTransactionState; /* changed by push */
4439 
4440  /*
4441  * Savepoint names, like the TransactionState block itself, live
4442  * in TopTransactionContext.
4443  */
4444  if (name)
4446  break;
4447 
4448  /* These cases are invalid. */
4449  case TBLOCK_DEFAULT:
4450  case TBLOCK_BEGIN:
4452  case TBLOCK_SUBBEGIN:
4453  case TBLOCK_SUBRELEASE:
4454  case TBLOCK_SUBCOMMIT:
4455  case TBLOCK_ABORT:
4456  case TBLOCK_SUBABORT:
4457  case TBLOCK_ABORT_END:
4458  case TBLOCK_SUBABORT_END:
4459  case TBLOCK_ABORT_PENDING:
4461  case TBLOCK_SUBRESTART:
4463  elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4465  break;
4466  }
4467 
4470 }
4471 
4472 /*
4473  * ReleaseCurrentSubTransaction
4474  *
4475  * RELEASE (ie, commit) the innermost subtransaction, regardless of its
4476  * savepoint name (if any).
4477  * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4478  */
4479 void
4481 {
4483 
4484  /*
4485  * Workers synchronize transaction state at the beginning of each parallel
4486  * operation, so we can't account for commit of subtransactions after that
4487  * point. This should not happen anyway. Code calling this would
4488  * typically have called BeginInternalSubTransaction() first, failing
4489  * there.
4490  */
4491  if (IsInParallelMode())
4492  ereport(ERROR,
4493  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4494  errmsg("cannot commit subtransactions during a parallel operation")));
4495 
4496  if (s->blockState != TBLOCK_SUBINPROGRESS)
4497  elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
4499  Assert(s->state == TRANS_INPROGRESS);
4502  s = CurrentTransactionState; /* changed by pop */
4503  Assert(s->state == TRANS_INPROGRESS);
4504 }
4505 
4506 /*
4507  * RollbackAndReleaseCurrentSubTransaction
4508  *
4509  * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
4510  * of its savepoint name (if any).
4511  * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4512  */
4513 void
4515 {
4517 
4518  /*
4519  * Unlike ReleaseCurrentSubTransaction(), this is nominally permitted
4520  * during parallel operations. That's because we may be in the leader,
4521  * recovering from an error thrown while we were in parallel mode. We
4522  * won't reach here in a worker, because BeginInternalSubTransaction()
4523  * will have failed.
4524  */
4525 
4526  switch (s->blockState)
4527  {
4528  /* Must be in a subtransaction */
4529  case TBLOCK_SUBINPROGRESS:
4530  case TBLOCK_SUBABORT:
4531  break;
4532 
4533  /* These cases are invalid. */
4534  case TBLOCK_DEFAULT:
4535  case TBLOCK_STARTED:
4536  case TBLOCK_BEGIN:
4539  case TBLOCK_SUBBEGIN:
4540  case TBLOCK_INPROGRESS:
4541  case TBLOCK_END:
4542  case TBLOCK_SUBRELEASE:
4543  case TBLOCK_SUBCOMMIT:
4544  case TBLOCK_ABORT:
4545  case TBLOCK_ABORT_END:
4546  case TBLOCK_SUBABORT_END:
4547  case TBLOCK_ABORT_PENDING:
4549  case TBLOCK_SUBRESTART:
4551  case TBLOCK_PREPARE:
4552  elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
4554  break;
4555  }
4556 
4557  /*
4558  * Abort the current subtransaction, if needed.
4559  */
4560  if (s->blockState == TBLOCK_SUBINPROGRESS)
4562 
4563  /* And clean it up, too */
4565 
4566  s = CurrentTransactionState; /* changed by pop */
4568  s->blockState == TBLOCK_INPROGRESS ||
4570  s->blockState == TBLOCK_STARTED);
4571 }
4572 
4573 /*
4574  * AbortOutOfAnyTransaction
4575  *
4576  * This routine is provided for error recovery purposes. It aborts any
4577  * active transaction or transaction block, leaving the system in a known
4578  * idle state.
4579  */
4580 void
4582 {
4584 
4585  /* Ensure we're not running in a doomed memory context */
4586  AtAbort_Memory();
4587 
4588  /*
4589  * Get out of any transaction or nested transaction
4590  */
4591  do
4592  {
4593  switch (s->blockState)
4594  {
4595  case TBLOCK_DEFAULT:
4596  if (s->state == TRANS_DEFAULT)
4597  {
4598  /* Not in a transaction, do nothing */
4599  }
4600  else
4601  {
4602  /*
4603  * We can get here after an error during transaction start
4604  * (state will be TRANS_START). Need to clean up the
4605  * incompletely started transaction. First, adjust the
4606  * low-level state to suppress warning message from
4607  * AbortTransaction.
4608  */
4609  if (s->state == TRANS_START)
4610  s->state = TRANS_INPROGRESS;
4611  AbortTransaction();
4613  }
4614  break;
4615  case TBLOCK_STARTED:
4616  case TBLOCK_BEGIN:
4617  case TBLOCK_INPROGRESS:
4620  case TBLOCK_END:
4621  case TBLOCK_ABORT_PENDING:
4622  case TBLOCK_PREPARE:
4623  /* In a transaction, so clean up */
4624  AbortTransaction();
4627  break;
4628  case TBLOCK_ABORT:
4629  case TBLOCK_ABORT_END:
4630 
4631  /*
4632  * AbortTransaction is already done, still need Cleanup.
4633  * However, if we failed partway through running ROLLBACK,
4634  * there will be an active portal running that command, which
4635  * we need to shut down before doing CleanupTransaction.
4636  */
4637  AtAbort_Portals();
4640  break;
4641 
4642  /*
4643  * In a subtransaction, so clean it up and abort parent too
4644  */
4645  case TBLOCK_SUBBEGIN:
4646  case TBLOCK_SUBINPROGRESS:
4647  case TBLOCK_SUBRELEASE:
4648  case TBLOCK_SUBCOMMIT:
4650  case TBLOCK_SUBRESTART:
4653  s = CurrentTransactionState; /* changed by pop */
4654  break;
4655 
4656  case TBLOCK_SUBABORT:
4657  case TBLOCK_SUBABORT_END:
4659  /* As above, but AbortSubTransaction already done */
4660  if (s->curTransactionOwner)
4661  {
4662  /* As in TBLOCK_ABORT, might have a live portal to zap */
4667  }
4669  s = CurrentTransactionState; /* changed by pop */
4670  break;
4671  }
4672  } while (s->blockState != TBLOCK_DEFAULT);
4673 
4674  /* Should be out of all subxacts now */
4675  Assert(s->parent == NULL);
4676 
4677  /* If we didn't actually have anything to do, revert to TopMemoryContext */
4678  AtCleanup_Memory();
4679 }
4680 
4681 /*
4682  * IsTransactionBlock --- are we within a transaction block?
4683  */
4684 bool
4686 {
4688 
4690  return false;
4691 
4692  return true;
4693 }
4694 
4695 /*
4696  * IsTransactionOrTransactionBlock --- are we within either a transaction
4697  * or a transaction block? (The backend is only really "idle" when this
4698  * returns false.)
4699  *
4700  * This should match up with IsTransactionBlock and IsTransactionState.
4701  */
4702 bool
4704 {
4706 
4707  if (s->blockState == TBLOCK_DEFAULT)
4708  return false;
4709 
4710  return true;
4711 }
4712 
4713 /*
4714  * TransactionBlockStatusCode - return status code to send in ReadyForQuery
4715  */
4716 char
4718 {
4720 
4721  switch (s->blockState)
4722  {
4723  case TBLOCK_DEFAULT:
4724  case TBLOCK_STARTED:
4725  return 'I'; /* idle --- not in transaction */
4726  case TBLOCK_BEGIN:
4727  case TBLOCK_SUBBEGIN:
4728  case TBLOCK_INPROGRESS:
4731  case TBLOCK_SUBINPROGRESS:
4732  case TBLOCK_END:
4733  case TBLOCK_SUBRELEASE:
4734  case TBLOCK_SUBCOMMIT:
4735  case TBLOCK_PREPARE:
4736  return 'T'; /* in transaction */
4737  case TBLOCK_ABORT:
4738  case TBLOCK_SUBABORT:
4739  case TBLOCK_ABORT_END:
4740  case TBLOCK_SUBABORT_END:
4741  case TBLOCK_ABORT_PENDING:
4743  case TBLOCK_SUBRESTART:
4745  return 'E'; /* in failed transaction */
4746  }
4747 
4748  /* should never get here */
4749  elog(FATAL, "invalid transaction block state: %s",
4751  return 0; /* keep compiler quiet */
4752 }
4753 
4754 /*
4755  * IsSubTransaction
4756  */
4757 bool
4759 {
4761 
4762  if (s->nestingLevel >= 2)
4763  return true;
4764 
4765  return false;
4766 }
4767 
4768 /*
4769  * StartSubTransaction
4770  *
4771  * If you're wondering why this is separate from PushTransaction: it's because
4772  * we can't conveniently do this stuff right inside DefineSavepoint. The
4773  * SAVEPOINT utility command will be executed inside a Portal, and if we
4774  * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
4775  * the Portal will undo those settings. So we make DefineSavepoint just
4776  * push a dummy transaction block, and when control returns to the main
4777  * idle loop, CommitTransactionCommand will be called, and we'll come here
4778  * to finish starting the subtransaction.
4779  */
4780 static void
4782 {
4784 
4785  if (s->state != TRANS_DEFAULT)
4786  elog(WARNING, "StartSubTransaction while in %s state",
4788 
4789  s->state = TRANS_START;
4790 
4791  /*
4792  * Initialize subsystems for new subtransaction
4793  *
4794  * must initialize resource-management stuff first
4795  */
4799 
4800  s->state = TRANS_INPROGRESS;
4801 
4802  /*
4803  * Call start-of-subxact callbacks
4804  */
4806  s->parent->subTransactionId);
4807 
4808  ShowTransactionState("StartSubTransaction");
4809 }
4810 
4811 /*
4812  * CommitSubTransaction
4813  *
4814  * The caller has to make sure to always reassign CurrentTransactionState
4815  * if it has a local pointer to it after calling this function.
4816  */
4817 static void
4819 {
4821 
4822  ShowTransactionState("CommitSubTransaction");
4823 
4824  if (s->state != TRANS_INPROGRESS)
4825  elog(WARNING, "CommitSubTransaction while in %s state",
4827 
4828  /* Pre-commit processing goes here */
4829 
4831  s->parent->subTransactionId);
4832 
4833  /* If in parallel mode, clean up workers and exit parallel mode. */
4834  if (IsInParallelMode())
4835  {
4837  s->parallelModeLevel = 0;
4838  }
4839 
4840  /* Do the actual "commit", such as it is */
4841  s->state = TRANS_COMMIT;
4842 
4843  /* Must CCI to ensure commands of subtransaction are seen as done */
4845 
4846  /*
4847  * Prior to 8.4 we marked subcommit in clog at this point. We now only
4848  * perform that step, if required, as part of the atomic update of the
4849  * whole transaction tree at top level commit or abort.
4850  */
4851 
4852  /* Post-commit cleanup */
4855  AfterTriggerEndSubXact(true);
4860  s->parent->subTransactionId);
4862 
4864  s->parent->subTransactionId);
4865 
4868  true, false);
4870  s->parent->subTransactionId);
4871  AtEOSubXact_Inval(true);
4872  AtSubCommit_smgr();
4873 
4874  /*
4875  * The only lock we actually release here is the subtransaction XID lock.
4876  */
4880 
4881  /*
4882  * Other locks should get transferred to their parent resource owner.
4883  */
4886  true, false);
4889  true, false);
4890 
4891  AtEOXact_GUC(true, s->gucNestLevel);
4894  s->parent->subTransactionId);
4896  s->parent->subTransactionId);
4898  s->parent->subTransactionId);
4900  AtEOSubXact_PgStat(true, s->nestingLevel);
4903 
4904  /*
4905  * We need to restore the upper transaction's read-only state, in case the
4906  * upper is read-write while the child is read-only; GUC will incorrectly
4907  * think it should leave the child state in place.
4908  */
4910 
4914  s->curTransactionOwner = NULL;
4915 
4917 
4918  s->state = TRANS_DEFAULT;
4919 
4920  PopTransaction();
4921 }
4922 
4923 /*
4924  * AbortSubTransaction
4925  */
4926 static void
4928 {
4930 
4931  /* Prevent cancel/die interrupt while cleaning up */
4932  HOLD_INTERRUPTS();
4933 
4934  /* Make sure we have a valid memory context and resource owner */
4937 
4938  /*
4939  * Release any LW locks we might be holding as quickly as possible.
4940  * (Regular locks, however, must be held till we finish aborting.)
4941  * Releasing LW locks is critical since we might try to grab them again
4942  * while cleaning up!
4943  *
4944  * FIXME This may be incorrect --- Are there some locks we should keep?
4945  * Buffer locks, for example? I don't think so but I'm not sure.
4946  */
4947  LWLockReleaseAll();
4948 
4951  AbortBufferIO();
4952  UnlockBuffers();
4953 
4954  /* Reset WAL record construction state */
4956 
4957  /* Cancel condition variable sleep */
4959 
4960  /*
4961  * Also clean up any open wait for lock, since the lock manager will choke
4962  * if we try to wait for another lock before doing this.
4963  */
4964  LockErrorCleanup();
4965 
4966  /*
4967  * If any timeout events are still active, make sure the timeout interrupt
4968  * is scheduled. This covers possible loss of a timeout interrupt due to
4969  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
4970  * We delay this till after LockErrorCleanup so that we don't uselessly
4971  * reschedule lock or deadlock check timeouts.
4972  */
4974 
4975  /*
4976  * Re-enable signals, in case we got here by longjmp'ing out of a signal
4977  * handler. We do this fairly early in the sequence so that the timeout
4978  * infrastructure will be functional if needed while aborting.
4979  */
4981 
4982  /*
4983  * check the current transaction state
4984  */
4985  ShowTransactionState("AbortSubTransaction");
4986 
4987  if (s->state != TRANS_INPROGRESS)
4988  elog(WARNING, "AbortSubTransaction while in %s state",
4990 
4991  s->state = TRANS_ABORT;
4992 
4993  /*
4994  * Reset user ID which might have been changed transiently. (See notes in
4995  * AbortTransaction.)
4996  */
4998 
4999  /* Forget about any active REINDEX. */
5001 
5002  /* Reset logical streaming state. */
5004 
5005  /* Exit from parallel mode, if necessary. */
5006  if (IsInParallelMode())
5007  {
5009  s->parallelModeLevel = 0;
5010  }
5011 
5012  /*
5013  * We can skip all this stuff if the subxact failed before creating a
5014  * ResourceOwner...
5015  */
5016  if (s->curTransactionOwner)
5017  {
5018  AfterTriggerEndSubXact(false);
5024  s->parent->subTransactionId);
5026 
5027  /* Advertise the fact that we aborted in pg_xact. */
5028  (void) RecordTransactionAbort(true);
5029 
5030  /* Post-abort cleanup */
5033 
5035  s->parent->subTransactionId);
5036 
5039  false, false);
5041  s->parent->subTransactionId);
5042  AtEOSubXact_Inval(false);
5045  false, false);
5048  false, false);
5049  AtSubAbort_smgr();
5050 
5051  AtEOXact_GUC(false, s->gucNestLevel);
5052  AtEOSubXact_SPI(false, s->subTransactionId);
5054  s->parent->subTransactionId);
5056  s->parent->subTransactionId);
5058  s->parent->subTransactionId);
5060  AtEOSubXact_PgStat(false, s->nestingLevel);
5063  }
5064 
5065  /*
5066  * Restore the upper transaction's read-only state, too. This should be
5067  * redundant with GUC's cleanup but we may as well do it for consistency
5068  * with the commit case.
5069  */
5071 
5073 }
5074 
5075 /*
5076  * CleanupSubTransaction
5077  *
5078  * The caller has to make sure to always reassign CurrentTransactionState
5079  * if it has a local pointer to it after calling this function.
5080  */
5081 static void
5083 {
5085 
5086  ShowTransactionState("CleanupSubTransaction");
5087 
5088  if (s->state != TRANS_ABORT)
5089  elog(WARNING, "CleanupSubTransaction while in %s state",
5091 
5093 
5096  if (s->curTransactionOwner)
5098  s->curTransactionOwner = NULL;
5099 
5101 
5102  s->state = TRANS_DEFAULT;
5103 
5104  PopTransaction();
5105 }
5106 
5107 /*
5108  * PushTransaction
5109  * Create transaction state stack entry for a subtransaction
5110  *
5111  * The caller has to make sure to always reassign CurrentTransactionState
5112  * if it has a local pointer to it after calling this function.
5113  */
5114 static void
5116 {
5118  TransactionState s;
5119 
5120  /*
5121  * We keep subtransaction state nodes in TopTransactionContext.
5122  */
5123  s = (TransactionState)
5125  sizeof(TransactionStateData));
5126 
5127  /*
5128  * Assign a subtransaction ID, watching out for counter wraparound.
5129  */
5132  {
5134  pfree(s);
5135  ereport(ERROR,
5136  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5137  errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
5138  }
5139 
5140  /*
5141  * We can now stack a minimally valid subtransaction without fear of
5142  * failure.
5143  */
5144  s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
5146  s->parent = p;
5147  s->nestingLevel = p->nestingLevel + 1;
5150  s->state = TRANS_DEFAULT;
5154  s->parallelModeLevel = 0;
5155  s->assigned = false;
5156 
5157  CurrentTransactionState = s;
5158 
5159  /*
5160  * AbortSubTransaction and CleanupSubTransaction have to be able to cope
5161  * with the subtransaction from here on out; in particular they should not
5162  * assume that it necessarily has a transaction context, resource owner,
5163  * or XID.
5164  */
5165 }
5166 
5167 /*
5168  * PopTransaction
5169  * Pop back to parent transaction state
5170  *
5171  * The caller has to make sure to always reassign CurrentTransactionState
5172  * if it has a local pointer to it after calling this function.
5173  */
5174 static void
5176 {
5178 
5179  if (s->state != TRANS_DEFAULT)
5180  elog(WARNING, "PopTransaction while in %s state",
5182 
5183  if (s->parent == NULL)
5184  elog(FATAL, "PopTransaction with no parent");
5185 
5186  CurrentTransactionState = s->parent;
5187 
5188  /* Let's just make sure CurTransactionContext is good */
5191 
5192  /* Ditto for ResourceOwner links */
5195 
5196  /* Free the old child structure */
5197  if (s->name)
5198  pfree(s->name);
5199  pfree(s);
5200 }
5201 
5202 /*
5203  * EstimateTransactionStateSpace
5204  * Estimate the amount of space that will be needed by
5205  * SerializeTransactionState. It would be OK to overestimate slightly,
5206  * but it's simple for us to work out the precise value, so we do.
5207  */
5208 Size
5210 {
5211  TransactionState s;
5212  Size nxids = 0;
5214 
5215  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5216  {
5218  nxids = add_size(nxids, 1);
5219  nxids = add_size(nxids, s->nChildXids);
5220  }
5221 
5222  return add_size(size, mul_size(sizeof(TransactionId), nxids));
5223 }
5224 
5225 /*
5226  * SerializeTransactionState
5227  * Write out relevant details of our transaction state that will be
5228  * needed by a parallel worker.
5229  *
5230  * We need to save and restore XactDeferrable, XactIsoLevel, and the XIDs
5231  * associated with this transaction. These are serialized into a
5232  * caller-supplied buffer big enough to hold the number of bytes reported by
5233  * EstimateTransactionStateSpace(). We emit the XIDs in sorted order for the
5234  * convenience of the receiving process.
5235  */
5236 void
5237 SerializeTransactionState(Size maxsize, char *start_address)
5238 {
5239  TransactionState s;
5240  Size nxids = 0;
5241  Size i = 0;
5242  TransactionId *workspace;
5244 
5245  result = (SerializedTransactionState *) start_address;
5246 
5247  result->xactIsoLevel = XactIsoLevel;
5248  result->xactDeferrable = XactDeferrable;
5250  result->currentFullTransactionId =
5251  CurrentTransactionState->fullTransactionId;
5253 
5254  /*
5255  * If we're running in a parallel worker and launching a parallel worker
5256  * of our own, we can just pass along the information that was passed to
5257  * us.
5258  */
5259  if (nParallelCurrentXids > 0)
5260  {
5262  memcpy(&result->parallelCurrentXids[0], ParallelCurrentXids,
5264  return;
5265  }
5266 
5267  /*
5268  * OK, we need to generate a sorted list of XIDs that our workers should
5269  * view as current. First, figure out how many there are.
5270  */
5271  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5272  {
5274  nxids = add_size(nxids, 1);
5275  nxids = add_size(nxids, s->nChildXids);
5276  }
5278  <= maxsize);
5279 
5280  /* Copy them to our scratch space. */
5281  workspace = palloc(nxids * sizeof(TransactionId));
5282  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5283  {
5285  workspace[i++] = XidFromFullTransactionId(s->fullTransactionId);
5286  memcpy(&workspace[i], s->childXids,
5287  s->nChildXids * sizeof(TransactionId));
5288  i += s->nChildXids;
5289  }
5290  Assert(i == nxids);
5291 
5292  /* Sort them. */
5293  qsort(workspace, nxids, sizeof(TransactionId), xidComparator);
5294 
5295  /* Copy data into output area. */
5296  result->nParallelCurrentXids = nxids;
5297  memcpy(&result->parallelCurrentXids[0], workspace,
5298  nxids * sizeof(TransactionId));
5299 }
5300 
5301 /*
5302  * StartParallelWorkerTransaction
5303  * Start a parallel worker transaction, restoring the relevant
5304  * transaction state serialized by SerializeTransactionState.
5305  */
5306 void
5308 {
5310 
5311  Assert(CurrentTransactionState->blockState == TBLOCK_DEFAULT);
5312  StartTransaction();
5313 
5314  tstate = (SerializedTransactionState *) tstatespace;
5315  XactIsoLevel = tstate->xactIsoLevel;
5316  XactDeferrable = tstate->xactDeferrable;
5317  XactTopFullTransactionId = tstate->topFullTransactionId;
5318  CurrentTransactionState->fullTransactionId =
5319  tstate->currentFullTransactionId;
5323 
5324  CurrentTransactionState->blockState = TBLOCK_PARALLEL_INPROGRESS;
5325 }
5326 
5327 /*
5328  * EndParallelWorkerTransaction
5329  * End a parallel worker transaction.
5330  */
5331 void
5333 {
5334  Assert(CurrentTransactionState->blockState == TBLOCK_PARALLEL_INPROGRESS);
5336  CurrentTransactionState->blockState = TBLOCK_DEFAULT;
5337 }
5338 
5339 /*
5340  * ShowTransactionState
5341  * Debug support
5342  */
5343 static void
5345 {
5346  /* skip work if message will definitely not be printed */
5348  ShowTransactionStateRec(str, CurrentTransactionState);
5349 }
5350 
5351 /*
5352  * ShowTransactionStateRec
5353  * Recursive subroutine for ShowTransactionState
5354  */
5355 static void
5357 {
5359 
5360  initStringInfo(&buf);
5361 
5362  if (s->nChildXids > 0)
5363  {
5364  int i;
5365 
5366  appendStringInfo(&buf, ", children: %u", s->childXids[0]);
5367  for (i = 1; i < s->nChildXids; i++)
5368  appendStringInfo(&buf, " %u", s->childXids[i]);
5369  }
5370 
5371  if (s->parent)
5373 
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));
5743 
5744