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