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-2024, PostgreSQL Global Development Group
9  * Portions Copyright (c) 1994, Regents of the University of California
10  *
11  *
12  * IDENTIFICATION
13  * src/backend/access/transam/xact.c
14  *
15  *-------------------------------------------------------------------------
16  */
17 
18 #include "postgres.h"
19 
20 #include <time.h>
21 #include <unistd.h>
22 
23 #include "access/commit_ts.h"
24 #include "access/multixact.h"
25 #include "access/parallel.h"
26 #include "access/subtrans.h"
27 #include "access/transam.h"
28 #include "access/twophase.h"
29 #include "access/xact.h"
30 #include "access/xlog.h"
31 #include "access/xloginsert.h"
32 #include "access/xlogrecovery.h"
33 #include "access/xlogutils.h"
34 #include "catalog/index.h"
35 #include "catalog/namespace.h"
36 #include "catalog/pg_enum.h"
37 #include "catalog/storage.h"
38 #include "commands/async.h"
39 #include "commands/tablecmds.h"
40 #include "commands/trigger.h"
41 #include "commands/waitlsn.h"
42 #include "common/pg_prng.h"
43 #include "executor/spi.h"
44 #include "libpq/be-fsstubs.h"
45 #include "libpq/pqsignal.h"
46 #include "miscadmin.h"
47 #include "pg_trace.h"
48 #include "pgstat.h"
49 #include "replication/logical.h"
52 #include "replication/origin.h"
53 #include "replication/snapbuild.h"
54 #include "replication/syncrep.h"
56 #include "storage/fd.h"
57 #include "storage/lmgr.h"
58 #include "storage/md.h"
59 #include "storage/predicate.h"
60 #include "storage/proc.h"
61 #include "storage/procarray.h"
62 #include "storage/sinvaladt.h"
63 #include "storage/smgr.h"
64 #include "utils/builtins.h"
65 #include "utils/combocid.h"
66 #include "utils/guc.h"
67 #include "utils/inval.h"
68 #include "utils/memutils.h"
69 #include "utils/relmapper.h"
70 #include "utils/snapmgr.h"
71 #include "utils/timeout.h"
72 #include "utils/timestamp.h"
73 
74 /*
75  * User-tweakable parameters
76  */
79 
80 bool DefaultXactReadOnly = false;
82 
83 bool DefaultXactDeferrable = false;
85 
87 
88 /*
89  * CheckXidAlive is a xid value pointing to a possibly ongoing (sub)
90  * transaction. Currently, it is used in logical decoding. It's possible
91  * that such transactions can get aborted while the decoding is ongoing in
92  * which case we skip decoding that particular transaction. To ensure that we
93  * check whether the CheckXidAlive is aborted after fetching the tuple from
94  * system tables. We also ensure that during logical decoding we never
95  * directly access the tableam or heap APIs because we are checking for the
96  * concurrent aborts only in systable_* APIs.
97  */
99 bool bsysscan = false;
100 
101 /*
102  * When running as a parallel worker, we place only a single
103  * TransactionStateData on the parallel worker's state stack, and the XID
104  * reflected there will be that of the *innermost* currently-active
105  * subtransaction in the backend that initiated parallelism. However,
106  * GetTopTransactionId() and TransactionIdIsCurrentTransactionId()
107  * need to return the same answers in the parallel worker as they would have
108  * in the user backend, so we need some additional bookkeeping.
109  *
110  * XactTopFullTransactionId stores the XID of our toplevel transaction, which
111  * will be the same as TopTransactionStateData.fullTransactionId in an
112  * ordinary backend; but in a parallel backend, which does not have the entire
113  * transaction state, it will instead be copied from the backend that started
114  * the parallel operation.
115  *
116  * nParallelCurrentXids will be 0 and ParallelCurrentXids NULL in an ordinary
117  * backend, but in a parallel backend, nParallelCurrentXids will contain the
118  * number of XIDs that need to be considered current, and ParallelCurrentXids
119  * will contain the XIDs themselves. This includes all XIDs that were current
120  * or sub-committed in the parent at the time the parallel operation began.
121  * The XIDs are stored sorted in numerical order (not logical order) to make
122  * lookups as fast as possible.
123  */
125 static int nParallelCurrentXids = 0;
127 
128 /*
129  * Miscellaneous flag bits to record events which occur on the top level
130  * transaction. These flags are only persisted in MyXactFlags and are intended
131  * so we remember to do certain things later on in the transaction. This is
132  * globally accessible, so can be set from anywhere in the code that requires
133  * recording flags.
134  */
136 
137 /*
138  * transaction states - transaction state from server perspective
139  */
140 typedef enum TransState
141 {
142  TRANS_DEFAULT, /* idle */
143  TRANS_START, /* transaction starting */
144  TRANS_INPROGRESS, /* inside a valid transaction */
145  TRANS_COMMIT, /* commit in progress */
146  TRANS_ABORT, /* abort in progress */
147  TRANS_PREPARE, /* prepare in progress */
149 
150 /*
151  * transaction block states - transaction state of client queries
152  *
153  * Note: the subtransaction states are used only for non-topmost
154  * transactions; the others appear only in the topmost transaction.
155  */
156 typedef enum TBlockState
157 {
158  /* not-in-transaction-block states */
159  TBLOCK_DEFAULT, /* idle */
160  TBLOCK_STARTED, /* running single-query transaction */
161 
162  /* transaction block states */
163  TBLOCK_BEGIN, /* starting transaction block */
164  TBLOCK_INPROGRESS, /* live transaction */
165  TBLOCK_IMPLICIT_INPROGRESS, /* live transaction after implicit BEGIN */
166  TBLOCK_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
167  TBLOCK_END, /* COMMIT received */
168  TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
169  TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
170  TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
171  TBLOCK_PREPARE, /* live xact, PREPARE received */
172 
173  /* subtransaction states */
174  TBLOCK_SUBBEGIN, /* starting a subtransaction */
175  TBLOCK_SUBINPROGRESS, /* live subtransaction */
176  TBLOCK_SUBRELEASE, /* RELEASE received */
177  TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
178  TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
179  TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
180  TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
181  TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
182  TBLOCK_SUBABORT_RESTART, /* failed subxact, ROLLBACK TO received */
184 
185 /*
186  * transaction state structure
187  *
188  * Note: parallelModeLevel counts the number of unmatched EnterParallelMode
189  * calls done at this transaction level. parallelChildXact is true if any
190  * upper transaction level has nonzero parallelModeLevel.
191  */
192 typedef struct TransactionStateData
193 {
194  FullTransactionId fullTransactionId; /* my FullTransactionId */
195  SubTransactionId subTransactionId; /* my subxact ID */
196  char *name; /* savepoint name, if any */
197  int savepointLevel; /* savepoint level */
198  TransState state; /* low-level state */
199  TBlockState blockState; /* high-level state */
200  int nestingLevel; /* transaction nesting depth */
201  int gucNestLevel; /* GUC context nesting depth */
202  MemoryContext curTransactionContext; /* my xact-lifetime context */
203  ResourceOwner curTransactionOwner; /* my query resources */
204  MemoryContext priorContext; /* CurrentMemoryContext before xact started */
205  TransactionId *childXids; /* subcommitted child XIDs, in XID order */
206  int nChildXids; /* # of subcommitted child XIDs */
207  int maxChildXids; /* allocated size of childXids[] */
208  Oid prevUser; /* previous CurrentUserId setting */
209  int prevSecContext; /* previous SecurityRestrictionContext */
210  bool prevXactReadOnly; /* entry-time xact r/o state */
211  bool startedInRecovery; /* did we start in recovery? */
212  bool didLogXid; /* has xid been included in WAL record? */
213  int parallelModeLevel; /* Enter/ExitParallelMode counter */
214  bool parallelChildXact; /* is any parent transaction parallel? */
215  bool chain; /* start a new block after this one */
216  bool topXidLogged; /* for a subxact: is top-level XID logged? */
217  struct TransactionStateData *parent; /* back link to parent */
219 
221 
222 /*
223  * Serialized representation used to transmit transaction state to parallel
224  * workers through shared memory.
225  */
227 {
236 
237 /* The size of SerializedTransactionState, not including the final array. */
238 #define SerializedTransactionStateHeaderSize \
239  offsetof(SerializedTransactionState, parallelCurrentXids)
240 
241 /*
242  * CurrentTransactionState always points to the current transaction state
243  * block. It will point to TopTransactionStateData when not in a
244  * transaction at all, or when in a top-level transaction.
245  */
247  .state = TRANS_DEFAULT,
248  .blockState = TBLOCK_DEFAULT,
249  .topXidLogged = false,
250 };
251 
252 /*
253  * unreportedXids holds XIDs of all subtransactions that have not yet been
254  * reported in an XLOG_XACT_ASSIGNMENT record.
255  */
256 static int nUnreportedXids;
258 
260 
261 /*
262  * The subtransaction ID and command ID assignment counters are global
263  * to a whole transaction, so we do not keep them in the state stack.
264  */
268 
269 /*
270  * xactStartTimestamp is the value of transaction_timestamp().
271  * stmtStartTimestamp is the value of statement_timestamp().
272  * xactStopTimestamp is the time at which we log a commit / abort WAL record,
273  * or if that was skipped, the time of the first subsequent
274  * GetCurrentTransactionStopTimestamp() call.
275  *
276  * These do not change as we enter and exit subtransactions, so we don't
277  * keep them inside the TransactionState stack.
278  */
282 
283 /*
284  * GID to be used for preparing the current transaction. This is also
285  * global to a whole transaction, so we don't keep it in the state stack.
286  */
287 static char *prepareGID;
288 
289 /*
290  * Some commands want to force synchronous commit.
291  */
292 static bool forceSyncCommit = false;
293 
294 /* Flag for logging statements in a transaction. */
295 bool xact_is_sampled = false;
296 
297 /*
298  * Private context for transaction-abort work --- we reserve space for this
299  * at startup to ensure that AbortTransaction and AbortSubTransaction can work
300  * when we've run out of memory.
301  */
303 
304 /*
305  * List of add-on start- and end-of-xact callbacks
306  */
307 typedef struct XactCallbackItem
308 {
311  void *arg;
313 
315 
316 /*
317  * List of add-on start- and end-of-subxact callbacks
318  */
319 typedef struct SubXactCallbackItem
320 {
323  void *arg;
325 
327 
328 
329 /* local function prototypes */
331 static void AbortTransaction(void);
332 static void AtAbort_Memory(void);
333 static void AtCleanup_Memory(void);
334 static void AtAbort_ResourceOwner(void);
335 static void AtCCI_LocalCache(void);
336 static void AtCommit_Memory(void);
337 static void AtStart_Cache(void);
338 static void AtStart_Memory(void);
339 static void AtStart_ResourceOwner(void);
340 static void CallXactCallbacks(XactEvent event);
341 static void CallSubXactCallbacks(SubXactEvent event,
342  SubTransactionId mySubid,
343  SubTransactionId parentSubid);
344 static void CleanupTransaction(void);
345 static void CheckTransactionBlock(bool isTopLevel, bool throwError,
346  const char *stmtType);
347 static void CommitTransaction(void);
348 static TransactionId RecordTransactionAbort(bool isSubXact);
349 static void StartTransaction(void);
350 
351 static bool CommitTransactionCommandInternal(void);
352 static bool AbortCurrentTransactionInternal(void);
353 
354 static void StartSubTransaction(void);
355 static void CommitSubTransaction(void);
356 static void AbortSubTransaction(void);
357 static void CleanupSubTransaction(void);
358 static void PushTransaction(void);
359 static void PopTransaction(void);
360 
361 static void AtSubAbort_Memory(void);
362 static void AtSubCleanup_Memory(void);
363 static void AtSubAbort_ResourceOwner(void);
364 static void AtSubCommit_Memory(void);
365 static void AtSubStart_Memory(void);
366 static void AtSubStart_ResourceOwner(void);
367 
368 static void ShowTransactionState(const char *str);
369 static void ShowTransactionStateRec(const char *str, TransactionState s);
370 static const char *BlockStateAsString(TBlockState blockState);
371 static const char *TransStateAsString(TransState state);
372 
373 
374 /* ----------------------------------------------------------------
375  * transaction state accessors
376  * ----------------------------------------------------------------
377  */
378 
379 /*
380  * IsTransactionState
381  *
382  * This returns true if we are inside a valid transaction; that is,
383  * it is safe to initiate database access, take heavyweight locks, etc.
384  */
385 bool
387 {
389 
390  /*
391  * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
392  * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
393  * TRANS_PREPARE since it might be too soon or too late within those
394  * transition states to do anything interesting. Hence, the only "valid"
395  * state is TRANS_INPROGRESS.
396  */
397  return (s->state == TRANS_INPROGRESS);
398 }
399 
400 /*
401  * IsAbortedTransactionBlockState
402  *
403  * This returns true if we are within an aborted transaction block.
404  */
405 bool
407 {
409 
410  if (s->blockState == TBLOCK_ABORT ||
412  return true;
413 
414  return false;
415 }
416 
417 
418 /*
419  * GetTopTransactionId
420  *
421  * This will return the XID of the main transaction, assigning one if
422  * it's not yet set. Be careful to call this only inside a valid xact.
423  */
426 {
430 }
431 
432 /*
433  * GetTopTransactionIdIfAny
434  *
435  * This will return the XID of the main transaction, if one is assigned.
436  * It will return InvalidTransactionId if we are not currently inside a
437  * transaction, or inside a transaction that hasn't yet been assigned an XID.
438  */
441 {
443 }
444 
445 /*
446  * GetCurrentTransactionId
447  *
448  * This will return the XID of the current transaction (main or sub
449  * transaction), assigning one if it's not yet set. Be careful to call this
450  * only inside a valid xact.
451  */
454 {
456 
460 }
461 
462 /*
463  * GetCurrentTransactionIdIfAny
464  *
465  * This will return the XID of the current sub xact, if one is assigned.
466  * It will return InvalidTransactionId if we are not currently inside a
467  * transaction, or inside a transaction that hasn't been assigned an XID yet.
468  */
471 {
473 }
474 
475 /*
476  * GetTopFullTransactionId
477  *
478  * This will return the FullTransactionId of the main transaction, assigning
479  * one if it's not yet set. Be careful to call this only inside a valid xact.
480  */
483 {
487 }
488 
489 /*
490  * GetTopFullTransactionIdIfAny
491  *
492  * This will return the FullTransactionId of the main transaction, if one is
493  * assigned. It will return InvalidFullTransactionId if we are not currently
494  * inside a transaction, or inside a transaction that hasn't yet been assigned
495  * one.
496  */
499 {
501 }
502 
503 /*
504  * GetCurrentFullTransactionId
505  *
506  * This will return the FullTransactionId of the current transaction (main or
507  * sub transaction), assigning one if it's not yet set. Be careful to call
508  * this only inside a valid xact.
509  */
512 {
514 
517  return s->fullTransactionId;
518 }
519 
520 /*
521  * GetCurrentFullTransactionIdIfAny
522  *
523  * This will return the FullTransactionId of the current sub xact, if one is
524  * assigned. It will return InvalidFullTransactionId if we are not currently
525  * inside a transaction, or inside a transaction that hasn't been assigned one
526  * yet.
527  */
530 {
532 }
533 
534 /*
535  * MarkCurrentTransactionIdLoggedIfAny
536  *
537  * Remember that the current xid - if it is assigned - now has been wal logged.
538  */
539 void
541 {
544 }
545 
546 /*
547  * IsSubxactTopXidLogPending
548  *
549  * This is used to decide whether we need to WAL log the top-level XID for
550  * operation in a subtransaction. We require that for logical decoding, see
551  * LogicalDecodingProcessRecord.
552  *
553  * This returns true if wal_level >= logical and we are inside a valid
554  * subtransaction, for which the assignment was not yet written to any WAL
555  * record.
556  */
557 bool
559 {
560  /* check whether it is already logged */
562  return false;
563 
564  /* wal_level has to be logical */
565  if (!XLogLogicalInfoActive())
566  return false;
567 
568  /* we need to be in a transaction state */
569  if (!IsTransactionState())
570  return false;
571 
572  /* it has to be a subtransaction */
573  if (!IsSubTransaction())
574  return false;
575 
576  /* the subtransaction has to have a XID assigned */
578  return false;
579 
580  return true;
581 }
582 
583 /*
584  * MarkSubxactTopXidLogged
585  *
586  * Remember that the top transaction id for the current subtransaction is WAL
587  * logged now.
588  */
589 void
591 {
593 
595 }
596 
597 /*
598  * GetStableLatestTransactionId
599  *
600  * Get the transaction's XID if it has one, else read the next-to-be-assigned
601  * XID. Once we have a value, return that same value for the remainder of the
602  * current transaction. This is meant to provide the reference point for the
603  * age(xid) function, but might be useful for other maintenance tasks as well.
604  */
607 {
609  static TransactionId stablexid = InvalidTransactionId;
610 
611  if (lxid != MyProc->vxid.lxid)
612  {
613  lxid = MyProc->vxid.lxid;
614  stablexid = GetTopTransactionIdIfAny();
615  if (!TransactionIdIsValid(stablexid))
616  stablexid = ReadNextTransactionId();
617  }
618 
619  Assert(TransactionIdIsValid(stablexid));
620 
621  return stablexid;
622 }
623 
624 /*
625  * AssignTransactionId
626  *
627  * Assigns a new permanent FullTransactionId to the given TransactionState.
628  * We do not assign XIDs to transactions until/unless this is called.
629  * Also, any parent TransactionStates that don't yet have XIDs are assigned
630  * one; this maintains the invariant that a child transaction has an XID
631  * following its parent's.
632  */
633 static void
635 {
636  bool isSubXact = (s->parent != NULL);
637  ResourceOwner currentOwner;
638  bool log_unknown_top = false;
639 
640  /* Assert that caller didn't screw up */
643 
644  /*
645  * Workers synchronize transaction state at the beginning of each parallel
646  * operation, so we can't account for new XIDs at this point.
647  */
649  ereport(ERROR,
650  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
651  errmsg("cannot assign transaction IDs during a parallel operation")));
652 
653  /*
654  * Ensure parent(s) have XIDs, so that a child always has an XID later
655  * than its parent. Mustn't recurse here, or we might get a stack
656  * overflow if we're at the bottom of a huge stack of subtransactions none
657  * of which have XIDs yet.
658  */
659  if (isSubXact && !FullTransactionIdIsValid(s->parent->fullTransactionId))
660  {
661  TransactionState p = s->parent;
662  TransactionState *parents;
663  size_t parentOffset = 0;
664 
665  parents = palloc(sizeof(TransactionState) * s->nestingLevel);
666  while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
667  {
668  parents[parentOffset++] = p;
669  p = p->parent;
670  }
671 
672  /*
673  * This is technically a recursive call, but the recursion will never
674  * be more than one layer deep.
675  */
676  while (parentOffset != 0)
677  AssignTransactionId(parents[--parentOffset]);
678 
679  pfree(parents);
680  }
681 
682  /*
683  * When wal_level=logical, guarantee that a subtransaction's xid can only
684  * be seen in the WAL stream if its toplevel xid has been logged before.
685  * If necessary we log an xact_assignment record with fewer than
686  * PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't set
687  * for a transaction even though it appears in a WAL record, we just might
688  * superfluously log something. That can happen when an xid is included
689  * somewhere inside a wal record, but not in XLogRecord->xl_xid, like in
690  * xl_standby_locks.
691  */
692  if (isSubXact && XLogLogicalInfoActive() &&
694  log_unknown_top = true;
695 
696  /*
697  * Generate a new FullTransactionId and record its xid in PGPROC and
698  * pg_subtrans.
699  *
700  * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
701  * shared storage other than PGPROC; because if there's no room for it in
702  * PGPROC, the subtrans entry is needed to ensure that other backends see
703  * the Xid as "running". See GetNewTransactionId.
704  */
705  s->fullTransactionId = GetNewTransactionId(isSubXact);
706  if (!isSubXact)
708 
709  if (isSubXact)
712 
713  /*
714  * If it's a top-level transaction, the predicate locking system needs to
715  * be told about it too.
716  */
717  if (!isSubXact)
719 
720  /*
721  * Acquire lock on the transaction XID. (We assume this cannot block.) We
722  * have to ensure that the lock is assigned to the transaction's own
723  * ResourceOwner.
724  */
725  currentOwner = CurrentResourceOwner;
727 
729 
730  CurrentResourceOwner = currentOwner;
731 
732  /*
733  * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
734  * top-level transaction we issue a WAL record for the assignment. We
735  * include the top-level xid and all the subxids that have not yet been
736  * reported using XLOG_XACT_ASSIGNMENT records.
737  *
738  * This is required to limit the amount of shared memory required in a hot
739  * standby server to keep track of in-progress XIDs. See notes for
740  * RecordKnownAssignedTransactionIds().
741  *
742  * We don't keep track of the immediate parent of each subxid, only the
743  * top-level transaction that each subxact belongs to. This is correct in
744  * recovery only because aborted subtransactions are separately WAL
745  * logged.
746  *
747  * This is correct even for the case where several levels above us didn't
748  * have an xid assigned as we recursed up to them beforehand.
749  */
750  if (isSubXact && XLogStandbyInfoActive())
751  {
753  nUnreportedXids++;
754 
755  /*
756  * ensure this test matches similar one in
757  * RecoverPreparedTransactions()
758  */
760  log_unknown_top)
761  {
762  xl_xact_assignment xlrec;
763 
764  /*
765  * xtop is always set by now because we recurse up transaction
766  * stack to the highest unassigned xid and then come back down
767  */
768  xlrec.xtop = GetTopTransactionId();
770  xlrec.nsubxacts = nUnreportedXids;
771 
772  XLogBeginInsert();
773  XLogRegisterData((char *) &xlrec, MinSizeOfXactAssignment);
775  nUnreportedXids * sizeof(TransactionId));
776 
777  (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
778 
779  nUnreportedXids = 0;
780  /* mark top, not current xact as having been logged */
782  }
783  }
784 }
785 
786 /*
787  * GetCurrentSubTransactionId
788  */
791 {
793 
794  return s->subTransactionId;
795 }
796 
797 /*
798  * SubTransactionIsActive
799  *
800  * Test if the specified subxact ID is still active. Note caller is
801  * responsible for checking whether this ID is relevant to the current xact.
802  */
803 bool
805 {
807 
808  for (s = CurrentTransactionState; s != NULL; s = s->parent)
809  {
810  if (s->state == TRANS_ABORT)
811  continue;
812  if (s->subTransactionId == subxid)
813  return true;
814  }
815  return false;
816 }
817 
818 
819 /*
820  * GetCurrentCommandId
821  *
822  * "used" must be true if the caller intends to use the command ID to mark
823  * inserted/updated/deleted tuples. false means the ID is being fetched
824  * for read-only purposes (ie, as a snapshot validity cutoff). See
825  * CommandCounterIncrement() for discussion.
826  */
827 CommandId
829 {
830  /* this is global to a transaction, not subtransaction-local */
831  if (used)
832  {
833  /*
834  * Forbid setting currentCommandIdUsed in a parallel worker, because
835  * we have no provision for communicating this back to the leader. We
836  * could relax this restriction when currentCommandIdUsed was already
837  * true at the start of the parallel operation.
838  */
839  if (IsParallelWorker())
840  ereport(ERROR,
841  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
842  errmsg("cannot modify data in a parallel worker")));
843 
844  currentCommandIdUsed = true;
845  }
846  return currentCommandId;
847 }
848 
849 /*
850  * SetParallelStartTimestamps
851  *
852  * In a parallel worker, we should inherit the parent transaction's
853  * timestamps rather than setting our own. The parallel worker
854  * infrastructure must call this to provide those values before
855  * calling StartTransaction() or SetCurrentStatementStartTimestamp().
856  */
857 void
859 {
861  xactStartTimestamp = xact_ts;
862  stmtStartTimestamp = stmt_ts;
863 }
864 
865 /*
866  * GetCurrentTransactionStartTimestamp
867  */
870 {
871  return xactStartTimestamp;
872 }
873 
874 /*
875  * GetCurrentStatementStartTimestamp
876  */
879 {
880  return stmtStartTimestamp;
881 }
882 
883 /*
884  * GetCurrentTransactionStopTimestamp
885  *
886  * If the transaction stop time hasn't already been set, which can happen if
887  * we decided we don't need to log an XLOG record, set xactStopTimestamp.
888  */
891 {
893 
894  /* should only be called after commit / abort processing */
895  Assert(s->state == TRANS_DEFAULT ||
896  s->state == TRANS_COMMIT ||
897  s->state == TRANS_ABORT ||
898  s->state == TRANS_PREPARE);
899 
900  if (xactStopTimestamp == 0)
902 
903  return xactStopTimestamp;
904 }
905 
906 /*
907  * SetCurrentStatementStartTimestamp
908  *
909  * In a parallel worker, this should already have been provided by a call
910  * to SetParallelStartTimestamps().
911  */
912 void
914 {
915  if (!IsParallelWorker())
917  else
919 }
920 
921 /*
922  * GetCurrentTransactionNestLevel
923  *
924  * Note: this will return zero when not inside any transaction, one when
925  * inside a top-level transaction, etc.
926  */
927 int
929 {
931 
932  return s->nestingLevel;
933 }
934 
935 
936 /*
937  * TransactionIdIsCurrentTransactionId
938  */
939 bool
941 {
943 
944  /*
945  * We always say that BootstrapTransactionId is "not my transaction ID"
946  * even when it is (ie, during bootstrap). Along with the fact that
947  * transam.c always treats BootstrapTransactionId as already committed,
948  * this causes the heapam_visibility.c routines to see all tuples as
949  * committed, which is what we need during bootstrap. (Bootstrap mode
950  * only inserts tuples, it never updates or deletes them, so all tuples
951  * can be presumed good immediately.)
952  *
953  * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
954  * not my transaction ID, so we can just return "false" immediately for
955  * any non-normal XID.
956  */
957  if (!TransactionIdIsNormal(xid))
958  return false;
959 
961  return true;
962 
963  /*
964  * In parallel workers, the XIDs we must consider as current are stored in
965  * ParallelCurrentXids rather than the transaction-state stack. Note that
966  * the XIDs in this array are sorted numerically rather than according to
967  * transactionIdPrecedes order.
968  */
969  if (nParallelCurrentXids > 0)
970  {
971  int low,
972  high;
973 
974  low = 0;
975  high = nParallelCurrentXids - 1;
976  while (low <= high)
977  {
978  int middle;
979  TransactionId probe;
980 
981  middle = low + (high - low) / 2;
982  probe = ParallelCurrentXids[middle];
983  if (probe == xid)
984  return true;
985  else if (probe < xid)
986  low = middle + 1;
987  else
988  high = middle - 1;
989  }
990  return false;
991  }
992 
993  /*
994  * We will return true for the Xid of the current subtransaction, any of
995  * its subcommitted children, any of its parents, or any of their
996  * previously subcommitted children. However, a transaction being aborted
997  * is no longer "current", even though it may still have an entry on the
998  * state stack.
999  */
1000  for (s = CurrentTransactionState; s != NULL; s = s->parent)
1001  {
1002  int low,
1003  high;
1004 
1005  if (s->state == TRANS_ABORT)
1006  continue;
1008  continue; /* it can't have any child XIDs either */
1010  return true;
1011  /* As the childXids array is ordered, we can use binary search */
1012  low = 0;
1013  high = s->nChildXids - 1;
1014  while (low <= high)
1015  {
1016  int middle;
1017  TransactionId probe;
1018 
1019  middle = low + (high - low) / 2;
1020  probe = s->childXids[middle];
1021  if (TransactionIdEquals(probe, xid))
1022  return true;
1023  else if (TransactionIdPrecedes(probe, xid))
1024  low = middle + 1;
1025  else
1026  high = middle - 1;
1027  }
1028  }
1029 
1030  return false;
1031 }
1032 
1033 /*
1034  * TransactionStartedDuringRecovery
1035  *
1036  * Returns true if the current transaction started while recovery was still
1037  * in progress. Recovery might have ended since so RecoveryInProgress() might
1038  * return false already.
1039  */
1040 bool
1042 {
1044 }
1045 
1046 /*
1047  * EnterParallelMode
1048  */
1049 void
1051 {
1053 
1054  Assert(s->parallelModeLevel >= 0);
1055 
1056  ++s->parallelModeLevel;
1057 }
1058 
1059 /*
1060  * ExitParallelMode
1061  */
1062 void
1064 {
1066 
1067  Assert(s->parallelModeLevel > 0);
1070 
1071  --s->parallelModeLevel;
1072 }
1073 
1074 /*
1075  * IsInParallelMode
1076  *
1077  * Are we in a parallel operation, as either the leader or a worker? Check
1078  * this to prohibit operations that change backend-local state expected to
1079  * match across all workers. Mere caches usually don't require such a
1080  * restriction. State modified in a strict push/pop fashion, such as the
1081  * active snapshot stack, is often fine.
1082  *
1083  * We say we are in parallel mode if we are in a subxact of a transaction
1084  * that's initiated a parallel operation; for most purposes that context
1085  * has all the same restrictions.
1086  */
1087 bool
1089 {
1091 
1092  return s->parallelModeLevel != 0 || s->parallelChildXact;
1093 }
1094 
1095 /*
1096  * CommandCounterIncrement
1097  */
1098 void
1100 {
1101  /*
1102  * If the current value of the command counter hasn't been "used" to mark
1103  * tuples, we need not increment it, since there's no need to distinguish
1104  * a read-only command from others. This helps postpone command counter
1105  * overflow, and keeps no-op CommandCounterIncrement operations cheap.
1106  */
1108  {
1109  /*
1110  * Workers synchronize transaction state at the beginning of each
1111  * parallel operation, so we can't account for new commands after that
1112  * point.
1113  */
1115  ereport(ERROR,
1116  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1117  errmsg("cannot start commands during a parallel operation")));
1118 
1119  currentCommandId += 1;
1121  {
1122  currentCommandId -= 1;
1123  ereport(ERROR,
1124  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1125  errmsg("cannot have more than 2^32-2 commands in a transaction")));
1126  }
1127  currentCommandIdUsed = false;
1128 
1129  /* Propagate new command ID into static snapshots */
1131 
1132  /*
1133  * Make any catalog changes done by the just-completed command visible
1134  * in the local syscache. We obviously don't need to do this after a
1135  * read-only command. (But see hacks in inval.c to make real sure we
1136  * don't think a command that queued inval messages was read-only.)
1137  */
1138  AtCCI_LocalCache();
1139  }
1140 }
1141 
1142 /*
1143  * ForceSyncCommit
1144  *
1145  * Interface routine to allow commands to force a synchronous commit of the
1146  * current top-level transaction. Currently, two-phase commit does not
1147  * persist and restore this variable. So long as all callers use
1148  * PreventInTransactionBlock(), that omission has no consequences.
1149  */
1150 void
1152 {
1153  forceSyncCommit = true;
1154 }
1155 
1156 
1157 /* ----------------------------------------------------------------
1158  * StartTransaction stuff
1159  * ----------------------------------------------------------------
1160  */
1161 
1162 /*
1163  * AtStart_Cache
1164  */
1165 static void
1167 {
1169 }
1170 
1171 /*
1172  * AtStart_Memory
1173  */
1174 static void
1176 {
1178 
1179  /*
1180  * Remember the memory context that was active prior to transaction start.
1181  */
1183 
1184  /*
1185  * If this is the first time through, create a private context for
1186  * AbortTransaction to work in. By reserving some space now, we can
1187  * insulate AbortTransaction from out-of-memory scenarios. Like
1188  * ErrorContext, we set it up with slow growth rate and a nonzero minimum
1189  * size, so that space will be reserved immediately.
1190  */
1191  if (TransactionAbortContext == NULL)
1194  "TransactionAbortContext",
1195  32 * 1024,
1196  32 * 1024,
1197  32 * 1024);
1198 
1199  /*
1200  * Likewise, if this is the first time through, create a top-level context
1201  * for transaction-local data. This context will be reset at transaction
1202  * end, and then re-used in later transactions.
1203  */
1204  if (TopTransactionContext == NULL)
1207  "TopTransactionContext",
1209 
1210  /*
1211  * In a top-level transaction, CurTransactionContext is the same as
1212  * TopTransactionContext.
1213  */
1216 
1217  /* Make the CurTransactionContext active. */
1219 }
1220 
1221 /*
1222  * AtStart_ResourceOwner
1223  */
1224 static void
1226 {
1228 
1229  /*
1230  * We shouldn't have a transaction resource owner already.
1231  */
1233 
1234  /*
1235  * Create a toplevel resource owner for the transaction.
1236  */
1237  s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1238 
1242 }
1243 
1244 /* ----------------------------------------------------------------
1245  * StartSubTransaction stuff
1246  * ----------------------------------------------------------------
1247  */
1248 
1249 /*
1250  * AtSubStart_Memory
1251  */
1252 static void
1254 {
1256 
1257  Assert(CurTransactionContext != NULL);
1258 
1259  /*
1260  * Remember the context that was active prior to subtransaction start.
1261  */
1263 
1264  /*
1265  * Create a CurTransactionContext, which will be used to hold data that
1266  * survives subtransaction commit but disappears on subtransaction abort.
1267  * We make it a child of the immediate parent's CurTransactionContext.
1268  */
1270  "CurTransactionContext",
1273 
1274  /* Make the CurTransactionContext active. */
1276 }
1277 
1278 /*
1279  * AtSubStart_ResourceOwner
1280  */
1281 static void
1283 {
1285 
1286  Assert(s->parent != NULL);
1287 
1288  /*
1289  * Create a resource owner for the subtransaction. We make it a child of
1290  * the immediate parent's resource owner.
1291  */
1292  s->curTransactionOwner =
1294  "SubTransaction");
1295 
1298 }
1299 
1300 /* ----------------------------------------------------------------
1301  * CommitTransaction stuff
1302  * ----------------------------------------------------------------
1303  */
1304 
1305 /*
1306  * RecordTransactionCommit
1307  *
1308  * Returns latest XID among xact and its children, or InvalidTransactionId
1309  * if the xact has no XID. (We compute that here just because it's easier.)
1310  *
1311  * If you change this function, see RecordTransactionCommitPrepared also.
1312  */
1313 static TransactionId
1315 {
1317  bool markXidCommitted = TransactionIdIsValid(xid);
1318  TransactionId latestXid = InvalidTransactionId;
1319  int nrels;
1320  RelFileLocator *rels;
1321  int nchildren;
1322  TransactionId *children;
1323  int ndroppedstats = 0;
1324  xl_xact_stats_item *droppedstats = NULL;
1325  int nmsgs = 0;
1326  SharedInvalidationMessage *invalMessages = NULL;
1327  bool RelcacheInitFileInval = false;
1328  bool wrote_xlog;
1329 
1330  /*
1331  * Log pending invalidations for logical decoding of in-progress
1332  * transactions. Normally for DDLs, we log this at each command end,
1333  * however, for certain cases where we directly update the system table
1334  * without a transaction block, the invalidations are not logged till this
1335  * time.
1336  */
1337  if (XLogLogicalInfoActive())
1339 
1340  /* Get data needed for commit record */
1341  nrels = smgrGetPendingDeletes(true, &rels);
1342  nchildren = xactGetCommittedChildren(&children);
1343  ndroppedstats = pgstat_get_transactional_drops(true, &droppedstats);
1344  if (XLogStandbyInfoActive())
1345  nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
1346  &RelcacheInitFileInval);
1347  wrote_xlog = (XactLastRecEnd != 0);
1348 
1349  /*
1350  * If we haven't been assigned an XID yet, we neither can, nor do we want
1351  * to write a COMMIT record.
1352  */
1353  if (!markXidCommitted)
1354  {
1355  /*
1356  * We expect that every RelationDropStorage is followed by a catalog
1357  * update, and hence XID assignment, so we shouldn't get here with any
1358  * pending deletes. Same is true for dropping stats.
1359  *
1360  * Use a real test not just an Assert to check this, since it's a bit
1361  * fragile.
1362  */
1363  if (nrels != 0 || ndroppedstats != 0)
1364  elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
1365 
1366  /* Can't have child XIDs either; AssignTransactionId enforces this */
1367  Assert(nchildren == 0);
1368 
1369  /*
1370  * Transactions without an assigned xid can contain invalidation
1371  * messages (e.g. explicit relcache invalidations or catcache
1372  * invalidations for inplace updates); standbys need to process those.
1373  * We can't emit a commit record without an xid, and we don't want to
1374  * force assigning an xid, because that'd be problematic for e.g.
1375  * vacuum. Hence we emit a bespoke record for the invalidations. We
1376  * don't want to use that in case a commit record is emitted, so they
1377  * happen synchronously with commits (besides not wanting to emit more
1378  * WAL records).
1379  */
1380  if (nmsgs != 0)
1381  {
1382  LogStandbyInvalidations(nmsgs, invalMessages,
1383  RelcacheInitFileInval);
1384  wrote_xlog = true; /* not strictly necessary */
1385  }
1386 
1387  /*
1388  * If we didn't create XLOG entries, we're done here; otherwise we
1389  * should trigger flushing those entries the same as a commit record
1390  * would. This will primarily happen for HOT pruning and the like; we
1391  * want these to be flushed to disk in due time.
1392  */
1393  if (!wrote_xlog)
1394  goto cleanup;
1395  }
1396  else
1397  {
1398  bool replorigin;
1399 
1400  /*
1401  * Are we using the replication origins feature? Or, in other words,
1402  * are we replaying remote actions?
1403  */
1404  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1406 
1407  /*
1408  * Mark ourselves as within our "commit critical section". This
1409  * forces any concurrent checkpoint to wait until we've updated
1410  * pg_xact. Without this, it is possible for the checkpoint to set
1411  * REDO after the XLOG record but fail to flush the pg_xact update to
1412  * disk, leading to loss of the transaction commit if the system
1413  * crashes a little later.
1414  *
1415  * Note: we could, but don't bother to, set this flag in
1416  * RecordTransactionAbort. That's because loss of a transaction abort
1417  * is noncritical; the presumption would be that it aborted, anyway.
1418  *
1419  * It's safe to change the delayChkptFlags flag of our own backend
1420  * without holding the ProcArrayLock, since we're the only one
1421  * modifying it. This makes checkpoint's determination of which xacts
1422  * are delaying the checkpoint a bit fuzzy, but it doesn't matter.
1423  */
1427 
1428  /*
1429  * Insert the commit XLOG record.
1430  */
1432  nchildren, children, nrels, rels,
1433  ndroppedstats, droppedstats,
1434  nmsgs, invalMessages,
1435  RelcacheInitFileInval,
1436  MyXactFlags,
1437  InvalidTransactionId, NULL /* plain commit */ );
1438 
1439  if (replorigin)
1440  /* Move LSNs forward for this replication origin */
1442  XactLastRecEnd);
1443 
1444  /*
1445  * Record commit timestamp. The value comes from plain commit
1446  * timestamp if there's no replication origin; otherwise, the
1447  * timestamp was already set in replorigin_session_origin_timestamp by
1448  * replication.
1449  *
1450  * We don't need to WAL-log anything here, as the commit record
1451  * written above already contains the data.
1452  */
1453 
1454  if (!replorigin || replorigin_session_origin_timestamp == 0)
1456 
1457  TransactionTreeSetCommitTsData(xid, nchildren, children,
1460  }
1461 
1462  /*
1463  * Check if we want to commit asynchronously. We can allow the XLOG flush
1464  * to happen asynchronously if synchronous_commit=off, or if the current
1465  * transaction has not performed any WAL-logged operation or didn't assign
1466  * an xid. The transaction can end up not writing any WAL, even if it has
1467  * an xid, if it only wrote to temporary and/or unlogged tables. It can
1468  * end up having written WAL without an xid if it did HOT pruning. In
1469  * case of a crash, the loss of such a transaction will be irrelevant;
1470  * temp tables will be lost anyway, unlogged tables will be truncated and
1471  * HOT pruning will be done again later. (Given the foregoing, you might
1472  * think that it would be unnecessary to emit the XLOG record at all in
1473  * this case, but we don't currently try to do that. It would certainly
1474  * cause problems at least in Hot Standby mode, where the
1475  * KnownAssignedXids machinery requires tracking every XID assignment. It
1476  * might be OK to skip it only when wal_level < replica, but for now we
1477  * don't.)
1478  *
1479  * However, if we're doing cleanup of any non-temp rels or committing any
1480  * command that wanted to force sync commit, then we must flush XLOG
1481  * immediately. (We must not allow asynchronous commit if there are any
1482  * non-temp tables to be deleted, because we might delete the files before
1483  * the COMMIT record is flushed to disk. We do allow asynchronous commit
1484  * if all to-be-deleted tables are temporary though, since they are lost
1485  * anyway if we crash.)
1486  */
1487  if ((wrote_xlog && markXidCommitted &&
1489  forceSyncCommit || nrels > 0)
1490  {
1492 
1493  /*
1494  * Now we may update the CLOG, if we wrote a COMMIT record above
1495  */
1496  if (markXidCommitted)
1497  TransactionIdCommitTree(xid, nchildren, children);
1498  }
1499  else
1500  {
1501  /*
1502  * Asynchronous commit case:
1503  *
1504  * This enables possible committed transaction loss in the case of a
1505  * postmaster crash because WAL buffers are left unwritten. Ideally we
1506  * could issue the WAL write without the fsync, but some
1507  * wal_sync_methods do not allow separate write/fsync.
1508  *
1509  * Report the latest async commit LSN, so that the WAL writer knows to
1510  * flush this commit.
1511  */
1513 
1514  /*
1515  * We must not immediately update the CLOG, since we didn't flush the
1516  * XLOG. Instead, we store the LSN up to which the XLOG must be
1517  * flushed before the CLOG may be updated.
1518  */
1519  if (markXidCommitted)
1520  TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1521  }
1522 
1523  /*
1524  * If we entered a commit critical section, leave it now, and let
1525  * checkpoints proceed.
1526  */
1527  if (markXidCommitted)
1528  {
1530  END_CRIT_SECTION();
1531  }
1532 
1533  /* Compute latestXid while we have the child XIDs handy */
1534  latestXid = TransactionIdLatest(xid, nchildren, children);
1535 
1536  /*
1537  * Wait for synchronous replication, if required. Similar to the decision
1538  * above about using committing asynchronously we only want to wait if
1539  * this backend assigned an xid and wrote WAL. No need to wait if an xid
1540  * was assigned due to temporary/unlogged tables or due to HOT pruning.
1541  *
1542  * Note that at this stage we have marked clog, but still show as running
1543  * in the procarray and continue to hold locks.
1544  */
1545  if (wrote_xlog && markXidCommitted)
1547 
1548  /* remember end of last commit record */
1550 
1551  /* Reset XactLastRecEnd until the next transaction writes something */
1552  XactLastRecEnd = 0;
1553 cleanup:
1554  /* Clean up local data */
1555  if (rels)
1556  pfree(rels);
1557  if (ndroppedstats)
1558  pfree(droppedstats);
1559 
1560  return latestXid;
1561 }
1562 
1563 
1564 /*
1565  * AtCCI_LocalCache
1566  */
1567 static void
1569 {
1570  /*
1571  * Make any pending relation map changes visible. We must do this before
1572  * processing local sinval messages, so that the map changes will get
1573  * reflected into the relcache when relcache invals are processed.
1574  */
1576 
1577  /*
1578  * Make catalog changes visible to me for the next command.
1579  */
1581 }
1582 
1583 /*
1584  * AtCommit_Memory
1585  */
1586 static void
1588 {
1590 
1591  /*
1592  * Return to the memory context that was current before we started the
1593  * transaction. (In principle, this could not be any of the contexts we
1594  * are about to delete. If it somehow is, assertions in mcxt.c will
1595  * complain.)
1596  */
1598 
1599  /*
1600  * Release all transaction-local memory. TopTransactionContext survives
1601  * but becomes empty; any sub-contexts go away.
1602  */
1603  Assert(TopTransactionContext != NULL);
1605 
1606  /*
1607  * Clear these pointers as a pro-forma matter. (Notionally, while
1608  * TopTransactionContext still exists, it's currently not associated with
1609  * this TransactionState struct.)
1610  */
1611  CurTransactionContext = NULL;
1612  s->curTransactionContext = NULL;
1613 }
1614 
1615 /* ----------------------------------------------------------------
1616  * CommitSubTransaction stuff
1617  * ----------------------------------------------------------------
1618  */
1619 
1620 /*
1621  * AtSubCommit_Memory
1622  */
1623 static void
1625 {
1627 
1628  Assert(s->parent != NULL);
1629 
1630  /* Return to parent transaction level's memory context. */
1633 
1634  /*
1635  * Ordinarily we cannot throw away the child's CurTransactionContext,
1636  * since the data it contains will be needed at upper commit. However, if
1637  * there isn't actually anything in it, we can throw it away. This avoids
1638  * a small memory leak in the common case of "trivial" subxacts.
1639  */
1641  {
1643  s->curTransactionContext = NULL;
1644  }
1645 }
1646 
1647 /*
1648  * AtSubCommit_childXids
1649  *
1650  * Pass my own XID and my child XIDs up to my parent as committed children.
1651  */
1652 static void
1654 {
1656  int new_nChildXids;
1657 
1658  Assert(s->parent != NULL);
1659 
1660  /*
1661  * The parent childXids array will need to hold my XID and all my
1662  * childXids, in addition to the XIDs already there.
1663  */
1664  new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1665 
1666  /* Allocate or enlarge the parent array if necessary */
1667  if (s->parent->maxChildXids < new_nChildXids)
1668  {
1669  int new_maxChildXids;
1670  TransactionId *new_childXids;
1671 
1672  /*
1673  * Make it 2x what's needed right now, to avoid having to enlarge it
1674  * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1675  * is what ensures that we don't need to worry about integer overflow
1676  * here or in the calculation of new_nChildXids.)
1677  */
1678  new_maxChildXids = Min(new_nChildXids * 2,
1679  (int) (MaxAllocSize / sizeof(TransactionId)));
1680 
1681  if (new_maxChildXids < new_nChildXids)
1682  ereport(ERROR,
1683  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1684  errmsg("maximum number of committed subtransactions (%d) exceeded",
1685  (int) (MaxAllocSize / sizeof(TransactionId)))));
1686 
1687  /*
1688  * We keep the child-XID arrays in TopTransactionContext; this avoids
1689  * setting up child-transaction contexts for what might be just a few
1690  * bytes of grandchild XIDs.
1691  */
1692  if (s->parent->childXids == NULL)
1693  new_childXids =
1695  new_maxChildXids * sizeof(TransactionId));
1696  else
1697  new_childXids = repalloc(s->parent->childXids,
1698  new_maxChildXids * sizeof(TransactionId));
1699 
1700  s->parent->childXids = new_childXids;
1701  s->parent->maxChildXids = new_maxChildXids;
1702  }
1703 
1704  /*
1705  * Copy all my XIDs to parent's array.
1706  *
1707  * Note: We rely on the fact that the XID of a child always follows that
1708  * of its parent. By copying the XID of this subtransaction before the
1709  * XIDs of its children, we ensure that the array stays ordered. Likewise,
1710  * all XIDs already in the array belong to subtransactions started and
1711  * subcommitted before us, so their XIDs must precede ours.
1712  */
1714 
1715  if (s->nChildXids > 0)
1716  memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1717  s->childXids,
1718  s->nChildXids * sizeof(TransactionId));
1719 
1720  s->parent->nChildXids = new_nChildXids;
1721 
1722  /* Release child's array to avoid leakage */
1723  if (s->childXids != NULL)
1724  pfree(s->childXids);
1725  /* We must reset these to avoid double-free if fail later in commit */
1726  s->childXids = NULL;
1727  s->nChildXids = 0;
1728  s->maxChildXids = 0;
1729 }
1730 
1731 /* ----------------------------------------------------------------
1732  * AbortTransaction stuff
1733  * ----------------------------------------------------------------
1734  */
1735 
1736 /*
1737  * RecordTransactionAbort
1738  *
1739  * Returns latest XID among xact and its children, or InvalidTransactionId
1740  * if the xact has no XID. (We compute that here just because it's easier.)
1741  */
1742 static TransactionId
1743 RecordTransactionAbort(bool isSubXact)
1744 {
1746  TransactionId latestXid;
1747  int nrels;
1748  RelFileLocator *rels;
1749  int ndroppedstats = 0;
1750  xl_xact_stats_item *droppedstats = NULL;
1751  int nchildren;
1752  TransactionId *children;
1753  TimestampTz xact_time;
1754  bool replorigin;
1755 
1756  /*
1757  * If we haven't been assigned an XID, nobody will care whether we aborted
1758  * or not. Hence, we're done in that case. It does not matter if we have
1759  * rels to delete (note that this routine is not responsible for actually
1760  * deleting 'em). We cannot have any child XIDs, either.
1761  */
1762  if (!TransactionIdIsValid(xid))
1763  {
1764  /* Reset XactLastRecEnd until the next transaction writes something */
1765  if (!isSubXact)
1766  XactLastRecEnd = 0;
1767  return InvalidTransactionId;
1768  }
1769 
1770  /*
1771  * We have a valid XID, so we should write an ABORT record for it.
1772  *
1773  * We do not flush XLOG to disk here, since the default assumption after a
1774  * crash would be that we aborted, anyway. For the same reason, we don't
1775  * need to worry about interlocking against checkpoint start.
1776  */
1777 
1778  /*
1779  * Check that we haven't aborted halfway through RecordTransactionCommit.
1780  */
1781  if (TransactionIdDidCommit(xid))
1782  elog(PANIC, "cannot abort transaction %u, it was already committed",
1783  xid);
1784 
1785  /*
1786  * Are we using the replication origins feature? Or, in other words, are
1787  * we replaying remote actions?
1788  */
1789  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1791 
1792  /* Fetch the data we need for the abort record */
1793  nrels = smgrGetPendingDeletes(false, &rels);
1794  nchildren = xactGetCommittedChildren(&children);
1795  ndroppedstats = pgstat_get_transactional_drops(false, &droppedstats);
1796 
1797  /* XXX do we really need a critical section here? */
1799 
1800  /* Write the ABORT record */
1801  if (isSubXact)
1802  xact_time = GetCurrentTimestamp();
1803  else
1804  {
1805  xact_time = GetCurrentTransactionStopTimestamp();
1806  }
1807 
1808  XactLogAbortRecord(xact_time,
1809  nchildren, children,
1810  nrels, rels,
1811  ndroppedstats, droppedstats,
1813  NULL);
1814 
1815  if (replorigin)
1816  /* Move LSNs forward for this replication origin */
1818  XactLastRecEnd);
1819 
1820  /*
1821  * Report the latest async abort LSN, so that the WAL writer knows to
1822  * flush this abort. There's nothing to be gained by delaying this, since
1823  * WALWriter may as well do this when it can. This is important with
1824  * streaming replication because if we don't flush WAL regularly we will
1825  * find that large aborts leave us with a long backlog for when commits
1826  * occur after the abort, increasing our window of data loss should
1827  * problems occur at that point.
1828  */
1829  if (!isSubXact)
1831 
1832  /*
1833  * Mark the transaction aborted in clog. This is not absolutely necessary
1834  * but we may as well do it while we are here; also, in the subxact case
1835  * it is helpful because XactLockTableWait makes use of it to avoid
1836  * waiting for already-aborted subtransactions. It is OK to do it without
1837  * having flushed the ABORT record to disk, because in event of a crash
1838  * we'd be assumed to have aborted anyway.
1839  */
1840  TransactionIdAbortTree(xid, nchildren, children);
1841 
1842  END_CRIT_SECTION();
1843 
1844  /* Compute latestXid while we have the child XIDs handy */
1845  latestXid = TransactionIdLatest(xid, nchildren, children);
1846 
1847  /*
1848  * If we're aborting a subtransaction, we can immediately remove failed
1849  * XIDs from PGPROC's cache of running child XIDs. We do that here for
1850  * subxacts, because we already have the child XID array at hand. For
1851  * main xacts, the equivalent happens just after this function returns.
1852  */
1853  if (isSubXact)
1854  XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1855 
1856  /* Reset XactLastRecEnd until the next transaction writes something */
1857  if (!isSubXact)
1858  XactLastRecEnd = 0;
1859 
1860  /* And clean up local data */
1861  if (rels)
1862  pfree(rels);
1863  if (ndroppedstats)
1864  pfree(droppedstats);
1865 
1866  return latestXid;
1867 }
1868 
1869 /*
1870  * AtAbort_Memory
1871  */
1872 static void
1874 {
1875  /*
1876  * Switch into TransactionAbortContext, which should have some free space
1877  * even if nothing else does. We'll work in this context until we've
1878  * finished cleaning up.
1879  *
1880  * It is barely possible to get here when we've not been able to create
1881  * TransactionAbortContext yet; if so use TopMemoryContext.
1882  */
1883  if (TransactionAbortContext != NULL)
1885  else
1887 }
1888 
1889 /*
1890  * AtSubAbort_Memory
1891  */
1892 static void
1894 {
1896 
1898 }
1899 
1900 
1901 /*
1902  * AtAbort_ResourceOwner
1903  */
1904 static void
1906 {
1907  /*
1908  * Make sure we have a valid ResourceOwner, if possible (else it will be
1909  * NULL, which is OK)
1910  */
1912 }
1913 
1914 /*
1915  * AtSubAbort_ResourceOwner
1916  */
1917 static void
1919 {
1921 
1922  /* Make sure we have a valid ResourceOwner */
1924 }
1925 
1926 
1927 /*
1928  * AtSubAbort_childXids
1929  */
1930 static void
1932 {
1934 
1935  /*
1936  * We keep the child-XID arrays in TopTransactionContext (see
1937  * AtSubCommit_childXids). This means we'd better free the array
1938  * explicitly at abort to avoid leakage.
1939  */
1940  if (s->childXids != NULL)
1941  pfree(s->childXids);
1942  s->childXids = NULL;
1943  s->nChildXids = 0;
1944  s->maxChildXids = 0;
1945 
1946  /*
1947  * We could prune the unreportedXids array here. But we don't bother. That
1948  * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
1949  * would likely introduce more CPU time into the more common paths, so we
1950  * choose not to do that.
1951  */
1952 }
1953 
1954 /* ----------------------------------------------------------------
1955  * CleanupTransaction stuff
1956  * ----------------------------------------------------------------
1957  */
1958 
1959 /*
1960  * AtCleanup_Memory
1961  */
1962 static void
1964 {
1966 
1967  /* Should be at top level */
1968  Assert(s->parent == NULL);
1969 
1970  /*
1971  * Return to the memory context that was current before we started the
1972  * transaction. (In principle, this could not be any of the contexts we
1973  * are about to delete. If it somehow is, assertions in mcxt.c will
1974  * complain.)
1975  */
1977 
1978  /*
1979  * Clear the special abort context for next time.
1980  */
1981  if (TransactionAbortContext != NULL)
1983 
1984  /*
1985  * Release all transaction-local memory, the same as in AtCommit_Memory,
1986  * except we must cope with the possibility that we didn't get as far as
1987  * creating TopTransactionContext.
1988  */
1989  if (TopTransactionContext != NULL)
1991 
1992  /*
1993  * Clear these pointers as a pro-forma matter. (Notionally, while
1994  * TopTransactionContext still exists, it's currently not associated with
1995  * this TransactionState struct.)
1996  */
1997  CurTransactionContext = NULL;
1998  s->curTransactionContext = NULL;
1999 }
2000 
2001 
2002 /* ----------------------------------------------------------------
2003  * CleanupSubTransaction stuff
2004  * ----------------------------------------------------------------
2005  */
2006 
2007 /*
2008  * AtSubCleanup_Memory
2009  */
2010 static void
2012 {
2014 
2015  Assert(s->parent != NULL);
2016 
2017  /*
2018  * Return to the memory context that was current before we started the
2019  * subtransaction. (In principle, this could not be any of the contexts
2020  * we are about to delete. If it somehow is, assertions in mcxt.c will
2021  * complain.)
2022  */
2024 
2025  /* Update CurTransactionContext (might not be same as priorContext) */
2027 
2028  /*
2029  * Clear the special abort context for next time.
2030  */
2031  if (TransactionAbortContext != NULL)
2033 
2034  /*
2035  * Delete the subxact local memory contexts. Its CurTransactionContext can
2036  * go too (note this also kills CurTransactionContexts from any children
2037  * of the subxact).
2038  */
2039  if (s->curTransactionContext)
2041  s->curTransactionContext = NULL;
2042 }
2043 
2044 /* ----------------------------------------------------------------
2045  * interface routines
2046  * ----------------------------------------------------------------
2047  */
2048 
2049 /*
2050  * StartTransaction
2051  */
2052 static void
2054 {
2055  TransactionState s;
2056  VirtualTransactionId vxid;
2057 
2058  /*
2059  * Let's just make sure the state stack is empty
2060  */
2063 
2065 
2066  /* check the current transaction state */
2067  Assert(s->state == TRANS_DEFAULT);
2068 
2069  /*
2070  * Set the current transaction state information appropriately during
2071  * start processing. Note that once the transaction status is switched
2072  * this process cannot fail until the user ID and the security context
2073  * flags are fetched below.
2074  */
2075  s->state = TRANS_START;
2076  s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
2077 
2078  /* Determine if statements are logged in this transaction */
2080  (log_xact_sample_rate == 1 ||
2082 
2083  /*
2084  * initialize current transaction state fields
2085  *
2086  * note: prevXactReadOnly is not used at the outermost level
2087  */
2088  s->nestingLevel = 1;
2089  s->gucNestLevel = 1;
2090  s->childXids = NULL;
2091  s->nChildXids = 0;
2092  s->maxChildXids = 0;
2093 
2094  /*
2095  * Once the current user ID and the security context flags are fetched,
2096  * both will be properly reset even if transaction startup fails.
2097  */
2099 
2100  /* SecurityRestrictionContext should never be set outside a transaction */
2101  Assert(s->prevSecContext == 0);
2102 
2103  /*
2104  * Make sure we've reset xact state variables
2105  *
2106  * If recovery is still in progress, mark this transaction as read-only.
2107  * We have lower level defences in XLogInsert and elsewhere to stop us
2108  * from modifying data during recovery, but this gives the normal
2109  * indication to the user that the transaction is read-only.
2110  */
2111  if (RecoveryInProgress())
2112  {
2113  s->startedInRecovery = true;
2114  XactReadOnly = true;
2115  }
2116  else
2117  {
2118  s->startedInRecovery = false;
2120  }
2123  forceSyncCommit = false;
2124  MyXactFlags = 0;
2125 
2126  /*
2127  * reinitialize within-transaction counters
2128  */
2132  currentCommandIdUsed = false;
2133 
2134  /*
2135  * initialize reported xid accounting
2136  */
2137  nUnreportedXids = 0;
2138  s->didLogXid = false;
2139 
2140  /*
2141  * must initialize resource-management stuff first
2142  */
2143  AtStart_Memory();
2145 
2146  /*
2147  * Assign a new LocalTransactionId, and combine it with the proc number to
2148  * form a virtual transaction id.
2149  */
2150  vxid.procNumber = MyProcNumber;
2152 
2153  /*
2154  * Lock the virtual transaction id before we announce it in the proc array
2155  */
2157 
2158  /*
2159  * Advertise it in the proc array. We assume assignment of
2160  * localTransactionId is atomic, and the proc number should be set
2161  * already.
2162  */
2165 
2166  TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
2167 
2168  /*
2169  * set transaction_timestamp() (a/k/a now()). Normally, we want this to
2170  * be the same as the first command's statement_timestamp(), so don't do a
2171  * fresh GetCurrentTimestamp() call (which'd be expensive anyway). But
2172  * for transactions started inside procedures (i.e., nonatomic SPI
2173  * contexts), we do need to advance the timestamp. Also, in a parallel
2174  * worker, the timestamp should already have been provided by a call to
2175  * SetParallelStartTimestamps().
2176  */
2177  if (!IsParallelWorker())
2178  {
2181  else
2183  }
2184  else
2185  Assert(xactStartTimestamp != 0);
2187  /* Mark xactStopTimestamp as unset. */
2188  xactStopTimestamp = 0;
2189 
2190  /*
2191  * initialize other subsystems for new transaction
2192  */
2193  AtStart_GUC();
2194  AtStart_Cache();
2196 
2197  /*
2198  * done with start processing, set current transaction state to "in
2199  * progress"
2200  */
2201  s->state = TRANS_INPROGRESS;
2202 
2203  /* Schedule transaction timeout */
2204  if (TransactionTimeout > 0)
2206 
2207  ShowTransactionState("StartTransaction");
2208 }
2209 
2210 
2211 /*
2212  * CommitTransaction
2213  *
2214  * NB: if you change this routine, better look at PrepareTransaction too!
2215  */
2216 static void
2218 {
2220  TransactionId latestXid;
2221  bool is_parallel_worker;
2222 
2223  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2224 
2225  /* Enforce parallel mode restrictions during parallel worker commit. */
2226  if (is_parallel_worker)
2228 
2229  ShowTransactionState("CommitTransaction");
2230 
2231  /*
2232  * check the current transaction state
2233  */
2234  if (s->state != TRANS_INPROGRESS)
2235  elog(WARNING, "CommitTransaction while in %s state",
2237  Assert(s->parent == NULL);
2238 
2239  /*
2240  * Do pre-commit processing that involves calling user-defined code, such
2241  * as triggers. SECURITY_RESTRICTED_OPERATION contexts must not queue an
2242  * action that would run here, because that would bypass the sandbox.
2243  * Since closing cursors could queue trigger actions, triggers could open
2244  * cursors, etc, we have to keep looping until there's nothing left to do.
2245  */
2246  for (;;)
2247  {
2248  /*
2249  * Fire all currently pending deferred triggers.
2250  */
2252 
2253  /*
2254  * Close open portals (converting holdable ones into static portals).
2255  * If there weren't any, we are done ... otherwise loop back to check
2256  * if they queued deferred triggers. Lather, rinse, repeat.
2257  */
2258  if (!PreCommit_Portals(false))
2259  break;
2260  }
2261 
2262  /*
2263  * The remaining actions cannot call any user-defined code, so it's safe
2264  * to start shutting down within-transaction services. But note that most
2265  * of this stuff could still throw an error, which would switch us into
2266  * the transaction-abort path.
2267  */
2268 
2271 
2272  /*
2273  * If this xact has started any unfinished parallel operation, clean up
2274  * its workers, warning about leaked resources. (But we don't actually
2275  * reset parallelModeLevel till entering TRANS_COMMIT, a bit below. This
2276  * keeps parallel mode restrictions active as long as possible in a
2277  * parallel worker.)
2278  */
2279  AtEOXact_Parallel(true);
2280  if (is_parallel_worker)
2281  {
2282  if (s->parallelModeLevel != 1)
2283  elog(WARNING, "parallelModeLevel is %d not 1 at end of parallel worker transaction",
2284  s->parallelModeLevel);
2285  }
2286  else
2287  {
2288  if (s->parallelModeLevel != 0)
2289  elog(WARNING, "parallelModeLevel is %d not 0 at end of transaction",
2290  s->parallelModeLevel);
2291  }
2292 
2293  /* Shut down the deferred-trigger manager */
2294  AfterTriggerEndXact(true);
2295 
2296  /*
2297  * Let ON COMMIT management do its thing (must happen after closing
2298  * cursors, to avoid dangling-reference problems)
2299  */
2301 
2302  /*
2303  * Synchronize files that are created and not WAL-logged during this
2304  * transaction. This must happen before AtEOXact_RelationMap(), so that we
2305  * don't see committed-but-broken files after a crash.
2306  */
2307  smgrDoPendingSyncs(true, is_parallel_worker);
2308 
2309  /* close large objects before lower-level cleanup */
2310  AtEOXact_LargeObject(true);
2311 
2312  /*
2313  * Insert notifications sent by NOTIFY commands into the queue. This
2314  * should be late in the pre-commit sequence to minimize time spent
2315  * holding the notify-insertion lock. However, this could result in
2316  * creating a snapshot, so we must do it before serializable cleanup.
2317  */
2318  PreCommit_Notify();
2319 
2320  /*
2321  * Mark serializable transaction as complete for predicate locking
2322  * purposes. This should be done as late as we can put it and still allow
2323  * errors to be raised for failure patterns found at commit. This is not
2324  * appropriate in a parallel worker however, because we aren't committing
2325  * the leader's transaction and its serializable state will live on.
2326  */
2327  if (!is_parallel_worker)
2329 
2330  /* Prevent cancel/die interrupt while cleaning up */
2331  HOLD_INTERRUPTS();
2332 
2333  /* Commit updates to the relation map --- do this as late as possible */
2334  AtEOXact_RelationMap(true, is_parallel_worker);
2335 
2336  /*
2337  * set the current transaction state information appropriately during
2338  * commit processing
2339  */
2340  s->state = TRANS_COMMIT;
2341  s->parallelModeLevel = 0;
2342  s->parallelChildXact = false; /* should be false already */
2343 
2344  /* Disable transaction timeout */
2345  if (TransactionTimeout > 0)
2347 
2348  if (!is_parallel_worker)
2349  {
2350  /*
2351  * We need to mark our XIDs as committed in pg_xact. This is where we
2352  * durably commit.
2353  */
2354  latestXid = RecordTransactionCommit();
2355  }
2356  else
2357  {
2358  /*
2359  * We must not mark our XID committed; the parallel leader is
2360  * responsible for that.
2361  */
2362  latestXid = InvalidTransactionId;
2363 
2364  /*
2365  * Make sure the leader will know about any WAL we wrote before it
2366  * commits.
2367  */
2369  }
2370 
2371  TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->vxid.lxid);
2372 
2373  /*
2374  * Let others know about no transaction in progress by me. Note that this
2375  * must be done _before_ releasing locks we hold and _after_
2376  * RecordTransactionCommit.
2377  */
2378  ProcArrayEndTransaction(MyProc, latestXid);
2379 
2380  /*
2381  * This is all post-commit cleanup. Note that if an error is raised here,
2382  * it's too late to abort the transaction. This should be just
2383  * noncritical resource releasing.
2384  *
2385  * The ordering of operations is not entirely random. The idea is:
2386  * release resources visible to other backends (eg, files, buffer pins);
2387  * then release locks; then release backend-local resources. We want to
2388  * release locks at the point where any backend waiting for us will see
2389  * our transaction as being fully cleaned up.
2390  *
2391  * Resources that can be associated with individual queries are handled by
2392  * the ResourceOwner mechanism. The other calls here are for backend-wide
2393  * state.
2394  */
2395 
2396  CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2397  : XACT_EVENT_COMMIT);
2398 
2399  CurrentResourceOwner = NULL;
2402  true, true);
2403 
2404  /* Check we've released all buffer pins */
2405  AtEOXact_Buffers(true);
2406 
2407  /* Clean up the relation cache */
2408  AtEOXact_RelationCache(true);
2409 
2410  /*
2411  * Make catalog changes visible to all backends. This has to happen after
2412  * relcache references are dropped (see comments for
2413  * AtEOXact_RelationCache), but before locks are released (if anyone is
2414  * waiting for lock on a relation we've modified, we want them to know
2415  * about the catalog change before they start using the relation).
2416  */
2417  AtEOXact_Inval(true);
2418 
2420 
2423  true, true);
2426  true, true);
2427 
2428  /*
2429  * Likewise, dropping of files deleted during the transaction is best done
2430  * after releasing relcache and buffer pins. (This is not strictly
2431  * necessary during commit, since such pins should have been released
2432  * already, but this ordering is definitely critical during abort.) Since
2433  * this may take many seconds, also delay until after releasing locks.
2434  * Other backends will observe the attendant catalog changes and not
2435  * attempt to access affected files.
2436  */
2437  smgrDoPendingDeletes(true);
2438 
2439  /*
2440  * Send out notification signals to other backends (and do other
2441  * post-commit NOTIFY cleanup). This must not happen until after our
2442  * transaction is fully done from the viewpoint of other backends.
2443  */
2444  AtCommit_Notify();
2445 
2446  /*
2447  * Everything after this should be purely internal-to-this-backend
2448  * cleanup.
2449  */
2450  AtEOXact_GUC(true, 1);
2451  AtEOXact_SPI(true);
2452  AtEOXact_Enum();
2454  AtEOXact_Namespace(true, is_parallel_worker);
2455  AtEOXact_SMgr();
2456  AtEOXact_Files(true);
2458  AtEOXact_HashTables(true);
2459  AtEOXact_PgStat(true, is_parallel_worker);
2460  AtEOXact_Snapshot(true, false);
2461  AtEOXact_ApplyLauncher(true);
2464 
2466  s->curTransactionOwner = NULL;
2469 
2470  AtCommit_Memory();
2471 
2474  s->nestingLevel = 0;
2475  s->gucNestLevel = 0;
2476  s->childXids = NULL;
2477  s->nChildXids = 0;
2478  s->maxChildXids = 0;
2479 
2482 
2483  /*
2484  * done with commit processing, set current transaction state back to
2485  * default
2486  */
2487  s->state = TRANS_DEFAULT;
2488 
2490 }
2491 
2492 
2493 /*
2494  * PrepareTransaction
2495  *
2496  * NB: if you change this routine, better look at CommitTransaction too!
2497  */
2498 static void
2500 {
2503  GlobalTransaction gxact;
2504  TimestampTz prepared_at;
2505 
2507 
2508  ShowTransactionState("PrepareTransaction");
2509 
2510  /*
2511  * check the current transaction state
2512  */
2513  if (s->state != TRANS_INPROGRESS)
2514  elog(WARNING, "PrepareTransaction while in %s state",
2516  Assert(s->parent == NULL);
2517 
2518  /*
2519  * Do pre-commit processing that involves calling user-defined code, such
2520  * as triggers. Since closing cursors could queue trigger actions,
2521  * triggers could open cursors, etc, we have to keep looping until there's
2522  * nothing left to do.
2523  */
2524  for (;;)
2525  {
2526  /*
2527  * Fire all currently pending deferred triggers.
2528  */
2530 
2531  /*
2532  * Close open portals (converting holdable ones into static portals).
2533  * If there weren't any, we are done ... otherwise loop back to check
2534  * if they queued deferred triggers. Lather, rinse, repeat.
2535  */
2536  if (!PreCommit_Portals(true))
2537  break;
2538  }
2539 
2541 
2542  /*
2543  * The remaining actions cannot call any user-defined code, so it's safe
2544  * to start shutting down within-transaction services. But note that most
2545  * of this stuff could still throw an error, which would switch us into
2546  * the transaction-abort path.
2547  */
2548 
2549  /* Shut down the deferred-trigger manager */
2550  AfterTriggerEndXact(true);
2551 
2552  /*
2553  * Let ON COMMIT management do its thing (must happen after closing
2554  * cursors, to avoid dangling-reference problems)
2555  */
2557 
2558  /*
2559  * Synchronize files that are created and not WAL-logged during this
2560  * transaction. This must happen before EndPrepare(), so that we don't see
2561  * committed-but-broken files after a crash and COMMIT PREPARED.
2562  */
2563  smgrDoPendingSyncs(true, false);
2564 
2565  /* close large objects before lower-level cleanup */
2566  AtEOXact_LargeObject(true);
2567 
2568  /* NOTIFY requires no work at this point */
2569 
2570  /*
2571  * Mark serializable transaction as complete for predicate locking
2572  * purposes. This should be done as late as we can put it and still allow
2573  * errors to be raised for failure patterns found at commit.
2574  */
2576 
2577  /*
2578  * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2579  * this transaction. Having the prepared xact hold locks on another
2580  * backend's temp table seems a bad idea --- for instance it would prevent
2581  * the backend from exiting. There are other problems too, such as how to
2582  * clean up the source backend's local buffers and ON COMMIT state if the
2583  * prepared xact includes a DROP of a temp table.
2584  *
2585  * Other objects types, like functions, operators or extensions, share the
2586  * same restriction as they should not be created, locked or dropped as
2587  * this can mess up with this session or even a follow-up session trying
2588  * to use the same temporary namespace.
2589  *
2590  * We must check this after executing any ON COMMIT actions, because they
2591  * might still access a temp relation.
2592  *
2593  * XXX In principle this could be relaxed to allow some useful special
2594  * cases, such as a temp table created and dropped all within the
2595  * transaction. That seems to require much more bookkeeping though.
2596  */
2598  ereport(ERROR,
2599  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2600  errmsg("cannot PREPARE a transaction that has operated on temporary objects")));
2601 
2602  /*
2603  * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2604  * supported if we added cleanup logic to twophase.c, but for now it
2605  * doesn't seem worth the trouble.
2606  */
2608  ereport(ERROR,
2609  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2610  errmsg("cannot PREPARE a transaction that has exported snapshots")));
2611 
2612  /* Prevent cancel/die interrupt while cleaning up */
2613  HOLD_INTERRUPTS();
2614 
2615  /*
2616  * set the current transaction state information appropriately during
2617  * prepare processing
2618  */
2619  s->state = TRANS_PREPARE;
2620 
2621  /* Disable transaction timeout */
2622  if (TransactionTimeout > 0)
2624 
2625  prepared_at = GetCurrentTimestamp();
2626 
2627  /*
2628  * Reserve the GID for this transaction. This could fail if the requested
2629  * GID is invalid or already in use.
2630  */
2631  gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2632  GetUserId(), MyDatabaseId);
2633  prepareGID = NULL;
2634 
2635  /*
2636  * Collect data for the 2PC state file. Note that in general, no actual
2637  * state change should happen in the called modules during this step,
2638  * since it's still possible to fail before commit, and in that case we
2639  * want transaction abort to be able to clean up. (In particular, the
2640  * AtPrepare routines may error out if they find cases they cannot
2641  * handle.) State cleanup should happen in the PostPrepare routines
2642  * below. However, some modules can go ahead and clear state here because
2643  * they wouldn't do anything with it during abort anyway.
2644  *
2645  * Note: because the 2PC state file records will be replayed in the same
2646  * order they are made, the order of these calls has to match the order in
2647  * which we want things to happen during COMMIT PREPARED or ROLLBACK
2648  * PREPARED; in particular, pay attention to whether things should happen
2649  * before or after releasing the transaction's locks.
2650  */
2651  StartPrepare(gxact);
2652 
2653  AtPrepare_Notify();
2654  AtPrepare_Locks();
2656  AtPrepare_PgStat();
2659 
2660  /*
2661  * Here is where we really truly prepare.
2662  *
2663  * We have to record transaction prepares even if we didn't make any
2664  * updates, because the transaction manager might get confused if we lose
2665  * a global transaction.
2666  */
2667  EndPrepare(gxact);
2668 
2669  /*
2670  * Now we clean up backend-internal state and release internal resources.
2671  */
2672 
2673  /* Reset XactLastRecEnd until the next transaction writes something */
2674  XactLastRecEnd = 0;
2675 
2676  /*
2677  * Transfer our locks to a dummy PGPROC. This has to be done before
2678  * ProcArrayClearTransaction(). Otherwise, a GetLockConflicts() would
2679  * conclude "xact already committed or aborted" for our locks.
2680  */
2681  PostPrepare_Locks(xid);
2682 
2683  /*
2684  * Let others know about no transaction in progress by me. This has to be
2685  * done *after* the prepared transaction has been marked valid, else
2686  * someone may think it is unlocked and recyclable.
2687  */
2689 
2690  /*
2691  * In normal commit-processing, this is all non-critical post-transaction
2692  * cleanup. When the transaction is prepared, however, it's important
2693  * that the locks and other per-backend resources are transferred to the
2694  * prepared transaction's PGPROC entry. Note that if an error is raised
2695  * here, it's too late to abort the transaction. XXX: This probably should
2696  * be in a critical section, to force a PANIC if any of this fails, but
2697  * that cure could be worse than the disease.
2698  */
2699 
2701 
2704  true, true);
2705 
2706  /* Check we've released all buffer pins */
2707  AtEOXact_Buffers(true);
2708 
2709  /* Clean up the relation cache */
2710  AtEOXact_RelationCache(true);
2711 
2712  /* notify doesn't need a postprepare call */
2713 
2715 
2717 
2718  PostPrepare_smgr();
2719 
2720  PostPrepare_MultiXact(xid);
2721 
2723 
2726  true, true);
2729  true, true);
2730 
2731  /*
2732  * Allow another backend to finish the transaction. After
2733  * PostPrepare_Twophase(), the transaction is completely detached from our
2734  * backend. The rest is just non-critical cleanup of backend-local state.
2735  */
2737 
2738  /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2739  AtEOXact_GUC(true, 1);
2740  AtEOXact_SPI(true);
2741  AtEOXact_Enum();
2743  AtEOXact_Namespace(true, false);
2744  AtEOXact_SMgr();
2745  AtEOXact_Files(true);
2747  AtEOXact_HashTables(true);
2748  /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2749  AtEOXact_Snapshot(true, true);
2750  /* we treat PREPARE as ROLLBACK so far as waking workers goes */
2751  AtEOXact_ApplyLauncher(false);
2754 
2755  CurrentResourceOwner = NULL;
2757  s->curTransactionOwner = NULL;
2760 
2761  AtCommit_Memory();
2762 
2765  s->nestingLevel = 0;
2766  s->gucNestLevel = 0;
2767  s->childXids = NULL;
2768  s->nChildXids = 0;
2769  s->maxChildXids = 0;
2770 
2773 
2774  /*
2775  * done with 1st phase commit processing, set current transaction state
2776  * back to default
2777  */
2778  s->state = TRANS_DEFAULT;
2779 
2781 }
2782 
2783 
2784 /*
2785  * AbortTransaction
2786  */
2787 static void
2789 {
2791  TransactionId latestXid;
2792  bool is_parallel_worker;
2793 
2794  /* Prevent cancel/die interrupt while cleaning up */
2795  HOLD_INTERRUPTS();
2796 
2797  /* Disable transaction timeout */
2798  if (TransactionTimeout > 0)
2800 
2801  /* Make sure we have a valid memory context and resource owner */
2802  AtAbort_Memory();
2804 
2805  /*
2806  * Release any LW locks we might be holding as quickly as possible.
2807  * (Regular locks, however, must be held till we finish aborting.)
2808  * Releasing LW locks is critical since we might try to grab them again
2809  * while cleaning up!
2810  */
2811  LWLockReleaseAll();
2812 
2813  /*
2814  * Cleanup waiting for LSN if any.
2815  */
2816  WaitLSNCleanup();
2817 
2818  /* Clear wait information and command progress indicator */
2821 
2822  /* Clean up buffer context locks, too */
2823  UnlockBuffers();
2824 
2825  /* Reset WAL record construction state */
2827 
2828  /* Cancel condition variable sleep */
2830 
2831  /*
2832  * Also clean up any open wait for lock, since the lock manager will choke
2833  * if we try to wait for another lock before doing this.
2834  */
2835  LockErrorCleanup();
2836 
2837  /*
2838  * If any timeout events are still active, make sure the timeout interrupt
2839  * is scheduled. This covers possible loss of a timeout interrupt due to
2840  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2841  * We delay this till after LockErrorCleanup so that we don't uselessly
2842  * reschedule lock or deadlock check timeouts.
2843  */
2845 
2846  /*
2847  * Re-enable signals, in case we got here by longjmp'ing out of a signal
2848  * handler. We do this fairly early in the sequence so that the timeout
2849  * infrastructure will be functional if needed while aborting.
2850  */
2851  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
2852 
2853  /*
2854  * check the current transaction state
2855  */
2856  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2857  if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2858  elog(WARNING, "AbortTransaction while in %s state",
2860  Assert(s->parent == NULL);
2861 
2862  /*
2863  * set the current transaction state information appropriately during the
2864  * abort processing
2865  */
2866  s->state = TRANS_ABORT;
2867 
2868  /*
2869  * Reset user ID which might have been changed transiently. We need this
2870  * to clean up in case control escaped out of a SECURITY DEFINER function
2871  * or other local change of CurrentUserId; therefore, the prior value of
2872  * SecurityRestrictionContext also needs to be restored.
2873  *
2874  * (Note: it is not necessary to restore session authorization or role
2875  * settings here because those can only be changed via GUC, and GUC will
2876  * take care of rolling them back if need be.)
2877  */
2879 
2880  /* Forget about any active REINDEX. */
2882 
2883  /* Reset logical streaming state. */
2885 
2886  /* Reset snapshot export state. */
2888 
2889  /*
2890  * If this xact has started any unfinished parallel operation, clean up
2891  * its workers and exit parallel mode. Don't warn about leaked resources.
2892  */
2893  AtEOXact_Parallel(false);
2894  s->parallelModeLevel = 0;
2895  s->parallelChildXact = false; /* should be false already */
2896 
2897  /*
2898  * do abort processing
2899  */
2900  AfterTriggerEndXact(false); /* 'false' means it's abort */
2901  AtAbort_Portals();
2902  smgrDoPendingSyncs(false, is_parallel_worker);
2903  AtEOXact_LargeObject(false);
2904  AtAbort_Notify();
2905  AtEOXact_RelationMap(false, is_parallel_worker);
2906  AtAbort_Twophase();
2907 
2908  /*
2909  * Advertise the fact that we aborted in pg_xact (assuming that we got as
2910  * far as assigning an XID to advertise). But if we're inside a parallel
2911  * worker, skip this; the user backend must be the one to write the abort
2912  * record.
2913  */
2914  if (!is_parallel_worker)
2915  latestXid = RecordTransactionAbort(false);
2916  else
2917  {
2918  latestXid = InvalidTransactionId;
2919 
2920  /*
2921  * Since the parallel leader won't get our value of XactLastRecEnd in
2922  * this case, we nudge WAL-writer ourselves in this case. See related
2923  * comments in RecordTransactionAbort for why this matters.
2924  */
2926  }
2927 
2928  TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->vxid.lxid);
2929 
2930  /*
2931  * Let others know about no transaction in progress by me. Note that this
2932  * must be done _before_ releasing locks we hold and _after_
2933  * RecordTransactionAbort.
2934  */
2935  ProcArrayEndTransaction(MyProc, latestXid);
2936 
2937  /*
2938  * Post-abort cleanup. See notes in CommitTransaction() concerning
2939  * ordering. We can skip all of it if the transaction failed before
2940  * creating a resource owner.
2941  */
2942  if (TopTransactionResourceOwner != NULL)
2943  {
2944  if (is_parallel_worker)
2946  else
2948 
2951  false, true);
2952  AtEOXact_Buffers(false);
2953  AtEOXact_RelationCache(false);
2954  AtEOXact_Inval(false);
2958  false, true);
2961  false, true);
2962  smgrDoPendingDeletes(false);
2963 
2964  AtEOXact_GUC(false, 1);
2965  AtEOXact_SPI(false);
2966  AtEOXact_Enum();
2968  AtEOXact_Namespace(false, is_parallel_worker);
2969  AtEOXact_SMgr();
2970  AtEOXact_Files(false);
2972  AtEOXact_HashTables(false);
2973  AtEOXact_PgStat(false, is_parallel_worker);
2974  AtEOXact_ApplyLauncher(false);
2977  }
2978 
2979  /*
2980  * State remains TRANS_ABORT until CleanupTransaction().
2981  */
2983 }
2984 
2985 /*
2986  * CleanupTransaction
2987  */
2988 static void
2990 {
2992 
2993  /*
2994  * State should still be TRANS_ABORT from AbortTransaction().
2995  */
2996  if (s->state != TRANS_ABORT)
2997  elog(FATAL, "CleanupTransaction: unexpected state %s",
2999 
3000  /*
3001  * do abort cleanup processing
3002  */
3003  AtCleanup_Portals(); /* now safe to release portal memory */
3004  AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
3005 
3006  CurrentResourceOwner = NULL; /* and resource owner */
3009  s->curTransactionOwner = NULL;
3012 
3013  AtCleanup_Memory(); /* and transaction memory */
3014 
3017  s->nestingLevel = 0;
3018  s->gucNestLevel = 0;
3019  s->childXids = NULL;
3020  s->nChildXids = 0;
3021  s->maxChildXids = 0;
3022  s->parallelModeLevel = 0;
3023  s->parallelChildXact = false;
3024 
3027 
3028  /*
3029  * done with abort processing, set current transaction state back to
3030  * default
3031  */
3032  s->state = TRANS_DEFAULT;
3033 }
3034 
3035 /*
3036  * StartTransactionCommand
3037  */
3038 void
3040 {
3042 
3043  switch (s->blockState)
3044  {
3045  /*
3046  * if we aren't in a transaction block, we just do our usual start
3047  * transaction.
3048  */
3049  case TBLOCK_DEFAULT:
3050  StartTransaction();
3052  break;
3053 
3054  /*
3055  * We are somewhere in a transaction block or subtransaction and
3056  * about to start a new command. For now we do nothing, but
3057  * someday we may do command-local resource initialization. (Note
3058  * that any needed CommandCounterIncrement was done by the
3059  * previous CommitTransactionCommand.)
3060  */
3061  case TBLOCK_INPROGRESS:
3063  case TBLOCK_SUBINPROGRESS:
3064  break;
3065 
3066  /*
3067  * Here we are in a failed transaction block (one of the commands
3068  * caused an abort) so we do nothing but remain in the abort
3069  * state. Eventually we will get a ROLLBACK command which will
3070  * get us out of this state. (It is up to other code to ensure
3071  * that no commands other than ROLLBACK will be processed in these
3072  * states.)
3073  */
3074  case TBLOCK_ABORT:
3075  case TBLOCK_SUBABORT:
3076  break;
3077 
3078  /* These cases are invalid. */
3079  case TBLOCK_STARTED:
3080  case TBLOCK_BEGIN:
3082  case TBLOCK_SUBBEGIN:
3083  case TBLOCK_END:
3084  case TBLOCK_SUBRELEASE:
3085  case TBLOCK_SUBCOMMIT:
3086  case TBLOCK_ABORT_END:
3087  case TBLOCK_SUBABORT_END:
3088  case TBLOCK_ABORT_PENDING:
3090  case TBLOCK_SUBRESTART:
3092  case TBLOCK_PREPARE:
3093  elog(ERROR, "StartTransactionCommand: unexpected state %s",
3095  break;
3096  }
3097 
3098  /*
3099  * We must switch to CurTransactionContext before returning. This is
3100  * already done if we called StartTransaction, otherwise not.
3101  */
3102  Assert(CurTransactionContext != NULL);
3104 }
3105 
3106 
3107 /*
3108  * Simple system for saving and restoring transaction characteristics
3109  * (isolation level, read only, deferrable). We need this for transaction
3110  * chaining, so that we can set the characteristics of the new transaction to
3111  * be the same as the previous one. (We need something like this because the
3112  * GUC system resets the characteristics at transaction end, so for example
3113  * just skipping the reset in StartTransaction() won't work.)
3114  */
3115 void
3117 {
3121 }
3122 
3123 void
3125 {
3129 }
3130 
3131 /*
3132  * CommitTransactionCommand -- a wrapper function handling the
3133  * loop over subtransactions to avoid a potentially dangerous recursion
3134  * in CommitTransactionCommandInternal().
3135  */
3136 void
3138 {
3139  /*
3140  * Repeatedly call CommitTransactionCommandInternal() until all the work
3141  * is done.
3142  */
3144  {
3145  }
3146 }
3147 
3148 /*
3149  * CommitTransactionCommandInternal - a function doing an iteration of work
3150  * regarding handling the commit transaction command. In the case of
3151  * subtransactions more than one iterations could be required. Returns
3152  * true when no more iterations required, false otherwise.
3153  */
3154 static bool
3156 {
3159 
3160  /* Must save in case we need to restore below */
3162 
3163  switch (s->blockState)
3164  {
3165  /*
3166  * These shouldn't happen. TBLOCK_DEFAULT means the previous
3167  * StartTransactionCommand didn't set the STARTED state
3168  * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
3169  * by EndParallelWorkerTransaction(), not this function.
3170  */
3171  case TBLOCK_DEFAULT:
3173  elog(FATAL, "CommitTransactionCommand: unexpected state %s",
3175  break;
3176 
3177  /*
3178  * If we aren't in a transaction block, just do our usual
3179  * transaction commit, and return to the idle state.
3180  */
3181  case TBLOCK_STARTED:
3184  break;
3185 
3186  /*
3187  * We are completing a "BEGIN TRANSACTION" command, so we change
3188  * to the "transaction block in progress" state and return. (We
3189  * assume the BEGIN did nothing to the database, so we need no
3190  * CommandCounterIncrement.)
3191  */
3192  case TBLOCK_BEGIN:
3194  break;
3195 
3196  /*
3197  * This is the case when we have finished executing a command
3198  * someplace within a transaction block. We increment the command
3199  * counter and return.
3200  */
3201  case TBLOCK_INPROGRESS:
3203  case TBLOCK_SUBINPROGRESS:
3205  break;
3206 
3207  /*
3208  * We are completing a "COMMIT" command. Do it and return to the
3209  * idle state.
3210  */
3211  case TBLOCK_END:
3214  if (s->chain)
3215  {
3216  StartTransaction();
3218  s->chain = false;
3220  }
3221  break;
3222 
3223  /*
3224  * Here we are in the middle of a transaction block but one of the
3225  * commands caused an abort so we do nothing but remain in the
3226  * abort state. Eventually we will get a ROLLBACK command.
3227  */
3228  case TBLOCK_ABORT:
3229  case TBLOCK_SUBABORT:
3230  break;
3231 
3232  /*
3233  * Here we were in an aborted transaction block and we just got
3234  * the ROLLBACK command from the user, so clean up the
3235  * already-aborted transaction and return to the idle state.
3236  */
3237  case TBLOCK_ABORT_END:
3240  if (s->chain)
3241  {
3242  StartTransaction();
3244  s->chain = false;
3246  }
3247  break;
3248 
3249  /*
3250  * Here we were in a perfectly good transaction block but the user
3251  * told us to ROLLBACK anyway. We have to abort the transaction
3252  * and then clean up.
3253  */
3254  case TBLOCK_ABORT_PENDING:
3255  AbortTransaction();
3258  if (s->chain)
3259  {
3260  StartTransaction();
3262  s->chain = false;
3264  }
3265  break;
3266 
3267  /*
3268  * We are completing a "PREPARE TRANSACTION" command. Do it and
3269  * return to the idle state.
3270  */
3271  case TBLOCK_PREPARE:
3274  break;
3275 
3276  /*
3277  * The user issued a SAVEPOINT inside a transaction block. Start a
3278  * subtransaction. (DefineSavepoint already did PushTransaction,
3279  * so as to have someplace to put the SUBBEGIN state.)
3280  */
3281  case TBLOCK_SUBBEGIN:
3284  break;
3285 
3286  /*
3287  * The user issued a RELEASE command, so we end the current
3288  * subtransaction and return to the parent transaction. The parent
3289  * might be ended too, so repeat till we find an INPROGRESS
3290  * transaction or subtransaction.
3291  */
3292  case TBLOCK_SUBRELEASE:
3293  do
3294  {
3296  s = CurrentTransactionState; /* changed by pop */
3297  } while (s->blockState == TBLOCK_SUBRELEASE);
3298 
3301  break;
3302 
3303  /*
3304  * The user issued a COMMIT, so we end the current subtransaction
3305  * hierarchy and perform final commit. We do this by rolling up
3306  * any subtransactions into their parent, which leads to O(N^2)
3307  * operations with respect to resource owners - this isn't that
3308  * bad until we approach a thousands of savepoints but is
3309  * necessary for correctness should after triggers create new
3310  * resource owners.
3311  */
3312  case TBLOCK_SUBCOMMIT:
3313  do
3314  {
3316  s = CurrentTransactionState; /* changed by pop */
3317  } while (s->blockState == TBLOCK_SUBCOMMIT);
3318  /* If we had a COMMIT command, finish off the main xact too */
3319  if (s->blockState == TBLOCK_END)
3320  {
3321  Assert(s->parent == NULL);
3324  if (s->chain)
3325  {
3326  StartTransaction();
3328  s->chain = false;
3330  }
3331  }
3332  else if (s->blockState == TBLOCK_PREPARE)
3333  {
3334  Assert(s->parent == NULL);
3337  }
3338  else
3339  elog(ERROR, "CommitTransactionCommand: unexpected state %s",
3341  break;
3342 
3343  /*
3344  * The current already-failed subtransaction is ending due to a
3345  * ROLLBACK or ROLLBACK TO command, so pop it and recursively
3346  * examine the parent (which could be in any of several states).
3347  * As we need to examine the parent, return false to request the
3348  * caller to do the next iteration.
3349  */
3350  case TBLOCK_SUBABORT_END:
3352  return false;
3353 
3354  /*
3355  * As above, but it's not dead yet, so abort first.
3356  */
3360  return false;
3361 
3362  /*
3363  * The current subtransaction is the target of a ROLLBACK TO
3364  * command. Abort and pop it, then start a new subtransaction
3365  * with the same name.
3366  */
3367  case TBLOCK_SUBRESTART:
3368  {
3369  char *name;
3370  int savepointLevel;
3371 
3372  /* save name and keep Cleanup from freeing it */
3373  name = s->name;
3374  s->name = NULL;
3375  savepointLevel = s->savepointLevel;
3376 
3379 
3380  DefineSavepoint(NULL);
3381  s = CurrentTransactionState; /* changed by push */
3382  s->name = name;
3383  s->savepointLevel = savepointLevel;
3384 
3385  /* This is the same as TBLOCK_SUBBEGIN case */
3389  }
3390  break;
3391 
3392  /*
3393  * Same as above, but the subtransaction had already failed, so we
3394  * don't need AbortSubTransaction.
3395  */
3397  {
3398  char *name;
3399  int savepointLevel;
3400 
3401  /* save name and keep Cleanup from freeing it */
3402  name = s->name;
3403  s->name = NULL;
3404  savepointLevel = s->savepointLevel;
3405 
3407 
3408  DefineSavepoint(NULL);
3409  s = CurrentTransactionState; /* changed by push */
3410  s->name = name;
3411  s->savepointLevel = savepointLevel;
3412 
3413  /* This is the same as TBLOCK_SUBBEGIN case */
3417  }
3418  break;
3419  }
3420 
3421  /* Done, no more iterations required */
3422  return true;
3423 }
3424 
3425 /*
3426  * AbortCurrentTransaction -- a wrapper function handling the
3427  * loop over subtransactions to avoid potentially dangerous recursion in
3428  * AbortCurrentTransactionInternal().
3429  */
3430 void
3432 {
3433  /*
3434  * Repeatedly call AbortCurrentTransactionInternal() until all the work is
3435  * done.
3436  */
3438  {
3439  }
3440 }
3441 
3442 /*
3443  * AbortCurrentTransactionInternal - a function doing an iteration of work
3444  * regarding handling the current transaction abort. In the case of
3445  * subtransactions more than one iterations could be required. Returns
3446  * true when no more iterations required, false otherwise.
3447  */
3448 static bool
3450 {
3452 
3453  switch (s->blockState)
3454  {
3455  case TBLOCK_DEFAULT:
3456  if (s->state == TRANS_DEFAULT)
3457  {
3458  /* we are idle, so nothing to do */
3459  }
3460  else
3461  {
3462  /*
3463  * We can get here after an error during transaction start
3464  * (state will be TRANS_START). Need to clean up the
3465  * incompletely started transaction. First, adjust the
3466  * low-level state to suppress warning message from
3467  * AbortTransaction.
3468  */
3469  if (s->state == TRANS_START)
3470  s->state = TRANS_INPROGRESS;
3471  AbortTransaction();
3473  }
3474  break;
3475 
3476  /*
3477  * If we aren't in a transaction block, we just do the basic abort
3478  * & cleanup transaction. For this purpose, we treat an implicit
3479  * transaction block as if it were a simple statement.
3480  */
3481  case TBLOCK_STARTED:
3483  AbortTransaction();
3486  break;
3487 
3488  /*
3489  * If we are in TBLOCK_BEGIN it means something screwed up right
3490  * after reading "BEGIN TRANSACTION". We assume that the user
3491  * will interpret the error as meaning the BEGIN failed to get him
3492  * into a transaction block, so we should abort and return to idle
3493  * state.
3494  */
3495  case TBLOCK_BEGIN:
3496  AbortTransaction();
3499  break;
3500 
3501  /*
3502  * We are somewhere in a transaction block and we've gotten a
3503  * failure, so we abort the transaction and set up the persistent
3504  * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3505  */
3506  case TBLOCK_INPROGRESS:
3508  AbortTransaction();
3509  s->blockState = TBLOCK_ABORT;
3510  /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
3511  break;
3512 
3513  /*
3514  * Here, we failed while trying to COMMIT. Clean up the
3515  * transaction and return to idle state (we do not want to stay in
3516  * the transaction).
3517  */
3518  case TBLOCK_END:
3519  AbortTransaction();
3522  break;
3523 
3524  /*
3525  * Here, we are already in an aborted transaction state and are
3526  * waiting for a ROLLBACK, but for some reason we failed again! So
3527  * we just remain in the abort state.
3528  */
3529  case TBLOCK_ABORT:
3530  case TBLOCK_SUBABORT:
3531  break;
3532 
3533  /*
3534  * We are in a failed transaction and we got the ROLLBACK command.
3535  * We have already aborted, we just need to cleanup and go to idle
3536  * state.
3537  */
3538  case TBLOCK_ABORT_END:
3541  break;
3542 
3543  /*
3544  * We are in a live transaction and we got a ROLLBACK command.
3545  * Abort, cleanup, go to idle state.
3546  */
3547  case TBLOCK_ABORT_PENDING:
3548  AbortTransaction();
3551  break;
3552 
3553  /*
3554  * Here, we failed while trying to PREPARE. Clean up the
3555  * transaction and return to idle state (we do not want to stay in
3556  * the transaction).
3557  */
3558  case TBLOCK_PREPARE:
3559  AbortTransaction();
3562  break;
3563 
3564  /*
3565  * We got an error inside a subtransaction. Abort just the
3566  * subtransaction, and go to the persistent SUBABORT state until
3567  * we get ROLLBACK.
3568  */
3569  case TBLOCK_SUBINPROGRESS:
3572  break;
3573 
3574  /*
3575  * If we failed while trying to create a subtransaction, clean up
3576  * the broken subtransaction and abort the parent. The same
3577  * applies if we get a failure while ending a subtransaction. As
3578  * we need to abort the parent, return false to request the caller
3579  * to do the next iteration.
3580  */
3581  case TBLOCK_SUBBEGIN:
3582  case TBLOCK_SUBRELEASE:
3583  case TBLOCK_SUBCOMMIT:
3585  case TBLOCK_SUBRESTART:
3588  return false;
3589 
3590  /*
3591  * Same as above, except the Abort() was already done.
3592  */
3593  case TBLOCK_SUBABORT_END:
3596  return false;
3597  }
3598 
3599  /* Done, no more iterations required */
3600  return true;
3601 }
3602 
3603 /*
3604  * PreventInTransactionBlock
3605  *
3606  * This routine is to be called by statements that must not run inside
3607  * a transaction block, typically because they have non-rollback-able
3608  * side effects or do internal commits.
3609  *
3610  * If this routine completes successfully, then the calling statement is
3611  * guaranteed that if it completes without error, its results will be
3612  * committed immediately.
3613  *
3614  * If we have already started a transaction block, issue an error; also issue
3615  * an error if we appear to be running inside a user-defined function (which
3616  * could issue more commands and possibly cause a failure after the statement
3617  * completes). Subtransactions are verboten too.
3618  *
3619  * We must also set XACT_FLAGS_NEEDIMMEDIATECOMMIT in MyXactFlags, to ensure
3620  * that postgres.c follows through by committing after the statement is done.
3621  *
3622  * isTopLevel: passed down from ProcessUtility to determine whether we are
3623  * inside a function. (We will always fail if this is false, but it's
3624  * convenient to centralize the check here instead of making callers do it.)
3625  * stmtType: statement type name, for error messages.
3626  */
3627 void
3628 PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
3629 {
3630  /*
3631  * xact block already started?
3632  */
3633  if (IsTransactionBlock())
3634  ereport(ERROR,
3635  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3636  /* translator: %s represents an SQL statement name */
3637  errmsg("%s cannot run inside a transaction block",
3638  stmtType)));
3639 
3640  /*
3641  * subtransaction?
3642  */
3643  if (IsSubTransaction())
3644  ereport(ERROR,
3645  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3646  /* translator: %s represents an SQL statement name */
3647  errmsg("%s cannot run inside a subtransaction",
3648  stmtType)));
3649 
3650  /*
3651  * inside a pipeline that has started an implicit transaction?
3652  */
3654  ereport(ERROR,
3655  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3656  /* translator: %s represents an SQL statement name */
3657  errmsg("%s cannot be executed within a pipeline",
3658  stmtType)));
3659 
3660  /*
3661  * inside a function call?
3662  */
3663  if (!isTopLevel)
3664  ereport(ERROR,
3665  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3666  /* translator: %s represents an SQL statement name */
3667  errmsg("%s cannot be executed from a function", stmtType)));
3668 
3669  /* If we got past IsTransactionBlock test, should be in default state */
3672  elog(FATAL, "cannot prevent transaction chain");
3673 
3674  /* All okay. Set the flag to make sure the right thing happens later. */
3676 }
3677 
3678 /*
3679  * WarnNoTransactionBlock
3680  * RequireTransactionBlock
3681  *
3682  * These two functions allow for warnings or errors if a command is executed
3683  * outside of a transaction block. This is useful for commands that have no
3684  * effects that persist past transaction end (and so calling them outside a
3685  * transaction block is presumably an error). DECLARE CURSOR is an example.
3686  * While top-level transaction control commands (BEGIN/COMMIT/ABORT) and SET
3687  * that have no effect issue warnings, all other no-effect commands generate
3688  * errors.
3689  *
3690  * If we appear to be running inside a user-defined function, we do not
3691  * issue anything, since the function could issue more commands that make
3692  * use of the current statement's results. Likewise subtransactions.
3693  * Thus these are inverses for PreventInTransactionBlock.
3694  *
3695  * isTopLevel: passed down from ProcessUtility to determine whether we are
3696  * inside a function.
3697  * stmtType: statement type name, for warning or error messages.
3698  */
3699 void
3700 WarnNoTransactionBlock(bool isTopLevel, const char *stmtType)
3701 {
3702  CheckTransactionBlock(isTopLevel, false, stmtType);
3703 }
3704 
3705 void
3706 RequireTransactionBlock(bool isTopLevel, const char *stmtType)
3707 {
3708  CheckTransactionBlock(isTopLevel, true, stmtType);
3709 }
3710 
3711 /*
3712  * This is the implementation of the above two.
3713  */
3714 static void
3715 CheckTransactionBlock(bool isTopLevel, bool throwError, const char *stmtType)
3716 {
3717  /*
3718  * xact block already started?
3719  */
3720  if (IsTransactionBlock())
3721  return;
3722 
3723  /*
3724  * subtransaction?
3725  */
3726  if (IsSubTransaction())
3727  return;
3728 
3729  /*
3730  * inside a function call?
3731  */
3732  if (!isTopLevel)
3733  return;
3734 
3735  ereport(throwError ? ERROR : WARNING,
3736  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3737  /* translator: %s represents an SQL statement name */
3738  errmsg("%s can only be used in transaction blocks",
3739  stmtType)));
3740 }
3741 
3742 /*
3743  * IsInTransactionBlock
3744  *
3745  * This routine is for statements that need to behave differently inside
3746  * a transaction block than when running as single commands. ANALYZE is
3747  * currently the only example.
3748  *
3749  * If this routine returns "false", then the calling statement is allowed
3750  * to perform internal transaction-commit-and-start cycles; there is not a
3751  * risk of messing up any transaction already in progress. (Note that this
3752  * is not the identical guarantee provided by PreventInTransactionBlock,
3753  * since we will not force a post-statement commit.)
3754  *
3755  * isTopLevel: passed down from ProcessUtility to determine whether we are
3756  * inside a function.
3757  */
3758 bool
3759 IsInTransactionBlock(bool isTopLevel)
3760 {
3761  /*
3762  * Return true on same conditions that would make
3763  * PreventInTransactionBlock error out
3764  */
3765  if (IsTransactionBlock())
3766  return true;
3767 
3768  if (IsSubTransaction())
3769  return true;
3770 
3772  return true;
3773 
3774  if (!isTopLevel)
3775  return true;
3776 
3779  return true;
3780 
3781  return false;
3782 }
3783 
3784 
3785 /*
3786  * Register or deregister callback functions for start- and end-of-xact
3787  * operations.
3788  *
3789  * These functions are intended for use by dynamically loaded modules.
3790  * For built-in modules we generally just hardwire the appropriate calls
3791  * (mainly because it's easier to control the order that way, where needed).
3792  *
3793  * At transaction end, the callback occurs post-commit or post-abort, so the
3794  * callback functions can only do noncritical cleanup.
3795  */
3796 void
3798 {
3799  XactCallbackItem *item;
3800 
3801  item = (XactCallbackItem *)
3803  item->callback = callback;
3804  item->arg = arg;
3805  item->next = Xact_callbacks;
3806  Xact_callbacks = item;
3807 }
3808 
3809 void
3811 {
3812  XactCallbackItem *item;
3813  XactCallbackItem *prev;
3814 
3815  prev = NULL;
3816  for (item = Xact_callbacks; item; prev = item, item = item->next)
3817  {
3818  if (item->callback == callback && item->arg == arg)
3819  {
3820  if (prev)
3821  prev->next = item->next;
3822  else
3823  Xact_callbacks = item->next;
3824  pfree(item);
3825  break;
3826  }
3827  }
3828 }
3829 
3830 static void
3832 {
3833  XactCallbackItem *item;
3835 
3836  for (item = Xact_callbacks; item; item = next)
3837  {
3838  /* allow callbacks to unregister themselves when called */
3839  next = item->next;
3840  item->callback(event, item->arg);
3841  }
3842 }
3843 
3844 
3845 /*
3846  * Register or deregister callback functions for start- and end-of-subxact
3847  * operations.
3848  *
3849  * Pretty much same as above, but for subtransaction events.
3850  *
3851  * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3852  * so the callback functions can only do noncritical cleanup. At
3853  * subtransaction start, the callback is called when the subtransaction has
3854  * finished initializing.
3855  */
3856 void
3858 {
3859  SubXactCallbackItem *item;
3860 
3861  item = (SubXactCallbackItem *)
3863  item->callback = callback;
3864  item->arg = arg;
3865  item->next = SubXact_callbacks;
3866  SubXact_callbacks = item;
3867 }
3868 
3869 void
3871 {
3872  SubXactCallbackItem *item;
3873  SubXactCallbackItem *prev;
3874 
3875  prev = NULL;
3876  for (item = SubXact_callbacks; item; prev = item, item = item->next)
3877  {
3878  if (item->callback == callback && item->arg == arg)
3879  {
3880  if (prev)
3881  prev->next = item->next;
3882  else
3883  SubXact_callbacks = item->next;
3884  pfree(item);
3885  break;
3886  }
3887  }
3888 }
3889 
3890 static void
3892  SubTransactionId mySubid,
3893  SubTransactionId parentSubid)
3894 {
3895  SubXactCallbackItem *item;
3897 
3898  for (item = SubXact_callbacks; item; item = next)
3899  {
3900  /* allow callbacks to unregister themselves when called */
3901  next = item->next;
3902  item->callback(event, mySubid, parentSubid, item->arg);
3903  }
3904 }
3905 
3906 
3907 /* ----------------------------------------------------------------
3908  * transaction block support
3909  * ----------------------------------------------------------------
3910  */
3911 
3912 /*
3913  * BeginTransactionBlock
3914  * This executes a BEGIN command.
3915  */
3916 void
3918 {
3920 
3921  switch (s->blockState)
3922  {
3923  /*
3924  * We are not inside a transaction block, so allow one to begin.
3925  */
3926  case TBLOCK_STARTED:
3927  s->blockState = TBLOCK_BEGIN;
3928  break;
3929 
3930  /*
3931  * BEGIN converts an implicit transaction block to a regular one.
3932  * (Note that we allow this even if we've already done some
3933  * commands, which is a bit odd but matches historical practice.)
3934  */
3936  s->blockState = TBLOCK_BEGIN;
3937  break;
3938 
3939  /*
3940  * Already a transaction block in progress.
3941  */
3942  case TBLOCK_INPROGRESS:
3944  case TBLOCK_SUBINPROGRESS:
3945  case TBLOCK_ABORT:
3946  case TBLOCK_SUBABORT:
3947  ereport(WARNING,
3948  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3949  errmsg("there is already a transaction in progress")));
3950  break;
3951 
3952  /* These cases are invalid. */
3953  case TBLOCK_DEFAULT:
3954  case TBLOCK_BEGIN:
3955  case TBLOCK_SUBBEGIN:
3956  case TBLOCK_END:
3957  case TBLOCK_SUBRELEASE:
3958  case TBLOCK_SUBCOMMIT:
3959  case TBLOCK_ABORT_END:
3960  case TBLOCK_SUBABORT_END:
3961  case TBLOCK_ABORT_PENDING:
3963  case TBLOCK_SUBRESTART:
3965  case TBLOCK_PREPARE:
3966  elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3968  break;
3969  }
3970 }
3971 
3972 /*
3973  * PrepareTransactionBlock
3974  * This executes a PREPARE command.
3975  *
3976  * Since PREPARE may actually do a ROLLBACK, the result indicates what
3977  * happened: true for PREPARE, false for ROLLBACK.
3978  *
3979  * Note that we don't actually do anything here except change blockState.
3980  * The real work will be done in the upcoming PrepareTransaction().
3981  * We do it this way because it's not convenient to change memory context,
3982  * resource owner, etc while executing inside a Portal.
3983  */
3984 bool
3985 PrepareTransactionBlock(const char *gid)
3986 {
3987  TransactionState s;
3988  bool result;
3989 
3990  /* Set up to commit the current transaction */
3991  result = EndTransactionBlock(false);
3992 
3993  /* If successful, change outer tblock state to PREPARE */
3994  if (result)
3995  {
3997 
3998  while (s->parent != NULL)
3999  s = s->parent;
4000 
4001  if (s->blockState == TBLOCK_END)
4002  {
4003  /* Save GID where PrepareTransaction can find it again */
4005 
4007  }
4008  else
4009  {
4010  /*
4011  * ignore case where we are not in a transaction;
4012  * EndTransactionBlock already issued a warning.
4013  */
4016  /* Don't send back a PREPARE result tag... */
4017  result = false;
4018  }
4019  }
4020 
4021  return result;
4022 }
4023 
4024 /*
4025  * EndTransactionBlock
4026  * This executes a COMMIT command.
4027  *
4028  * Since COMMIT may actually do a ROLLBACK, the result indicates what
4029  * happened: true for COMMIT, false for ROLLBACK.
4030  *
4031  * Note that we don't actually do anything here except change blockState.
4032  * The real work will be done in the upcoming CommitTransactionCommand().
4033  * We do it this way because it's not convenient to change memory context,
4034  * resource owner, etc while executing inside a Portal.
4035  */
4036 bool
4038 {
4040  bool result = false;
4041 
4042  switch (s->blockState)
4043  {
4044  /*
4045  * We are in a transaction block, so tell CommitTransactionCommand
4046  * to COMMIT.
4047  */
4048  case TBLOCK_INPROGRESS:
4049  s->blockState = TBLOCK_END;
4050  result = true;
4051  break;
4052 
4053  /*
4054  * We are in an implicit transaction block. If AND CHAIN was
4055  * specified, error. Otherwise commit, but issue a warning
4056  * because there was no explicit BEGIN before this.
4057  */
4059  if (chain)
4060  ereport(ERROR,
4061  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4062  /* translator: %s represents an SQL statement name */
4063  errmsg("%s can only be used in transaction blocks",
4064  "COMMIT AND CHAIN")));
4065  else
4066  ereport(WARNING,
4067  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4068  errmsg("there is no transaction in progress")));
4069  s->blockState = TBLOCK_END;
4070  result = true;
4071  break;
4072 
4073  /*
4074  * We are in a failed transaction block. Tell
4075  * CommitTransactionCommand it's time to exit the block.
4076  */
4077  case TBLOCK_ABORT:
4079  break;
4080 
4081  /*
4082  * We are in a live subtransaction block. Set up to subcommit all
4083  * open subtransactions and then commit the main transaction.
4084  */
4085  case TBLOCK_SUBINPROGRESS:
4086  while (s->parent != NULL)
4087  {
4088  if (s->blockState == TBLOCK_SUBINPROGRESS)
4090  else
4091  elog(FATAL, "EndTransactionBlock: unexpected state %s",
4093  s = s->parent;
4094  }
4095  if (s->blockState == TBLOCK_INPROGRESS)
4096  s->blockState = TBLOCK_END;
4097  else
4098  elog(FATAL, "EndTransactionBlock: unexpected state %s",
4100  result = true;
4101  break;
4102 
4103  /*
4104  * Here we are inside an aborted subtransaction. Treat the COMMIT
4105  * as ROLLBACK: set up to abort everything and exit the main
4106  * transaction.
4107  */
4108  case TBLOCK_SUBABORT:
4109  while (s->parent != NULL)
4110  {
4111  if (s->blockState == TBLOCK_SUBINPROGRESS)
4113  else if (s->blockState == TBLOCK_SUBABORT)
4115  else
4116  elog(FATAL, "EndTransactionBlock: unexpected state %s",
4118  s = s->parent;
4119  }
4120  if (s->blockState == TBLOCK_INPROGRESS)
4122  else if (s->blockState == TBLOCK_ABORT)
4124  else
4125  elog(FATAL, "EndTransactionBlock: unexpected state %s",
4127  break;
4128 
4129  /*
4130  * The user issued COMMIT when not inside a transaction. For
4131  * COMMIT without CHAIN, issue a WARNING, staying in
4132  * TBLOCK_STARTED state. The upcoming call to
4133  * CommitTransactionCommand() will then close the transaction and
4134  * put us back into the default state. For COMMIT AND CHAIN,
4135  * error.
4136  */
4137  case TBLOCK_STARTED:
4138  if (chain)
4139  ereport(ERROR,
4140  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4141  /* translator: %s represents an SQL statement name */
4142  errmsg("%s can only be used in transaction blocks",
4143  "COMMIT AND CHAIN")));
4144  else
4145  ereport(WARNING,
4146  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4147  errmsg("there is no transaction in progress")));
4148  result = true;
4149  break;
4150 
4151  /*
4152  * The user issued a COMMIT that somehow ran inside a parallel
4153  * worker. We can't cope with that.
4154  */
4156  ereport(FATAL,
4157  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4158  errmsg("cannot commit during a parallel operation")));
4159  break;
4160 
4161  /* These cases are invalid. */
4162  case TBLOCK_DEFAULT:
4163  case TBLOCK_BEGIN:
4164  case TBLOCK_SUBBEGIN:
4165  case TBLOCK_END:
4166  case TBLOCK_SUBRELEASE:
4167  case TBLOCK_SUBCOMMIT:
4168  case TBLOCK_ABORT_END:
4169  case TBLOCK_SUBABORT_END:
4170  case TBLOCK_ABORT_PENDING:
4172  case TBLOCK_SUBRESTART:
4174  case TBLOCK_PREPARE:
4175  elog(FATAL, "EndTransactionBlock: unexpected state %s",
4177  break;
4178  }
4179 
4181  s->blockState == TBLOCK_END ||
4182  s->blockState == TBLOCK_ABORT_END ||
4184 
4185  s->chain = chain;
4186 
4187  return result;
4188 }
4189 
4190 /*
4191  * UserAbortTransactionBlock
4192  * This executes a ROLLBACK command.
4193  *
4194  * As above, we don't actually do anything here except change blockState.
4195  */
4196 void
4198 {
4200 
4201  switch (s->blockState)
4202  {
4203  /*
4204  * We are inside a transaction block and we got a ROLLBACK command
4205  * from the user, so tell CommitTransactionCommand to abort and
4206  * exit the transaction block.
4207  */
4208  case TBLOCK_INPROGRESS:
4210  break;
4211 
4212  /*
4213  * We are inside a failed transaction block and we got a ROLLBACK
4214  * command from the user. Abort processing is already done, so
4215  * CommitTransactionCommand just has to cleanup and go back to
4216  * idle state.
4217  */
4218  case TBLOCK_ABORT:
4220  break;
4221 
4222  /*
4223  * We are inside a subtransaction. Mark everything up to top
4224  * level as exitable.
4225  */
4226  case TBLOCK_SUBINPROGRESS:
4227  case TBLOCK_SUBABORT:
4228  while (s->parent != NULL)
4229  {
4230  if (s->blockState == TBLOCK_SUBINPROGRESS)
4232  else if (s->blockState == TBLOCK_SUBABORT)
4234  else
4235  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4237  s = s->parent;
4238  }
4239  if (s->blockState == TBLOCK_INPROGRESS)
4241  else if (s->blockState == TBLOCK_ABORT)
4243  else
4244  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4246  break;
4247 
4248  /*
4249  * The user issued ABORT when not inside a transaction. For
4250  * ROLLBACK without CHAIN, issue a WARNING and go to abort state.
4251  * The upcoming call to CommitTransactionCommand() will then put
4252  * us back into the default state. For ROLLBACK AND CHAIN, error.
4253  *
4254  * We do the same thing with ABORT inside an implicit transaction,
4255  * although in this case we might be rolling back actual database
4256  * state changes. (It's debatable whether we should issue a
4257  * WARNING in this case, but we have done so historically.)
4258  */
4259  case TBLOCK_STARTED:
4261  if (chain)
4262  ereport(ERROR,
4263  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4264  /* translator: %s represents an SQL statement name */
4265  errmsg("%s can only be used in transaction blocks",
4266  "ROLLBACK AND CHAIN")));
4267  else
4268  ereport(WARNING,
4269  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4270  errmsg("there is no transaction in progress")));
4272  break;
4273 
4274  /*
4275  * The user issued an ABORT that somehow ran inside a parallel
4276  * worker. We can't cope with that.
4277  */
4279  ereport(FATAL,
4280  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4281  errmsg("cannot abort during a parallel operation")));
4282  break;
4283 
4284  /* These cases are invalid. */
4285  case TBLOCK_DEFAULT:
4286  case TBLOCK_BEGIN:
4287  case TBLOCK_SUBBEGIN:
4288  case TBLOCK_END:
4289  case TBLOCK_SUBRELEASE:
4290  case TBLOCK_SUBCOMMIT:
4291  case TBLOCK_ABORT_END:
4292  case TBLOCK_SUBABORT_END:
4293  case TBLOCK_ABORT_PENDING:
4295  case TBLOCK_SUBRESTART:
4297  case TBLOCK_PREPARE:
4298  elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4300  break;
4301  }
4302 
4305 
4306  s->chain = chain;
4307 }
4308 
4309 /*
4310  * BeginImplicitTransactionBlock
4311  * Start an implicit transaction block if we're not already in one.
4312  *
4313  * Unlike BeginTransactionBlock, this is called directly from the main loop
4314  * in postgres.c, not within a Portal. So we can just change blockState
4315  * without a lot of ceremony. We do not expect caller to do
4316  * CommitTransactionCommand/StartTransactionCommand.
4317  */
4318 void
4320 {
4322 
4323  /*
4324  * If we are in STARTED state (that is, no transaction block is open),
4325  * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
4326  * block.
4327  *
4328  * For caller convenience, we consider all other transaction states as
4329  * legal here; otherwise the caller would need its own state check, which
4330  * seems rather pointless.
4331  */
4332  if (s->blockState == TBLOCK_STARTED)
4334 }
4335 
4336 /*
4337  * EndImplicitTransactionBlock
4338  * End an implicit transaction block, if we're in one.
4339  *
4340  * Like EndTransactionBlock, we just make any needed blockState change here.
4341  * The real work will be done in the upcoming CommitTransactionCommand().
4342  */
4343 void
4345 {
4347 
4348  /*
4349  * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
4350  * allowing CommitTransactionCommand to commit whatever happened during
4351  * the implicit transaction block as though it were a single statement.
4352  *
4353  * For caller convenience, we consider all other transaction states as
4354  * legal here; otherwise the caller would need its own state check, which
4355  * seems rather pointless.
4356  */
4359 }
4360 
4361 /*
4362  * DefineSavepoint
4363  * This executes a SAVEPOINT command.
4364  */
4365 void
4366 DefineSavepoint(const char *name)
4367 {
4369 
4370  /*
4371  * Workers synchronize transaction state at the beginning of each parallel
4372  * operation, so we can't account for new subtransactions after that
4373  * point. (Note that this check will certainly error out if s->blockState
4374  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4375  * below.)
4376  */
4378  ereport(ERROR,
4379  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4380  errmsg("cannot define savepoints during a parallel operation")));
4381 
4382  switch (s->blockState)
4383  {
4384  case TBLOCK_INPROGRESS:
4385  case TBLOCK_SUBINPROGRESS:
4386  /* Normal subtransaction start */
4387  PushTransaction();
4388  s = CurrentTransactionState; /* changed by push */
4389 
4390  /*
4391  * Savepoint names, like the TransactionState block itself, live
4392  * in TopTransactionContext.
4393  */
4394  if (name)
4396  break;
4397 
4398  /*
4399  * We disallow savepoint commands in implicit transaction blocks.
4400  * There would be no great difficulty in allowing them so far as
4401  * this module is concerned, but a savepoint seems inconsistent
4402  * with exec_simple_query's behavior of abandoning the whole query
4403  * string upon error. Also, the point of an implicit transaction
4404  * block (as opposed to a regular one) is to automatically close
4405  * after an error, so it's hard to see how a savepoint would fit
4406  * into that.
4407  *
4408  * The error messages for this are phrased as if there were no
4409  * active transaction block at all, which is historical but
4410  * perhaps could be improved.
4411  */
4413  ereport(ERROR,
4414  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4415  /* translator: %s represents an SQL statement name */
4416  errmsg("%s can only be used in transaction blocks",
4417  "SAVEPOINT")));
4418  break;
4419 
4420  /* These cases are invalid. */
4421  case TBLOCK_DEFAULT:
4422  case TBLOCK_STARTED:
4423  case TBLOCK_BEGIN:
4425  case TBLOCK_SUBBEGIN:
4426  case TBLOCK_END:
4427  case TBLOCK_SUBRELEASE:
4428  case TBLOCK_SUBCOMMIT:
4429  case TBLOCK_ABORT:
4430  case TBLOCK_SUBABORT:
4431  case TBLOCK_ABORT_END:
4432  case TBLOCK_SUBABORT_END:
4433  case TBLOCK_ABORT_PENDING:
4435  case TBLOCK_SUBRESTART:
4437  case TBLOCK_PREPARE:
4438  elog(FATAL, "DefineSavepoint: unexpected state %s",
4440  break;
4441  }
4442 }
4443 
4444 /*
4445  * ReleaseSavepoint
4446  * This executes a RELEASE command.
4447  *
4448  * As above, we don't actually do anything here except change blockState.
4449  */
4450 void
4452 {
4454  TransactionState target,
4455  xact;
4456 
4457  /*
4458  * Workers synchronize transaction state at the beginning of each parallel
4459  * operation, so we can't account for transaction state change after that
4460  * point. (Note that this check will certainly error out if s->blockState
4461  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4462  * below.)
4463  */
4465  ereport(ERROR,
4466  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4467  errmsg("cannot release savepoints during a parallel operation")));
4468 
4469  switch (s->blockState)
4470  {
4471  /*
4472  * We can't release a savepoint if there is no savepoint defined.
4473  */
4474  case TBLOCK_INPROGRESS:
4475  ereport(ERROR,
4476  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4477  errmsg("savepoint \"%s\" does not exist", name)));
4478  break;
4479 
4481  /* See comment about implicit transactions in DefineSavepoint */
4482  ereport(ERROR,
4483  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4484  /* translator: %s represents an SQL statement name */
4485  errmsg("%s can only be used in transaction blocks",
4486  "RELEASE SAVEPOINT")));
4487  break;
4488 
4489  /*
4490  * We are in a non-aborted subtransaction. This is the only valid
4491  * case.
4492  */
4493  case TBLOCK_SUBINPROGRESS:
4494  break;
4495 
4496  /* These cases are invalid. */
4497  case TBLOCK_DEFAULT:
4498  case TBLOCK_STARTED:
4499  case TBLOCK_BEGIN:
4501  case TBLOCK_SUBBEGIN:
4502  case TBLOCK_END:
4503  case TBLOCK_SUBRELEASE:
4504  case TBLOCK_SUBCOMMIT:
4505  case TBLOCK_ABORT:
4506  case TBLOCK_SUBABORT:
4507  case TBLOCK_ABORT_END:
4508  case TBLOCK_SUBABORT_END:
4509  case TBLOCK_ABORT_PENDING:
4511  case TBLOCK_SUBRESTART:
4513  case TBLOCK_PREPARE:
4514  elog(FATAL, "ReleaseSavepoint: unexpected state %s",
4516  break;
4517  }
4518 
4519  for (target = s; PointerIsValid(target); target = target->parent)
4520  {
4521  if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
4522  break;
4523  }
4524 
4525  if (!PointerIsValid(target))
4526  ereport(ERROR,
4527  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4528  errmsg("savepoint \"%s\" does not exist", name)));
4529 
4530  /* disallow crossing savepoint level boundaries */
4531  if (target->savepointLevel != s->savepointLevel)
4532  ereport(ERROR,
4533  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4534  errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4535 
4536  /*
4537  * Mark "commit pending" all subtransactions up to the target
4538  * subtransaction. The actual commits will happen when control gets to
4539  * CommitTransactionCommand.
4540  */
4541  xact = CurrentTransactionState;
4542  for (;;)
4543  {
4545  xact->blockState = TBLOCK_SUBRELEASE;
4546  if (xact == target)
4547  break;
4548  xact = xact->parent;
4549  Assert(PointerIsValid(xact));
4550  }
4551 }
4552 
4553 /*
4554  * RollbackToSavepoint
4555  * This executes a ROLLBACK TO <savepoint> command.
4556  *
4557  * As above, we don't actually do anything here except change blockState.
4558  */
4559 void
4561 {
4563  TransactionState target,
4564  xact;
4565 
4566  /*
4567  * Workers synchronize transaction state at the beginning of each parallel
4568  * operation, so we can't account for transaction state change after that
4569  * point. (Note that this check will certainly error out if s->blockState
4570  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4571  * below.)
4572  */
4574  ereport(ERROR,
4575  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4576  errmsg("cannot rollback to savepoints during a parallel operation")));
4577 
4578  switch (s->blockState)
4579  {
4580  /*
4581  * We can't rollback to a savepoint if there is no savepoint
4582  * defined.
4583  */
4584  case TBLOCK_INPROGRESS:
4585  case TBLOCK_ABORT:
4586  ereport(ERROR,
4587  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4588  errmsg("savepoint \"%s\" does not exist", name)));
4589  break;
4590 
4592  /* See comment about implicit transactions in DefineSavepoint */
4593  ereport(ERROR,
4594  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4595  /* translator: %s represents an SQL statement name */
4596  errmsg("%s can only be used in transaction blocks",
4597  "ROLLBACK TO SAVEPOINT")));
4598  break;
4599 
4600  /*
4601  * There is at least one savepoint, so proceed.
4602  */
4603  case TBLOCK_SUBINPROGRESS:
4604  case TBLOCK_SUBABORT:
4605  break;
4606 
4607  /* These cases are invalid. */
4608  case TBLOCK_DEFAULT:
4609  case TBLOCK_STARTED:
4610  case TBLOCK_BEGIN:
4612  case TBLOCK_SUBBEGIN:
4613  case TBLOCK_END:
4614  case TBLOCK_SUBRELEASE:
4615  case TBLOCK_SUBCOMMIT:
4616  case TBLOCK_ABORT_END:
4617  case TBLOCK_SUBABORT_END:
4618  case TBLOCK_ABORT_PENDING:
4620  case TBLOCK_SUBRESTART:
4622  case TBLOCK_PREPARE:
4623  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4625  break;
4626  }
4627 
4628  for (target = s; PointerIsValid(target); target = target->parent)
4629  {
4630  if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
4631  break;
4632  }
4633 
4634  if (!PointerIsValid(target))
4635  ereport(ERROR,
4636  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4637  errmsg("savepoint \"%s\" does not exist", name)));
4638 
4639  /* disallow crossing savepoint level boundaries */
4640  if (target->savepointLevel != s->savepointLevel)
4641  ereport(ERROR,
4642  (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4643  errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4644 
4645  /*
4646  * Mark "abort pending" all subtransactions up to the target
4647  * subtransaction. The actual aborts will happen when control gets to
4648  * CommitTransactionCommand.
4649  */
4650  xact = CurrentTransactionState;
4651  for (;;)
4652  {
4653  if (xact == target)
4654  break;
4655  if (xact->blockState == TBLOCK_SUBINPROGRESS)
4657  else if (xact->blockState == TBLOCK_SUBABORT)
4659  else
4660  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4662  xact = xact->parent;
4663  Assert(PointerIsValid(xact));
4664  }
4665 
4666  /* And mark the target as "restart pending" */
4667  if (xact->blockState == TBLOCK_SUBINPROGRESS)
4668  xact->blockState = TBLOCK_SUBRESTART;
4669  else if (xact->blockState == TBLOCK_SUBABORT)
4671  else
4672  elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4674 }
4675 
4676 /*
4677  * BeginInternalSubTransaction
4678  * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
4679  * TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_END,
4680  * and TBLOCK_PREPARE states, and therefore it can safely be used in
4681  * functions that might be called when not inside a BEGIN block or when
4682  * running deferred triggers at COMMIT/PREPARE time. Also, it
4683  * automatically does CommitTransactionCommand/StartTransactionCommand
4684  * instead of expecting the caller to do it.
4685  */
4686 void
4688 {
4690  bool save_ExitOnAnyError = ExitOnAnyError;
4691 
4692  /*
4693  * Errors within this function are improbable, but if one does happen we
4694  * force a FATAL exit. Callers generally aren't prepared to handle losing
4695  * control, and moreover our transaction state is probably corrupted if we
4696  * fail partway through; so an ordinary ERROR longjmp isn't okay.
4697  */
4698  ExitOnAnyError = true;
4699 
4700  /*
4701  * We do not check for parallel mode here. It's permissible to start and
4702  * end "internal" subtransactions while in parallel mode, so long as no
4703  * new XIDs or command IDs are assigned. Enforcement of that occurs in
4704  * AssignTransactionId() and CommandCounterIncrement().
4705  */
4706 
4707  switch (s->blockState)
4708  {
4709  case TBLOCK_STARTED:
4710  case TBLOCK_INPROGRESS:
4713  case TBLOCK_END:
4714  case TBLOCK_PREPARE:
4715  case TBLOCK_SUBINPROGRESS:
4716  /* Normal subtransaction start */
4717  PushTransaction();
4718  s = CurrentTransactionState; /* changed by push */
4719 
4720  /*
4721  * Savepoint names, like the TransactionState block itself, live
4722  * in TopTransactionContext.
4723  */
4724  if (name)
4726  break;
4727 
4728  /* These cases are invalid. */
4729  case TBLOCK_DEFAULT:
4730  case TBLOCK_BEGIN:
4731  case TBLOCK_SUBBEGIN:
4732  case TBLOCK_SUBRELEASE:
4733  case TBLOCK_SUBCOMMIT:
4734  case TBLOCK_ABORT:
4735  case TBLOCK_SUBABORT:
4736  case TBLOCK_ABORT_END:
4737  case TBLOCK_SUBABORT_END:
4738  case TBLOCK_ABORT_PENDING:
4740  case TBLOCK_SUBRESTART:
4742  elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4744  break;
4745  }
4746 
4749 
4750  ExitOnAnyError = save_ExitOnAnyError;
4751 }
4752 
4753 /*
4754  * ReleaseCurrentSubTransaction
4755  *
4756  * RELEASE (ie, commit) the innermost subtransaction, regardless of its
4757  * savepoint name (if any).
4758  * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4759  */
4760 void
4762 {
4764 
4765  /*
4766  * We do not check for parallel mode here. It's permissible to start and
4767  * end "internal" subtransactions while in parallel mode, so long as no
4768  * new XIDs or command IDs are assigned.
4769  */
4770 
4771  if (s->blockState != TBLOCK_SUBINPROGRESS)
4772  elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
4774  Assert(s->state == TRANS_INPROGRESS);
4777  s = CurrentTransactionState; /* changed by pop */
4778  Assert(s->state == TRANS_INPROGRESS);
4779 }
4780 
4781 /*
4782  * RollbackAndReleaseCurrentSubTransaction
4783  *
4784  * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
4785  * of its savepoint name (if any).
4786  * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4787  */
4788 void
4790 {
4792 
4793  /*
4794  * We do not check for parallel mode here. It's permissible to start and
4795  * end "internal" subtransactions while in parallel mode, so long as no
4796  * new XIDs or command IDs are assigned.
4797  */
4798 
4799  switch (s->blockState)
4800  {
4801  /* Must be in a subtransaction */
4802  case TBLOCK_SUBINPROGRESS:
4803  case TBLOCK_SUBABORT:
4804  break;
4805 
4806  /* These cases are invalid. */
4807  case TBLOCK_DEFAULT:
4808  case TBLOCK_STARTED:
4809  case TBLOCK_BEGIN:
4812  case TBLOCK_SUBBEGIN:
4813  case TBLOCK_INPROGRESS:
4814  case TBLOCK_END:
4815  case TBLOCK_SUBRELEASE:
4816  case TBLOCK_SUBCOMMIT:
4817  case TBLOCK_ABORT:
4818  case TBLOCK_ABORT_END:
4819  case TBLOCK_SUBABORT_END:
4820  case TBLOCK_ABORT_PENDING:
4822  case TBLOCK_SUBRESTART:
4824  case TBLOCK_PREPARE:
4825  elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
4827  break;
4828  }
4829 
4830  /*
4831  * Abort the current subtransaction, if needed.
4832  */
4833  if (s->blockState == TBLOCK_SUBINPROGRESS)
4835 
4836  /* And clean it up, too */
4838 
4839  s = CurrentTransactionState; /* changed by pop */
4841  s->blockState == TBLOCK_INPROGRESS ||
4844  s->blockState == TBLOCK_STARTED);
4845 }
4846 
4847 /*
4848  * AbortOutOfAnyTransaction
4849  *
4850  * This routine is provided for error recovery purposes. It aborts any
4851  * active transaction or transaction block, leaving the system in a known
4852  * idle state.
4853  */
4854 void
4856 {
4858 
4859  /* Ensure we're not running in a doomed memory context */
4860  AtAbort_Memory();
4861 
4862  /*
4863  * Get out of any transaction or nested transaction
4864  */
4865  do
4866  {
4867  switch (s->blockState)
4868  {
4869  case TBLOCK_DEFAULT:
4870  if (s->state == TRANS_DEFAULT)
4871  {
4872  /* Not in a transaction, do nothing */
4873  }
4874  else
4875  {
4876  /*
4877  * We can get here after an error during transaction start
4878  * (state will be TRANS_START). Need to clean up the
4879  * incompletely started transaction. First, adjust the
4880  * low-level state to suppress warning message from
4881  * AbortTransaction.
4882  */
4883  if (s->state == TRANS_START)
4884  s->state = TRANS_INPROGRESS;
4885  AbortTransaction();
4887  }
4888  break;
4889  case TBLOCK_STARTED:
4890  case TBLOCK_BEGIN:
4891  case TBLOCK_INPROGRESS:
4894  case TBLOCK_END:
4895  case TBLOCK_ABORT_PENDING:
4896  case TBLOCK_PREPARE:
4897  /* In a transaction, so clean up */
4898  AbortTransaction();
4901  break;
4902  case TBLOCK_ABORT:
4903  case TBLOCK_ABORT_END:
4904 
4905  /*
4906  * AbortTransaction is already done, still need Cleanup.
4907  * However, if we failed partway through running ROLLBACK,
4908  * there will be an active portal running that command, which
4909  * we need to shut down before doing CleanupTransaction.
4910  */
4911  AtAbort_Portals();
4914  break;
4915 
4916  /*
4917  * In a subtransaction, so clean it up and abort parent too
4918  */
4919  case TBLOCK_SUBBEGIN:
4920  case TBLOCK_SUBINPROGRESS:
4921  case TBLOCK_SUBRELEASE:
4922  case TBLOCK_SUBCOMMIT:
4924  case TBLOCK_SUBRESTART:
4927  s = CurrentTransactionState; /* changed by pop */
4928  break;
4929 
4930  case TBLOCK_SUBABORT:
4931  case TBLOCK_SUBABORT_END:
4933  /* As above, but AbortSubTransaction already done */
4934  if (s->curTransactionOwner)
4935  {
4936  /* As in TBLOCK_ABORT, might have a live portal to zap */
4941  }
4943  s = CurrentTransactionState; /* changed by pop */
4944  break;
4945  }
4946  } while (s->blockState != TBLOCK_DEFAULT);
4947 
4948  /* Should be out of all subxacts now */
4949  Assert(s->parent == NULL);
4950 
4951  /*
4952  * Revert to TopMemoryContext, to ensure we exit in a well-defined state
4953  * whether there were any transactions to close or not. (Callers that
4954  * don't intend to exit soon should switch to some other context to avoid
4955  * long-term memory leaks.)
4956  */
4958 }
4959 
4960 /*
4961  * IsTransactionBlock --- are we within a transaction block?
4962  */
4963 bool
4965 {
4967 
4969  return false;
4970 
4971  return true;
4972 }
4973 
4974 /*
4975  * IsTransactionOrTransactionBlock --- are we within either a transaction
4976  * or a transaction block? (The backend is only really "idle" when this
4977  * returns false.)
4978  *
4979  * This should match up with IsTransactionBlock and IsTransactionState.
4980  */
4981 bool
4983 {
4985 
4986  if (s->blockState == TBLOCK_DEFAULT)
4987  return false;
4988 
4989  return true;
4990 }
4991 
4992 /*
4993  * TransactionBlockStatusCode - return status code to send in ReadyForQuery
4994  */
4995 char
4997 {
4999 
5000  switch (s->blockState)
5001  {
5002  case TBLOCK_DEFAULT:
5003  case TBLOCK_STARTED:
5004  return 'I'; /* idle --- not in transaction */
5005  case TBLOCK_BEGIN:
5006  case TBLOCK_SUBBEGIN:
5007  case TBLOCK_INPROGRESS:
5010  case TBLOCK_SUBINPROGRESS:
5011  case TBLOCK_END:
5012  case TBLOCK_SUBRELEASE:
5013  case TBLOCK_SUBCOMMIT:
5014  case TBLOCK_PREPARE:
5015  return 'T'; /* in transaction */
5016  case TBLOCK_ABORT:
5017  case TBLOCK_SUBABORT:
5018  case TBLOCK_ABORT_END:
5019  case TBLOCK_SUBABORT_END:
5020  case TBLOCK_ABORT_PENDING:
5022  case TBLOCK_SUBRESTART:
5024  return 'E'; /* in failed transaction */
5025  }
5026 
5027  /* should never get here */
5028  elog(FATAL, "invalid transaction block state: %s",
5030  return 0; /* keep compiler quiet */
5031 }
5032 
5033 /*
5034  * IsSubTransaction
5035  */
5036 bool
5038 {
5040 
5041  if (s->nestingLevel >= 2)
5042  return true;
5043 
5044  return false;
5045 }
5046 
5047 /*
5048  * StartSubTransaction
5049  *
5050  * If you're wondering why this is separate from PushTransaction: it's because
5051  * we can't conveniently do this stuff right inside DefineSavepoint. The
5052  * SAVEPOINT utility command will be executed inside a Portal, and if we
5053  * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
5054  * the Portal will undo those settings. So we make DefineSavepoint just
5055  * push a dummy transaction block, and when control returns to the main
5056  * idle loop, CommitTransactionCommand will be called, and we'll come here
5057  * to finish starting the subtransaction.
5058  */
5059 static void
5061 {
5063 
5064  if (s->state != TRANS_DEFAULT)
5065  elog(WARNING, "StartSubTransaction while in %s state",
5067 
5068  s->state = TRANS_START;
5069 
5070  /*
5071  * Initialize subsystems for new subtransaction
5072  *
5073  * must initialize resource-management stuff first
5074  */
5078 
5079  s->state = TRANS_INPROGRESS;
5080 
5081  /*
5082  * Call start-of-subxact callbacks
5083  */
5085  s->parent->subTransactionId);
5086 
5087  ShowTransactionState("StartSubTransaction");
5088 }
5089 
5090 /*
5091  * CommitSubTransaction
5092  *
5093  * The caller has to make sure to always reassign CurrentTransactionState
5094  * if it has a local pointer to it after calling this function.
5095  */
5096 static void
5098 {
5100 
5101  ShowTransactionState("CommitSubTransaction");
5102 
5103  if (s->state != TRANS_INPROGRESS)
5104  elog(WARNING, "CommitSubTransaction while in %s state",
5106 
5107  /* Pre-commit processing goes here */
5108 
5110  s->parent->subTransactionId);
5111 
5112  /*
5113  * If this subxact has started any unfinished parallel operation, clean up
5114  * its workers and exit parallel mode. Warn about leaked resources.
5115  */
5117  if (s->parallelModeLevel != 0)
5118  {
5119  elog(WARNING, "parallelModeLevel is %d not 0 at end of subtransaction",
5120  s->parallelModeLevel);
5121  s->parallelModeLevel = 0;
5122  }
5123 
5124  /* Do the actual "commit", such as it is */
5125  s->state = TRANS_COMMIT;
5126 
5127  /* Must CCI to ensure commands of subtransaction are seen as done */
5129 
5130  /*
5131  * Prior to 8.4 we marked subcommit in clog at this point. We now only
5132  * perform that step, if required, as part of the atomic update of the
5133  * whole transaction tree at top level commit or abort.
5134  */
5135 
5136  /* Post-commit cleanup */
5139  AfterTriggerEndSubXact(true);
5142  s->parent->nestingLevel,
5145  s->parent->subTransactionId);
5147 
5149  s->parent->subTransactionId);
5150 
5153  true, false);
5155  s->parent->subTransactionId);
5156  AtEOSubXact_Inval(true);
5157  AtSubCommit_smgr();
5158 
5159  /*
5160  * The only lock we actually release here is the subtransaction XID lock.
5161  */
5165 
5166  /*
5167  * Other locks should get transferred to their parent resource owner.
5168  */
5171  true, false);
5174  true, false);
5175 
5176  AtEOXact_GUC(true, s->gucNestLevel);
5179  s->parent->subTransactionId);
5181  s->parent->subTransactionId);
5183  s->parent->subTransactionId);
5185  AtEOSubXact_PgStat(true, s->nestingLevel);
5187 
5188  /*
5189  * We need to restore the upper transaction's read-only state, in case the
5190  * upper is read-write while the child is read-only; GUC will incorrectly
5191  * think it should leave the child state in place.
5192  */
5194 
5198  s->curTransactionOwner = NULL;
5199 
5201 
5202  s->state = TRANS_DEFAULT;
5203 
5204  PopTransaction();
5205 }
5206 
5207 /*
5208  * AbortSubTransaction
5209  */
5210 static void
5212 {
5214 
5215  /* Prevent cancel/die interrupt while cleaning up */
5216  HOLD_INTERRUPTS();
5217 
5218  /* Make sure we have a valid memory context and resource owner */
5221 
5222  /*
5223  * Release any LW locks we might be holding as quickly as possible.
5224  * (Regular locks, however, must be held till we finish aborting.)
5225  * Releasing LW locks is critical since we might try to grab them again
5226  * while cleaning up!
5227  *
5228  * FIXME This may be incorrect --- Are there some locks we should keep?
5229  * Buffer locks, for example? I don't think so but I'm not sure.
5230  */
5231  LWLockReleaseAll();
5232 
5235  UnlockBuffers();
5236 
5237  /* Reset WAL record construction state */
5239 
5240  /* Cancel condition variable sleep */
5242 
5243  /*
5244  * Also clean up any open wait for lock, since the lock manager will choke
5245  * if we try to wait for another lock before doing this.
5246  */
5247  LockErrorCleanup();
5248 
5249  /*
5250  * If any timeout events are still active, make sure the timeout interrupt
5251  * is scheduled. This covers possible loss of a timeout interrupt due to
5252  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
5253  * We delay this till after LockErrorCleanup so that we don't uselessly
5254  * reschedule lock or deadlock check timeouts.
5255  */
5257 
5258  /*
5259  * Re-enable signals, in case we got here by longjmp'ing out of a signal
5260  * handler. We do this fairly early in the sequence so that the timeout
5261  * infrastructure will be functional if needed while aborting.
5262  */
5263  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
5264 
5265  /*
5266  * check the current transaction state
5267  */
5268  ShowTransactionState("AbortSubTransaction");
5269 
5270  if (s->state != TRANS_INPROGRESS)
5271  elog(WARNING, "AbortSubTransaction while in %s state",
5273 
5274  s->state = TRANS_ABORT;
5275 
5276  /*
5277  * Reset user ID which might have been changed transiently. (See notes in
5278  * AbortTransaction.)
5279  */
5281 
5282  /* Forget about any active REINDEX. */
5284 
5285  /* Reset logical streaming state. */
5287 
5288  /*
5289  * No need for SnapBuildResetExportedSnapshotState() here, snapshot
5290  * exports are not supported in subtransactions.
5291  */
5292 
5293  /*
5294  * If this subxact has started any unfinished parallel operation, clean up
5295  * its workers and exit parallel mode. Don't warn about leaked resources.
5296  */
5298  s->parallelModeLevel = 0;
5299 
5300  /*
5301  * We can skip all this stuff if the subxact failed before creating a
5302  * ResourceOwner...
5303  */
5304  if (s->curTransactionOwner)
5305  {
5306  AfterTriggerEndSubXact(false);
5312  s->parent->subTransactionId);
5314 
5315  /* Advertise the fact that we aborted in pg_xact. */
5316  (void) RecordTransactionAbort(true);
5317 
5318  /* Post-abort cleanup */
5321 
5323  s->parent->subTransactionId);
5324 
5327  false, false);
5328 
5330  s->parent->subTransactionId);
5331  AtEOSubXact_Inval(false);
5334  false, false);
5337  false, false);
5338  AtSubAbort_smgr();
5339 
5340  AtEOXact_GUC(false, s->gucNestLevel);
5341  AtEOSubXact_SPI(false, s->subTransactionId);
5343  s->parent->subTransactionId);
5345  s->parent->subTransactionId);
5347  s->parent->subTransactionId);
5349  AtEOSubXact_PgStat(false, s->nestingLevel);
5351  }
5352 
5353  /*
5354  * Restore the upper transaction's read-only state, too. This should be
5355  * redundant with GUC's cleanup but we may as well do it for consistency
5356  * with the commit case.
5357  */
5359 
5361 }
5362 
5363 /*
5364  * CleanupSubTransaction
5365  *
5366  * The caller has to make sure to always reassign CurrentTransactionState
5367  * if it has a local pointer to it after calling this function.
5368  */
5369 static void
5371 {
5373 
5374  ShowTransactionState("CleanupSubTransaction");
5375 
5376  if (s->state != TRANS_ABORT)
5377  elog(WARNING, "CleanupSubTransaction while in %s state",
5379 
5381 
5384  if (s->curTransactionOwner)
5386  s->curTransactionOwner = NULL;
5387 
5389 
5390  s->state = TRANS_DEFAULT;
5391 
5392  PopTransaction();
5393 }
5394 
5395 /*
5396  * PushTransaction
5397  * Create transaction state stack entry for a subtransaction
5398  *
5399  * The caller has to make sure to always reassign CurrentTransactionState
5400  * if it has a local pointer to it after calling this function.
5401  */
5402 static void
5404 {
5406  TransactionState s;
5407 
5408  /*
5409  * We keep subtransaction state nodes in TopTransactionContext.
5410  */
5411  s = (TransactionState)
5413  sizeof(TransactionStateData));
5414 
5415  /*
5416  * Assign a subtransaction ID, watching out for counter wraparound.
5417  */
5420  {
5422  pfree(s);
5423  ereport(ERROR,
5424  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5425  errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
5426  }
5427 
5428  /*
5429  * We can now stack a minimally valid subtransaction without fear of
5430  * failure.
5431  */
5432  s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
5434  s->parent = p;
5435  s->nestingLevel = p->nestingLevel + 1;
5438  s->state = TRANS_DEFAULT;
5443  s->parallelModeLevel = 0;
5445  s->topXidLogged = false;
5446 
5448 
5449  /*
5450  * AbortSubTransaction and CleanupSubTransaction have to be able to cope
5451  * with the subtransaction from here on out; in particular they should not
5452  * assume that it necessarily has a transaction context, resource owner,
5453  * or XID.
5454  */
5455 }
5456 
5457 /*
5458  * PopTransaction
5459  * Pop back to parent transaction state
5460  *
5461  * The caller has to make sure to always reassign CurrentTransactionState
5462  * if it has a local pointer to it after calling this function.
5463  */
5464 static void
5466 {
5468 
5469  if (s->state != TRANS_DEFAULT)
5470  elog(WARNING, "PopTransaction while in %s state",
5472 
5473  if (s->parent == NULL)
5474  elog(FATAL, "PopTransaction with no parent");
5475 
5477 
5478  /* Let's just make sure CurTransactionContext is good */
5481 
5482  /* Ditto for ResourceOwner links */
5485 
5486  /* Free the old child structure */
5487  if (s->name)
5488  pfree(s->name);
5489  pfree(s);
5490 }
5491 
5492 /*
5493  * EstimateTransactionStateSpace
5494  * Estimate the amount of space that will be needed by
5495  * SerializeTransactionState. It would be OK to overestimate slightly,
5496  * but it's simple for us to work out the precise value, so we do.
5497  */
5498 Size
5500 {
5501  TransactionState s;
5502  Size nxids = 0;
5504 
5505  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5506  {
5508  nxids = add_size(nxids, 1);
5509  nxids = add_size(nxids, s->nChildXids);
5510  }
5511 
5512  return add_size(size, mul_size(sizeof(TransactionId), nxids));
5513 }
5514 
5515 /*
5516  * SerializeTransactionState
5517  * Write out relevant details of our transaction state that will be
5518  * needed by a parallel worker.
5519  *
5520  * We need to save and restore XactDeferrable, XactIsoLevel, and the XIDs
5521  * associated with this transaction. These are serialized into a
5522  * caller-supplied buffer big enough to hold the number of bytes reported by
5523  * EstimateTransactionStateSpace(). We emit the XIDs in sorted order for the
5524  * convenience of the receiving process.
5525  */
5526 void
5527 SerializeTransactionState(Size maxsize, char *start_address)
5528 {
5529  TransactionState s;
5530  Size nxids = 0;
5531  Size i = 0;
5532  TransactionId *workspace;
5534 
5535  result = (SerializedTransactionState *) start_address;
5536 
5537  result->xactIsoLevel = XactIsoLevel;
5538  result->xactDeferrable = XactDeferrable;
5540  result->currentFullTransactionId =
5543 
5544  /*
5545  * If we're running in a parallel worker and launching a parallel worker
5546  * of our own, we can just pass along the information that was passed to
5547  * us.
5548  */
5549  if (nParallelCurrentXids > 0)
5550  {
5552  memcpy(&result->parallelCurrentXids[0], ParallelCurrentXids,
5554  return;
5555  }
5556 
5557  /*
5558  * OK, we need to generate a sorted list of XIDs that our workers should
5559  * view as current. First, figure out how many there are.
5560  */
5561  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5562  {
5564  nxids = add_size(nxids, 1);
5565  nxids = add_size(nxids, s->nChildXids);
5566  }
5568  <= maxsize);
5569 
5570  /* Copy them to our scratch space. */
5571  workspace = palloc(nxids * sizeof(TransactionId));
5572  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5573  {
5575  workspace[i++] = XidFromFullTransactionId(s->fullTransactionId);
5576  if (s->nChildXids > 0)
5577  memcpy(&workspace[i], s->childXids,
5578  s->nChildXids * sizeof(TransactionId));
5579  i += s->nChildXids;
5580  }
5581  Assert(i == nxids);
5582 
5583  /* Sort them. */
5584  qsort(workspace, nxids, sizeof(TransactionId), xidComparator);
5585 
5586  /* Copy data into output area. */
5587  result->nParallelCurrentXids = nxids;
5588  memcpy(&result->parallelCurrentXids[0], workspace,
5589  nxids * sizeof(TransactionId));
5590 }
5591 
5592 /*
5593  * StartParallelWorkerTransaction
5594  * Start a parallel worker transaction, restoring the relevant
5595  * transaction state serialized by SerializeTransactionState.
5596  */
5597 void
5599 {
5601 
5603  StartTransaction();
5604 
5605  tstate = (SerializedTransactionState *) tstatespace;
5606  XactIsoLevel = tstate->xactIsoLevel;
5607  XactDeferrable = tstate->xactDeferrable;
5610  tstate->currentFullTransactionId;
5614 
5616 }
5617 
5618 /*
5619  * EndParallelWorkerTransaction
5620  * End a parallel worker transaction.
5621  */
5622 void
5624 {
5628 }
5629 
5630 /*
5631  * ShowTransactionState
5632  * Debug support
5633  */
5634 static void
5636 {
5637  /* skip work if message will definitely not be printed */
5640 }
5641 
5642 /*
5643  * ShowTransactionStateRec
5644  * Recursive subroutine for ShowTransactionState
5645  */
5646 static void
5648 {
5650 
5651  if (s->parent)
5652  {
5653  /*
5654  * Since this function recurses, it could be driven to stack overflow.
5655  * This is just a debugging aid, so we can leave out some details
5656  * instead of erroring out with check_stack_depth().
5657  */
5658  if (stack_is_too_deep())
5659  ereport(DEBUG5,
5660  (errmsg_internal("%s(%d): parent omitted to avoid stack overflow",
5661  str, s->nestingLevel)));
5662  else
5664  }
5665 
5666  initStringInfo(&buf);
5667  if (s->nChildXids > 0)
5668  {
5669  int i;
5670 
5671  appendStringInfo(&buf, ", children: %u", s->childXids[0]);
5672  for (i = 1; i < s->nChildXids; i++)
5673  appendStringInfo(&buf, " %u", s->childXids[i]);
5674  }
5675  ereport(DEBUG5,
5676  (errmsg_internal("%s(%d) name: %s; blockState: %s; state: %s, xid/subid/cid: %u/%u/%u%s%s",
5677  str, s->nestingLevel,
5678  PointerIsValid(s->