PostgreSQL Source Code  git master
trigger.h File Reference
Include dependency graph for trigger.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  TriggerData
 
struct  TransitionCaptureState
 

Macros

#define CALLED_AS_TRIGGER(fcinfo)   ((fcinfo)->context != NULL && IsA((fcinfo)->context, TriggerData))
 
#define TRIGGER_EVENT_INSERT   0x00000000
 
#define TRIGGER_EVENT_DELETE   0x00000001
 
#define TRIGGER_EVENT_UPDATE   0x00000002
 
#define TRIGGER_EVENT_TRUNCATE   0x00000003
 
#define TRIGGER_EVENT_OPMASK   0x00000003
 
#define TRIGGER_EVENT_ROW   0x00000004
 
#define TRIGGER_EVENT_BEFORE   0x00000008
 
#define TRIGGER_EVENT_AFTER   0x00000000
 
#define TRIGGER_EVENT_INSTEAD   0x00000010
 
#define TRIGGER_EVENT_TIMINGMASK   0x00000018
 
#define AFTER_TRIGGER_DEFERRABLE   0x00000020
 
#define AFTER_TRIGGER_INITDEFERRED   0x00000040
 
#define TRIGGER_FIRED_BY_INSERT(event)   (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_INSERT)
 
#define TRIGGER_FIRED_BY_DELETE(event)   (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_DELETE)
 
#define TRIGGER_FIRED_BY_UPDATE(event)   (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_UPDATE)
 
#define TRIGGER_FIRED_BY_TRUNCATE(event)   (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_TRUNCATE)
 
#define TRIGGER_FIRED_FOR_ROW(event)   ((event) & TRIGGER_EVENT_ROW)
 
#define TRIGGER_FIRED_FOR_STATEMENT(event)   (!TRIGGER_FIRED_FOR_ROW(event))
 
#define TRIGGER_FIRED_BEFORE(event)   (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_BEFORE)
 
#define TRIGGER_FIRED_AFTER(event)   (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_AFTER)
 
#define TRIGGER_FIRED_INSTEAD(event)   (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_INSTEAD)
 
#define SESSION_REPLICATION_ROLE_ORIGIN   0
 
#define SESSION_REPLICATION_ROLE_REPLICA   1
 
#define SESSION_REPLICATION_ROLE_LOCAL   2
 
#define TRIGGER_FIRES_ON_ORIGIN   'O'
 
#define TRIGGER_FIRES_ALWAYS   'A'
 
#define TRIGGER_FIRES_ON_REPLICA   'R'
 
#define TRIGGER_DISABLED   'D'
 
#define RI_TRIGGER_PK   1 /* is a trigger on the PK relation */
 
#define RI_TRIGGER_FK   2 /* is a trigger on the FK relation */
 
#define RI_TRIGGER_NONE   0 /* is not an RI trigger function */
 

Typedefs

typedef uint32 TriggerEvent
 
typedef struct TriggerData TriggerData
 
typedef struct TransitionCaptureState TransitionCaptureState
 

Functions

ObjectAddress CreateTrigger (CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition)
 
ObjectAddress CreateTriggerFiringOn (CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition, char trigger_fires_when)
 
void RemoveTriggerById (Oid trigOid)
 
Oid get_trigger_oid (Oid relid, const char *name, bool missing_ok)
 
ObjectAddress renametrig (RenameStmt *stmt)
 
void EnableDisableTrigger (Relation rel, const char *tgname, char fires_when, bool skip_system, LOCKMODE lockmode)
 
void RelationBuildTriggers (Relation relation)
 
TriggerDescCopyTriggerDesc (TriggerDesc *trigdesc)
 
const char * FindTriggerIncompatibleWithInheritance (TriggerDesc *trigdesc)
 
TransitionCaptureStateMakeTransitionCaptureState (TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
 
void FreeTriggerDesc (TriggerDesc *trigdesc)
 
void ExecBSInsertTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASInsertTriggers (EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
 
bool ExecBRInsertTriggers (EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
 
void ExecARInsertTriggers (EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
 
bool ExecIRInsertTriggers (EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
 
void ExecBSDeleteTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASDeleteTriggers (EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
 
bool ExecBRDeleteTriggers (EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot **epqslot)
 
void ExecARDeleteTriggers (EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TransitionCaptureState *transition_capture)
 
bool ExecIRDeleteTriggers (EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple)
 
void ExecBSUpdateTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASUpdateTriggers (EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
 
bool ExecBRUpdateTriggers (EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *slot)
 
void ExecARUpdateTriggers (EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
 
bool ExecIRUpdateTriggers (EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *slot)
 
void ExecBSTruncateTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASTruncateTriggers (EState *estate, ResultRelInfo *relinfo)
 
void AfterTriggerBeginXact (void)
 
void AfterTriggerBeginQuery (void)
 
void AfterTriggerEndQuery (EState *estate)
 
void AfterTriggerFireDeferred (void)
 
void AfterTriggerEndXact (bool isCommit)
 
void AfterTriggerBeginSubXact (void)
 
void AfterTriggerEndSubXact (bool isCommit)
 
void AfterTriggerSetState (ConstraintsSetStmt *stmt)
 
bool AfterTriggerPendingOnRel (Oid relid)
 
bool RI_FKey_pk_upd_check_required (Trigger *trigger, Relation pk_rel, TupleTableSlot *old_slot, TupleTableSlot *new_slot)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, TupleTableSlot *old_slot, TupleTableSlot *new_slot)
 
bool RI_Initial_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
void RI_PartitionRemove_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
int RI_FKey_trigger_type (Oid tgfoid)
 

Variables

PGDLLIMPORT int SessionReplicationRole
 

Macro Definition Documentation

◆ AFTER_TRIGGER_DEFERRABLE

#define AFTER_TRIGGER_DEFERRABLE   0x00000020

Definition at line 106 of file trigger.h.

Referenced by afterTriggerCheckState(), AfterTriggerSaveEvent(), and ExecCallTriggerFunc().

◆ AFTER_TRIGGER_INITDEFERRED

#define AFTER_TRIGGER_INITDEFERRED   0x00000040

Definition at line 107 of file trigger.h.

Referenced by afterTriggerCheckState(), AfterTriggerSaveEvent(), and ExecCallTriggerFunc().

◆ CALLED_AS_TRIGGER

◆ RI_TRIGGER_FK

#define RI_TRIGGER_FK   2 /* is a trigger on the FK relation */

Definition at line 269 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), and RI_FKey_trigger_type().

◆ RI_TRIGGER_NONE

#define RI_TRIGGER_NONE   0 /* is not an RI trigger function */

Definition at line 270 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), and RI_FKey_trigger_type().

◆ RI_TRIGGER_PK

#define RI_TRIGGER_PK   1 /* is a trigger on the PK relation */

Definition at line 268 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), and RI_FKey_trigger_type().

◆ SESSION_REPLICATION_ROLE_LOCAL

#define SESSION_REPLICATION_ROLE_LOCAL   2

Definition at line 141 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_ORIGIN

#define SESSION_REPLICATION_ROLE_ORIGIN   0

Definition at line 139 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_REPLICA

#define SESSION_REPLICATION_ROLE_REPLICA   1

Definition at line 140 of file trigger.h.

Referenced by filter_event_trigger(), matchLocks(), and TriggerEnabled().

◆ TRIGGER_DISABLED

#define TRIGGER_DISABLED   'D'

Definition at line 151 of file trigger.h.

Referenced by ATExecCmd(), BuildEventTriggerCache(), and TriggerEnabled().

◆ TRIGGER_EVENT_AFTER

#define TRIGGER_EVENT_AFTER   0x00000000

Definition at line 100 of file trigger.h.

◆ TRIGGER_EVENT_BEFORE

◆ TRIGGER_EVENT_DELETE

#define TRIGGER_EVENT_DELETE   0x00000001

◆ TRIGGER_EVENT_INSERT

◆ TRIGGER_EVENT_INSTEAD

#define TRIGGER_EVENT_INSTEAD   0x00000010

Definition at line 101 of file trigger.h.

Referenced by ExecIRDeleteTriggers(), ExecIRInsertTriggers(), and ExecIRUpdateTriggers().

◆ TRIGGER_EVENT_OPMASK

#define TRIGGER_EVENT_OPMASK   0x00000003

◆ TRIGGER_EVENT_ROW

◆ TRIGGER_EVENT_TIMINGMASK

#define TRIGGER_EVENT_TIMINGMASK   0x00000018

Definition at line 102 of file trigger.h.

◆ TRIGGER_EVENT_TRUNCATE

#define TRIGGER_EVENT_TRUNCATE   0x00000003

Definition at line 94 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), ExecASTruncateTriggers(), and ExecBSTruncateTriggers().

◆ TRIGGER_EVENT_UPDATE

◆ TRIGGER_FIRED_AFTER

◆ TRIGGER_FIRED_BEFORE

◆ TRIGGER_FIRED_BY_DELETE

◆ TRIGGER_FIRED_BY_INSERT

◆ TRIGGER_FIRED_BY_TRUNCATE

#define TRIGGER_FIRED_BY_TRUNCATE (   event)    (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_TRUNCATE)

◆ TRIGGER_FIRED_BY_UPDATE

◆ TRIGGER_FIRED_FOR_ROW

◆ TRIGGER_FIRED_FOR_STATEMENT

#define TRIGGER_FIRED_FOR_STATEMENT (   event)    (!TRIGGER_FIRED_FOR_ROW(event))

◆ TRIGGER_FIRED_INSTEAD

#define TRIGGER_FIRED_INSTEAD (   event)    (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_INSTEAD)

◆ TRIGGER_FIRES_ALWAYS

#define TRIGGER_FIRES_ALWAYS   'A'

Definition at line 149 of file trigger.h.

Referenced by ATExecCmd().

◆ TRIGGER_FIRES_ON_ORIGIN

◆ TRIGGER_FIRES_ON_REPLICA

#define TRIGGER_FIRES_ON_REPLICA   'R'

Definition at line 150 of file trigger.h.

Referenced by ATExecCmd(), filter_event_trigger(), and TriggerEnabled().

Typedef Documentation

◆ TransitionCaptureState

◆ TriggerData

typedef struct TriggerData TriggerData

◆ TriggerEvent

Definition at line 28 of file trigger.h.

Function Documentation

◆ AfterTriggerBeginQuery()

void AfterTriggerBeginQuery ( void  )

Definition at line 4670 of file trigger.c.

References AfterTriggersData::query_depth.

Referenced by CopyFrom(), create_edata_for_relation(), ExecuteTruncateGuts(), and standard_ExecutorStart().

4671 {
4672  /* Increase the query stack depth */
4674 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3679

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 4940 of file trigger.c.

References AfterTriggersData::events, AfterTriggersTransData::events, AfterTriggersData::firing_counter, AfterTriggersTransData::firing_counter, GetCurrentTransactionNestLevel(), AfterTriggersData::maxtransdepth, MemoryContextAlloc(), AfterTriggersData::query_depth, AfterTriggersTransData::query_depth, repalloc(), AfterTriggersTransData::state, TopTransactionContext, and AfterTriggersData::trans_stack.

Referenced by StartSubTransaction().

4941 {
4942  int my_level = GetCurrentTransactionNestLevel();
4943 
4944  /*
4945  * Allocate more space in the trans_stack if needed. (Note: because the
4946  * minimum nest level of a subtransaction is 2, we waste the first couple
4947  * entries of the array; not worth the notational effort to avoid it.)
4948  */
4949  while (my_level >= afterTriggers.maxtransdepth)
4950  {
4951  if (afterTriggers.maxtransdepth == 0)
4952  {
4953  /* Arbitrarily initialize for max of 8 subtransaction levels */
4956  8 * sizeof(AfterTriggersTransData));
4958  }
4959  else
4960  {
4961  /* repalloc will keep the stack in the same context */
4962  int new_alloc = afterTriggers.maxtransdepth * 2;
4963 
4966  new_alloc * sizeof(AfterTriggersTransData));
4967  afterTriggers.maxtransdepth = new_alloc;
4968  }
4969  }
4970 
4971  /*
4972  * Push the current information into the stack. The SET CONSTRAINTS state
4973  * is not saved until/unless changed. Likewise, we don't make a
4974  * per-subtransaction event context until needed.
4975  */
4976  afterTriggers.trans_stack[my_level].state = NULL;
4980 }
AfterTriggersTransData * trans_stack
Definition: trigger.c:3645
MemoryContext TopTransactionContext
Definition: mcxt.c:53
AfterTriggerEventList events
Definition: trigger.c:3660
CommandId firing_counter
Definition: trigger.c:3662
CommandId firing_counter
Definition: trigger.c:3634
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
AfterTriggerEventList events
Definition: trigger.c:3636
static AfterTriggersData afterTriggers
Definition: trigger.c:3679
SetConstraintState state
Definition: trigger.c:3659

◆ AfterTriggerBeginXact()

void AfterTriggerBeginXact ( void  )

Definition at line 4638 of file trigger.c.

References Assert, AfterTriggersData::event_cxt, AfterTriggersData::events, AfterTriggersData::firing_counter, AfterTriggerEventList::head, AfterTriggersData::maxquerydepth, AfterTriggersData::maxtransdepth, AfterTriggersData::query_depth, AfterTriggersData::query_stack, AfterTriggersData::state, and AfterTriggersData::trans_stack.

Referenced by StartTransaction().

4639 {
4640  /*
4641  * Initialize after-trigger state structure to empty
4642  */
4643  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4645 
4646  /*
4647  * Verify that there is no leftover state remaining. If these assertions
4648  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4649  * up properly.
4650  */
4651  Assert(afterTriggers.state == NULL);
4652  Assert(afterTriggers.query_stack == NULL);
4654  Assert(afterTriggers.event_cxt == NULL);
4655  Assert(afterTriggers.events.head == NULL);
4656  Assert(afterTriggers.trans_stack == NULL);
4658 }
uint32 CommandId
Definition: c.h:601
AfterTriggersTransData * trans_stack
Definition: trigger.c:3645
AfterTriggersQueryData * query_stack
Definition: trigger.c:3640
SetConstraintState state
Definition: trigger.c:3635
CommandId firing_counter
Definition: trigger.c:3634
#define Assert(condition)
Definition: c.h:804
AfterTriggerEventChunk * head
Definition: trigger.c:3528
MemoryContext event_cxt
Definition: trigger.c:3637
AfterTriggerEventList events
Definition: trigger.c:3636
static AfterTriggersData afterTriggers
Definition: trigger.c:3679

◆ AfterTriggerEndQuery()

void AfterTriggerEndQuery ( EState estate)

Definition at line 4690 of file trigger.c.

References afterTriggerDeleteHeadEventChunk(), AfterTriggerFreeQuery(), afterTriggerInvokeEvents(), afterTriggerMarkEvents(), Assert, AfterTriggersData::events, AfterTriggersQueryData::events, AfterTriggersData::firing_counter, AfterTriggerEventList::head, AfterTriggersData::maxquerydepth, AfterTriggersData::query_depth, AfterTriggersData::query_stack, and AfterTriggerEventList::tail.

Referenced by CopyFrom(), ExecuteTruncateGuts(), finish_edata(), and standard_ExecutorFinish().

4691 {
4693 
4694  /* Must be inside a query, too */
4696 
4697  /*
4698  * If we never even got as far as initializing the event stack, there
4699  * certainly won't be any events, so exit quickly.
4700  */
4702  {
4704  return;
4705  }
4706 
4707  /*
4708  * Process all immediate-mode triggers queued by the query, and move the
4709  * deferred ones to the main list of deferred events.
4710  *
4711  * Notice that we decide which ones will be fired, and put the deferred
4712  * ones on the main list, before anything is actually fired. This ensures
4713  * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
4714  * IMMEDIATE: all events we have decided to defer will be available for it
4715  * to fire.
4716  *
4717  * We loop in case a trigger queues more events at the same query level.
4718  * Ordinary trigger functions, including all PL/pgSQL trigger functions,
4719  * will instead fire any triggers in a dedicated query level. Foreign key
4720  * enforcement triggers do add to the current query level, thanks to their
4721  * passing fire_triggers = false to SPI_execute_snapshot(). Other
4722  * C-language triggers might do likewise.
4723  *
4724  * If we find no firable events, we don't have to increment
4725  * firing_counter.
4726  */
4728 
4729  for (;;)
4730  {
4732  {
4733  CommandId firing_id = afterTriggers.firing_counter++;
4734  AfterTriggerEventChunk *oldtail = qs->events.tail;
4735 
4736  if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
4737  break; /* all fired */
4738 
4739  /*
4740  * Firing a trigger could result in query_stack being repalloc'd,
4741  * so we must recalculate qs after each afterTriggerInvokeEvents
4742  * call. Furthermore, it's unsafe to pass delete_ok = true here,
4743  * because that could cause afterTriggerInvokeEvents to try to
4744  * access qs->events after the stack has been repalloc'd.
4745  */
4747 
4748  /*
4749  * We'll need to scan the events list again. To reduce the cost
4750  * of doing so, get rid of completely-fired chunks. We know that
4751  * all events were marked IN_PROGRESS or DONE at the conclusion of
4752  * afterTriggerMarkEvents, so any still-interesting events must
4753  * have been added after that, and so must be in the chunk that
4754  * was then the tail chunk, or in later chunks. So, zap all
4755  * chunks before oldtail. This is approximately the same set of
4756  * events we would have gotten rid of by passing delete_ok = true.
4757  */
4758  Assert(oldtail != NULL);
4759  while (qs->events.head != oldtail)
4761  }
4762  else
4763  break;
4764  }
4765 
4766  /* Release query-level-local storage, including tuplestores if any */
4768 
4770 }
uint32 CommandId
Definition: c.h:601
static void afterTriggerDeleteHeadEventChunk(AfterTriggersQueryData *qs)
Definition: trigger.c:3966
AfterTriggersQueryData * query_stack
Definition: trigger.c:3640
AfterTriggerEventChunk * tail
Definition: trigger.c:3529
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4318
CommandId firing_counter
Definition: trigger.c:3634
#define Assert(condition)
Definition: c.h:804
AfterTriggerEventChunk * head
Definition: trigger.c:3528
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4234
AfterTriggerEventList events
Definition: trigger.c:3636
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:4781
AfterTriggerEventList events
Definition: trigger.c:3651
static AfterTriggersData afterTriggers
Definition: trigger.c:3679

◆ AfterTriggerEndSubXact()

void AfterTriggerEndSubXact ( bool  isCommit)

Definition at line 4988 of file trigger.c.

References AFTER_TRIGGER_DONE, AFTER_TRIGGER_IN_PROGRESS, AfterTriggerFreeQuery(), afterTriggerRestoreEventList(), Assert, AfterTriggerEventData::ate_flags, AfterTriggerSharedData::ats_firing_id, AfterTriggersData::events, AfterTriggersTransData::events, AfterTriggersTransData::firing_counter, for_each_event_chunk, GetCurrentTransactionNestLevel(), GetTriggerSharedData, AfterTriggersData::maxquerydepth, AfterTriggersData::maxtransdepth, pfree(), AfterTriggersData::query_depth, AfterTriggersTransData::query_depth, AfterTriggersData::query_stack, AfterTriggersData::state, AfterTriggersTransData::state, and AfterTriggersData::trans_stack.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

4989 {
4990  int my_level = GetCurrentTransactionNestLevel();
4992  AfterTriggerEvent event;
4993  AfterTriggerEventChunk *chunk;
4994  CommandId subxact_firing_id;
4995 
4996  /*
4997  * Pop the prior state if needed.
4998  */
4999  if (isCommit)
5000  {
5001  Assert(my_level < afterTriggers.maxtransdepth);
5002  /* If we saved a prior state, we don't need it anymore */
5003  state = afterTriggers.trans_stack[my_level].state;
5004  if (state != NULL)
5005  pfree(state);
5006  /* this avoids double pfree if error later: */
5007  afterTriggers.trans_stack[my_level].state = NULL;
5010  }
5011  else
5012  {
5013  /*
5014  * Aborting. It is possible subxact start failed before calling
5015  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
5016  * trans_stack levels that aren't there.
5017  */
5018  if (my_level >= afterTriggers.maxtransdepth)
5019  return;
5020 
5021  /*
5022  * Release query-level storage for queries being aborted, and restore
5023  * query_depth to its pre-subxact value. This assumes that a
5024  * subtransaction will not add events to query levels started in a
5025  * earlier transaction state.
5026  */
5028  {
5032  }
5035 
5036  /*
5037  * Restore the global deferred-event list to its former length,
5038  * discarding any events queued by the subxact.
5039  */
5041  &afterTriggers.trans_stack[my_level].events);
5042 
5043  /*
5044  * Restore the trigger state. If the saved state is NULL, then this
5045  * subxact didn't save it, so it doesn't need restoring.
5046  */
5047  state = afterTriggers.trans_stack[my_level].state;
5048  if (state != NULL)
5049  {
5051  afterTriggers.state = state;
5052  }
5053  /* this avoids double pfree if error later: */
5054  afterTriggers.trans_stack[my_level].state = NULL;
5055 
5056  /*
5057  * Scan for any remaining deferred events that were marked DONE or IN
5058  * PROGRESS by this subxact or a child, and un-mark them. We can
5059  * recognize such events because they have a firing ID greater than or
5060  * equal to the firing_counter value we saved at subtransaction start.
5061  * (This essentially assumes that the current subxact includes all
5062  * subxacts started after it.)
5063  */
5064  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
5066  {
5067  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5068 
5069  if (event->ate_flags &
5071  {
5072  if (evtshared->ats_firing_id >= subxact_firing_id)
5073  event->ate_flags &=
5075  }
5076  }
5077  }
5078 }
uint32 CommandId
Definition: c.h:601
AfterTriggersTransData * trans_stack
Definition: trigger.c:3645
TriggerFlags ate_flags
Definition: trigger.c:3479
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3454
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3541
AfterTriggerEventList events
Definition: trigger.c:3660
AfterTriggersQueryData * query_stack
Definition: trigger.c:3640
CommandId firing_counter
Definition: trigger.c:3662
#define GetTriggerSharedData(evt)
Definition: trigger.c:3504
void pfree(void *pointer)
Definition: mcxt.c:1169
SetConstraintState state
Definition: trigger.c:3635
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
#define Assert(condition)
Definition: c.h:804
Definition: regguts.h:317
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:3926
CommandId ats_firing_id
Definition: trigger.c:3470
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3455
AfterTriggerEventList events
Definition: trigger.c:3636
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:4781
static AfterTriggersData afterTriggers
Definition: trigger.c:3679
SetConstraintState state
Definition: trigger.c:3659

◆ AfterTriggerEndXact()

void AfterTriggerEndXact ( bool  isCommit)

Definition at line 4892 of file trigger.c.

References AfterTriggersData::event_cxt, AfterTriggersData::events, AfterTriggerEventList::head, AfterTriggersData::maxquerydepth, AfterTriggersData::maxtransdepth, MemoryContextDelete(), AfterTriggersData::query_depth, AfterTriggersData::query_stack, AfterTriggersData::state, AfterTriggerEventList::tail, AfterTriggerEventList::tailfree, and AfterTriggersData::trans_stack.

Referenced by AbortTransaction(), CommitTransaction(), and PrepareTransaction().

4893 {
4894  /*
4895  * Forget the pending-events list.
4896  *
4897  * Since all the info is in TopTransactionContext or children thereof, we
4898  * don't really need to do anything to reclaim memory. However, the
4899  * pending-events list could be large, and so it's useful to discard it as
4900  * soon as possible --- especially if we are aborting because we ran out
4901  * of memory for the list!
4902  */
4904  {
4906  afterTriggers.event_cxt = NULL;
4907  afterTriggers.events.head = NULL;
4908  afterTriggers.events.tail = NULL;
4909  afterTriggers.events.tailfree = NULL;
4910  }
4911 
4912  /*
4913  * Forget any subtransaction state as well. Since this can't be very
4914  * large, we let the eventual reset of TopTransactionContext free the
4915  * memory instead of doing it here.
4916  */
4917  afterTriggers.trans_stack = NULL;
4919 
4920 
4921  /*
4922  * Forget the query stack and constraint-related state information. As
4923  * with the subtransaction state information, we don't bother freeing the
4924  * memory here.
4925  */
4926  afterTriggers.query_stack = NULL;
4928  afterTriggers.state = NULL;
4929 
4930  /* No more afterTriggers manipulation until next transaction starts. */
4932 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
AfterTriggersTransData * trans_stack
Definition: trigger.c:3645
AfterTriggersQueryData * query_stack
Definition: trigger.c:3640
AfterTriggerEventChunk * tail
Definition: trigger.c:3529
SetConstraintState state
Definition: trigger.c:3635
AfterTriggerEventChunk * head
Definition: trigger.c:3528
MemoryContext event_cxt
Definition: trigger.c:3637
AfterTriggerEventList events
Definition: trigger.c:3636
static AfterTriggersData afterTriggers
Definition: trigger.c:3679

◆ AfterTriggerFireDeferred()

void AfterTriggerFireDeferred ( void  )

Definition at line 4836 of file trigger.c.

References afterTriggerInvokeEvents(), afterTriggerMarkEvents(), Assert, AfterTriggersData::events, AfterTriggersData::firing_counter, GetTransactionSnapshot(), AfterTriggerEventList::head, PopActiveSnapshot(), PushActiveSnapshot(), and AfterTriggersData::query_depth.

Referenced by CommitTransaction(), and PrepareTransaction().

4837 {
4838  AfterTriggerEventList *events;
4839  bool snap_pushed = false;
4840 
4841  /* Must not be inside a query */
4843 
4844  /*
4845  * If there are any triggers to fire, make sure we have set a snapshot for
4846  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
4847  * can't assume ActiveSnapshot is valid on entry.)
4848  */
4849  events = &afterTriggers.events;
4850  if (events->head != NULL)
4851  {
4853  snap_pushed = true;
4854  }
4855 
4856  /*
4857  * Run all the remaining triggers. Loop until they are all gone, in case
4858  * some trigger queues more for us to do.
4859  */
4860  while (afterTriggerMarkEvents(events, NULL, false))
4861  {
4862  CommandId firing_id = afterTriggers.firing_counter++;
4863 
4864  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
4865  break; /* all fired */
4866  }
4867 
4868  /*
4869  * We don't bother freeing the event list, since it will go away anyway
4870  * (and more efficiently than via pfree) in AfterTriggerEndXact.
4871  */
4872 
4873  if (snap_pushed)
4875 }
uint32 CommandId
Definition: c.h:601
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4318
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
CommandId firing_counter
Definition: trigger.c:3634
#define Assert(condition)
Definition: c.h:804
AfterTriggerEventChunk * head
Definition: trigger.c:3528
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4234
AfterTriggerEventList events
Definition: trigger.c:3636
static AfterTriggersData afterTriggers
Definition: trigger.c:3679

◆ AfterTriggerPendingOnRel()

bool AfterTriggerPendingOnRel ( Oid  relid)

Definition at line 5527 of file trigger.c.

References AFTER_TRIGGER_DONE, AfterTriggerEventData::ate_flags, AfterTriggerSharedData::ats_relid, AfterTriggersData::events, AfterTriggersQueryData::events, for_each_event_chunk, GetTriggerSharedData, AfterTriggersData::maxquerydepth, AfterTriggersData::query_depth, and AfterTriggersData::query_stack.

Referenced by CheckTableNotInUse().

5528 {
5529  AfterTriggerEvent event;
5530  AfterTriggerEventChunk *chunk;
5531  int depth;
5532 
5533  /* Scan queued events */
5535  {
5536  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5537 
5538  /*
5539  * We can ignore completed events. (Even if a DONE flag is rolled
5540  * back by subxact abort, it's OK because the effects of the TRUNCATE
5541  * or whatever must get rolled back too.)
5542  */
5543  if (event->ate_flags & AFTER_TRIGGER_DONE)
5544  continue;
5545 
5546  if (evtshared->ats_relid == relid)
5547  return true;
5548  }
5549 
5550  /*
5551  * Also scan events queued by incomplete queries. This could only matter
5552  * if TRUNCATE/etc is executed by a function or trigger within an updating
5553  * query on the same relation, which is pretty perverse, but let's check.
5554  */
5555  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
5556  {
5558  {
5559  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5560 
5561  if (event->ate_flags & AFTER_TRIGGER_DONE)
5562  continue;
5563 
5564  if (evtshared->ats_relid == relid)
5565  return true;
5566  }
5567  }
5568 
5569  return false;
5570 }
TriggerFlags ate_flags
Definition: trigger.c:3479
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3454
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3541
AfterTriggersQueryData * query_stack
Definition: trigger.c:3640
#define GetTriggerSharedData(evt)
Definition: trigger.c:3504
AfterTriggerEventList events
Definition: trigger.c:3636
AfterTriggerEventList events
Definition: trigger.c:3651
static AfterTriggersData afterTriggers
Definition: trigger.c:3679

◆ AfterTriggerSetState()

void AfterTriggerSetState ( ConstraintsSetStmt stmt)

Definition at line 5212 of file trigger.c.

References AccessShareLock, afterTriggerInvokeEvents(), afterTriggerMarkEvents(), SetConstraintStateData::all_isdeferred, SetConstraintStateData::all_isset, BTEqualStrategyNumber, RangeVar::catalogname, ConstraintsSetStmt::constraints, CStringGetDatum, ConstraintsSetStmt::deferred, ereport, errcode(), errmsg(), ERROR, AfterTriggersData::events, fetch_search_path(), AfterTriggersData::firing_counter, get_database_name(), GetCurrentTransactionNestLevel(), GETSTRUCT, GetTransactionSnapshot(), HeapTupleIsValid, i, IsSubTransaction(), sort-test::key, lappend_oid(), lfirst, lfirst_oid, list_free(), list_make1_oid, LookupExplicitNamespace(), MyDatabaseId, NIL, SetConstraintStateData::numstates, ObjectIdGetDatum, PopActiveSnapshot(), PushActiveSnapshot(), RangeVar::relname, ScanKeyInit(), RangeVar::schemaname, SetConstraintTriggerData::sct_tgisdeferred, SetConstraintTriggerData::sct_tgoid, SetConstraintStateAddItem(), SetConstraintStateCopy(), SetConstraintStateCreate(), AfterTriggersData::state, AfterTriggersTransData::state, systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), AfterTriggersData::trans_stack, and SetConstraintStateData::trigstates.

Referenced by standard_ProcessUtility().

5213 {
5214  int my_level = GetCurrentTransactionNestLevel();
5215 
5216  /* If we haven't already done so, initialize our state. */
5217  if (afterTriggers.state == NULL)
5219 
5220  /*
5221  * If in a subtransaction, and we didn't save the current state already,
5222  * save it so it can be restored if the subtransaction aborts.
5223  */
5224  if (my_level > 1 &&
5225  afterTriggers.trans_stack[my_level].state == NULL)
5226  {
5227  afterTriggers.trans_stack[my_level].state =
5229  }
5230 
5231  /*
5232  * Handle SET CONSTRAINTS ALL ...
5233  */
5234  if (stmt->constraints == NIL)
5235  {
5236  /*
5237  * Forget any previous SET CONSTRAINTS commands in this transaction.
5238  */
5240 
5241  /*
5242  * Set the per-transaction ALL state to known.
5243  */
5244  afterTriggers.state->all_isset = true;
5246  }
5247  else
5248  {
5249  Relation conrel;
5250  Relation tgrel;
5251  List *conoidlist = NIL;
5252  List *tgoidlist = NIL;
5253  ListCell *lc;
5254 
5255  /*
5256  * Handle SET CONSTRAINTS constraint-name [, ...]
5257  *
5258  * First, identify all the named constraints and make a list of their
5259  * OIDs. Since, unlike the SQL spec, we allow multiple constraints of
5260  * the same name within a schema, the specifications are not
5261  * necessarily unique. Our strategy is to target all matching
5262  * constraints within the first search-path schema that has any
5263  * matches, but disregard matches in schemas beyond the first match.
5264  * (This is a bit odd but it's the historical behavior.)
5265  *
5266  * A constraint in a partitioned table may have corresponding
5267  * constraints in the partitions. Grab those too.
5268  */
5269  conrel = table_open(ConstraintRelationId, AccessShareLock);
5270 
5271  foreach(lc, stmt->constraints)
5272  {
5273  RangeVar *constraint = lfirst(lc);
5274  bool found;
5275  List *namespacelist;
5276  ListCell *nslc;
5277 
5278  if (constraint->catalogname)
5279  {
5280  if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
5281  ereport(ERROR,
5282  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5283  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
5284  constraint->catalogname, constraint->schemaname,
5285  constraint->relname)));
5286  }
5287 
5288  /*
5289  * If we're given the schema name with the constraint, look only
5290  * in that schema. If given a bare constraint name, use the
5291  * search path to find the first matching constraint.
5292  */
5293  if (constraint->schemaname)
5294  {
5295  Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
5296  false);
5297 
5298  namespacelist = list_make1_oid(namespaceId);
5299  }
5300  else
5301  {
5302  namespacelist = fetch_search_path(true);
5303  }
5304 
5305  found = false;
5306  foreach(nslc, namespacelist)
5307  {
5308  Oid namespaceId = lfirst_oid(nslc);
5309  SysScanDesc conscan;
5310  ScanKeyData skey[2];
5311  HeapTuple tup;
5312 
5313  ScanKeyInit(&skey[0],
5314  Anum_pg_constraint_conname,
5315  BTEqualStrategyNumber, F_NAMEEQ,
5316  CStringGetDatum(constraint->relname));
5317  ScanKeyInit(&skey[1],
5318  Anum_pg_constraint_connamespace,
5319  BTEqualStrategyNumber, F_OIDEQ,
5320  ObjectIdGetDatum(namespaceId));
5321 
5322  conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
5323  true, NULL, 2, skey);
5324 
5325  while (HeapTupleIsValid(tup = systable_getnext(conscan)))
5326  {
5328 
5329  if (con->condeferrable)
5330  conoidlist = lappend_oid(conoidlist, con->oid);
5331  else if (stmt->deferred)
5332  ereport(ERROR,
5333  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5334  errmsg("constraint \"%s\" is not deferrable",
5335  constraint->relname)));
5336  found = true;
5337  }
5338 
5339  systable_endscan(conscan);
5340 
5341  /*
5342  * Once we've found a matching constraint we do not search
5343  * later parts of the search path.
5344  */
5345  if (found)
5346  break;
5347  }
5348 
5349  list_free(namespacelist);
5350 
5351  /*
5352  * Not found ?
5353  */
5354  if (!found)
5355  ereport(ERROR,
5356  (errcode(ERRCODE_UNDEFINED_OBJECT),
5357  errmsg("constraint \"%s\" does not exist",
5358  constraint->relname)));
5359  }
5360 
5361  /*
5362  * Scan for any possible descendants of the constraints. We append
5363  * whatever we find to the same list that we're scanning; this has the
5364  * effect that we create new scans for those, too, so if there are
5365  * further descendents, we'll also catch them.
5366  */
5367  foreach(lc, conoidlist)
5368  {
5369  Oid parent = lfirst_oid(lc);
5370  ScanKeyData key;
5371  SysScanDesc scan;
5372  HeapTuple tuple;
5373 
5374  ScanKeyInit(&key,
5375  Anum_pg_constraint_conparentid,
5376  BTEqualStrategyNumber, F_OIDEQ,
5377  ObjectIdGetDatum(parent));
5378 
5379  scan = systable_beginscan(conrel, ConstraintParentIndexId, true, NULL, 1, &key);
5380 
5381  while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5382  {
5384 
5385  conoidlist = lappend_oid(conoidlist, con->oid);
5386  }
5387 
5388  systable_endscan(scan);
5389  }
5390 
5391  table_close(conrel, AccessShareLock);
5392 
5393  /*
5394  * Now, locate the trigger(s) implementing each of these constraints,
5395  * and make a list of their OIDs.
5396  */
5397  tgrel = table_open(TriggerRelationId, AccessShareLock);
5398 
5399  foreach(lc, conoidlist)
5400  {
5401  Oid conoid = lfirst_oid(lc);
5402  ScanKeyData skey;
5403  SysScanDesc tgscan;
5404  HeapTuple htup;
5405 
5406  ScanKeyInit(&skey,
5407  Anum_pg_trigger_tgconstraint,
5408  BTEqualStrategyNumber, F_OIDEQ,
5409  ObjectIdGetDatum(conoid));
5410 
5411  tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
5412  NULL, 1, &skey);
5413 
5414  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
5415  {
5416  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
5417 
5418  /*
5419  * Silently skip triggers that are marked as non-deferrable in
5420  * pg_trigger. This is not an error condition, since a
5421  * deferrable RI constraint may have some non-deferrable
5422  * actions.
5423  */
5424  if (pg_trigger->tgdeferrable)
5425  tgoidlist = lappend_oid(tgoidlist, pg_trigger->oid);
5426  }
5427 
5428  systable_endscan(tgscan);
5429  }
5430 
5431  table_close(tgrel, AccessShareLock);
5432 
5433  /*
5434  * Now we can set the trigger states of individual triggers for this
5435  * xact.
5436  */
5437  foreach(lc, tgoidlist)
5438  {
5439  Oid tgoid = lfirst_oid(lc);
5441  bool found = false;
5442  int i;
5443 
5444  for (i = 0; i < state->numstates; i++)
5445  {
5446  if (state->trigstates[i].sct_tgoid == tgoid)
5447  {
5448  state->trigstates[i].sct_tgisdeferred = stmt->deferred;
5449  found = true;
5450  break;
5451  }
5452  }
5453  if (!found)
5454  {
5456  SetConstraintStateAddItem(state, tgoid, stmt->deferred);
5457  }
5458  }
5459  }
5460 
5461  /*
5462  * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
5463  * checks against that constraint must be made when the SET CONSTRAINTS
5464  * command is executed -- i.e. the effects of the SET CONSTRAINTS command
5465  * apply retroactively. We've updated the constraints state, so scan the
5466  * list of previously deferred events to fire any that have now become
5467  * immediate.
5468  *
5469  * Obviously, if this was SET ... DEFERRED then it can't have converted
5470  * any unfired events to immediate, so we need do nothing in that case.
5471  */
5472  if (!stmt->deferred)
5473  {
5475  bool snapshot_set = false;
5476 
5477  while (afterTriggerMarkEvents(events, NULL, true))
5478  {
5479  CommandId firing_id = afterTriggers.firing_counter++;
5480 
5481  /*
5482  * Make sure a snapshot has been established in case trigger
5483  * functions need one. Note that we avoid setting a snapshot if
5484  * we don't find at least one trigger that has to be fired now.
5485  * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
5486  * ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
5487  * at the start of a transaction it's not possible for any trigger
5488  * events to be queued yet.)
5489  */
5490  if (!snapshot_set)
5491  {
5493  snapshot_set = true;
5494  }
5495 
5496  /*
5497  * We can delete fired events if we are at top transaction level,
5498  * but we'd better not if inside a subtransaction, since the
5499  * subtransaction could later get rolled back.
5500  */
5501  if (afterTriggerInvokeEvents(events, firing_id, NULL,
5502  !IsSubTransaction()))
5503  break; /* all fired */
5504  }
5505 
5506  if (snapshot_set)
5508  }
5509 }
#define NIL
Definition: pg_list.h:65
uint32 CommandId
Definition: c.h:601
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2938
AfterTriggersTransData * trans_stack
Definition: trigger.c:3645
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
SetConstraintTriggerData trigstates[FLEXIBLE_ARRAY_MEMBER]
Definition: trigger.c:3408
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
static SetConstraintState SetConstraintStateAddItem(SetConstraintState state, Oid tgoid, bool tgisdeferred)
Definition: trigger.c:5182
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4318
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
char * schemaname
Definition: primnodes.h:67
char * relname
Definition: primnodes.h:68
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
SetConstraintState state
Definition: trigger.c:3635
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2113
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define CStringGetDatum(X)
Definition: postgres.h:622
static SetConstraintState SetConstraintStateCreate(int numalloc)
Definition: trigger.c:5137
#define list_make1_oid(x1)
Definition: pg_list.h:236
Oid MyDatabaseId
Definition: globals.c:88
CommandId firing_counter
Definition: trigger.c:3634
#define ereport(elevel,...)
Definition: elog.h:157
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:169
Definition: regguts.h:317
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
bool IsSubTransaction(void)
Definition: xact.c:4756
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
int i
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4234
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
AfterTriggerEventList events
Definition: trigger.c:3636
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
List * fetch_search_path(bool includeImplicit)
Definition: namespace.c:4428
static AfterTriggersData afterTriggers
Definition: trigger.c:3679
char * catalogname
Definition: primnodes.h:66
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:171
SetConstraintState state
Definition: trigger.c:3659
static SetConstraintState SetConstraintStateCopy(SetConstraintState state)
Definition: trigger.c:5162

◆ CopyTriggerDesc()

TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 2014 of file trigger.c.

References i, TriggerDesc::numtriggers, palloc(), pstrdup(), Trigger::tgargs, Trigger::tgattr, Trigger::tgname, Trigger::tgnargs, Trigger::tgnattr, Trigger::tgnewtable, Trigger::tgoldtable, Trigger::tgqual, and TriggerDesc::triggers.

Referenced by InitResultRelInfo(), and RelationBuildTriggers().

2015 {
2016  TriggerDesc *newdesc;
2017  Trigger *trigger;
2018  int i;
2019 
2020  if (trigdesc == NULL || trigdesc->numtriggers <= 0)
2021  return NULL;
2022 
2023  newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
2024  memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
2025 
2026  trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
2027  memcpy(trigger, trigdesc->triggers,
2028  trigdesc->numtriggers * sizeof(Trigger));
2029  newdesc->triggers = trigger;
2030 
2031  for (i = 0; i < trigdesc->numtriggers; i++)
2032  {
2033  trigger->tgname = pstrdup(trigger->tgname);
2034  if (trigger->tgnattr > 0)
2035  {
2036  int16 *newattr;
2037 
2038  newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
2039  memcpy(newattr, trigger->tgattr,
2040  trigger->tgnattr * sizeof(int16));
2041  trigger->tgattr = newattr;
2042  }
2043  if (trigger->tgnargs > 0)
2044  {
2045  char **newargs;
2046  int16 j;
2047 
2048  newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
2049  for (j = 0; j < trigger->tgnargs; j++)
2050  newargs[j] = pstrdup(trigger->tgargs[j]);
2051  trigger->tgargs = newargs;
2052  }
2053  if (trigger->tgqual)
2054  trigger->tgqual = pstrdup(trigger->tgqual);
2055  if (trigger->tgoldtable)
2056  trigger->tgoldtable = pstrdup(trigger->tgoldtable);
2057  if (trigger->tgnewtable)
2058  trigger->tgnewtable = pstrdup(trigger->tgnewtable);
2059  trigger++;
2060  }
2061 
2062  return newdesc;
2063 }
signed short int16
Definition: c.h:428
char * pstrdup(const char *in)
Definition: mcxt.c:1299
char * tgqual
Definition: reltrigger.h:42
char * tgname
Definition: reltrigger.h:27
Trigger * triggers
Definition: reltrigger.h:49
int numtriggers
Definition: reltrigger.h:50
char ** tgargs
Definition: reltrigger.h:41
int16 * tgattr
Definition: reltrigger.h:40
char * tgnewtable
Definition: reltrigger.h:44
int16 tgnattr
Definition: reltrigger.h:39
void * palloc(Size size)
Definition: mcxt.c:1062
int i
int16 tgnargs
Definition: reltrigger.h:38
char * tgoldtable
Definition: reltrigger.h:43

◆ CreateTrigger()

ObjectAddress CreateTrigger ( CreateTrigStmt stmt,
const char *  queryString,
Oid  relOid,
Oid  refRelOid,
Oid  constraintOid,
Oid  indexOid,
Oid  funcoid,
Oid  parentTriggerOid,
Node whenClause,
bool  isInternal,
bool  in_partition 
)

Definition at line 156 of file trigger.c.

References CreateTriggerFiringOn(), and TRIGGER_FIRES_ON_ORIGIN.

Referenced by CreateFKCheckTrigger(), createForeignKeyActionTriggers(), index_constraint_create(), and ProcessUtilitySlow().

160 {
161  return
162  CreateTriggerFiringOn(stmt, queryString, relOid, refRelOid,
163  constraintOid, indexOid, funcoid,
164  parentTriggerOid, whenClause, isInternal,
165  in_partition, TRIGGER_FIRES_ON_ORIGIN);
166 }
ObjectAddress CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition, char trigger_fires_when)
Definition: trigger.c:173
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:148

◆ CreateTriggerFiringOn()

ObjectAddress CreateTriggerFiringOn ( CreateTrigStmt stmt,
const char *  queryString,
Oid  relOid,
Oid  refRelOid,
Oid  constraintOid,
Oid  indexOid,
Oid  funcoid,
Oid  parentTriggerOid,
Node whenClause,
bool  isInternal,
bool  in_partition,
char  trigger_fires_when 
)

Definition at line 173 of file trigger.c.

References AccessShareLock, ACL_EXECUTE, ACL_TRIGGER, aclcheck_error(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate, allowSystemTableMods, generate_unaccent_rules::args, CreateTrigStmt::args, Assert, assign_expr_collations(), attnameAttNum(), attnum, BoolGetDatum, BTEqualStrategyNumber, buildint2vector(), byteain(), CacheInvalidateRelcacheByTuple(), CatalogTupleInsert(), CatalogTupleUpdate(), ObjectAddress::classId, CreateTrigStmt::columns, CommandCounterIncrement(), CreateTrigStmt::constrrel, copyObject, CreateConstraintEntry(), CreateTriggerFiringOn(), CStringGetDatum, CStringGetTextDatum, CurrentMemoryContext, DatumGetPointer, CreateTrigStmt::deferrable, deleteDependencyRecordsFor(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, DEPENDENCY_NORMAL, DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, DirectFunctionCall1, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errdetail_relkind_not_supported(), errhint(), errmsg(), ERROR, CreateTrigStmt::events, EXPR_KIND_TRIGGER_WHEN, find_all_inheritors(), find_inheritance_children(), forboth, free_parsestate(), CreateTrigStmt::funcname, get_func_rettype(), get_rel_name(), get_rel_relkind(), get_relkind_objtype(), GetNewOidWithIndex(), GETSTRUCT, GetUserId(), has_superclass(), heap_copytuple(), heap_form_tuple(), heap_freetuple(), HeapTupleIsValid, i, IndexGetRelation(), CreateTrigStmt::initdeferred, Int16GetDatum, InvalidAttrNumber, InvalidOid, InvokeObjectPostCreateHookArg, CreateTrigStmt::isconstraint, TriggerTransition::isNew, IsSystemRelation(), TriggerTransition::isTable, lappend_oid(), lfirst, lfirst_node, lfirst_oid, list_free(), list_length(), Var::location, LockRelationOid(), LookupFuncName(), make_parsestate(), makeAlias(), map_partition_varattnos(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), name, TriggerTransition::name, NAMEDATALEN, namein(), NameListToString(), NameStr, NIL, nodeToString(), NoLock, PartitionDescData::nparts, OBJECT_FUNCTION, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, PartitionDescData::oids, ParseState::p_rtable, ParseState::p_sourcetext, palloc(), parser_errposition(), pfree(), pg_class_aclcheck(), pg_proc_aclcheck(), PointerGetDatum, PRS2_NEW_VARNO, PRS2_OLD_VARNO, pull_var_clause(), RangeVarGetRelid, RelationData::rd_att, RelationData::rd_id, RelationData::rd_rel, recordDependencyOn(), recordDependencyOnExpr(), CreateTrigStmt::relation, RelationGetDescr, RelationGetNamespace, RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, RELOID, CreateTrigStmt::replace, CreateTrigStmt::row, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, ShareRowExclusiveLock, snprintf, strVal, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), table_openrv(), CreateTrigStmt::timing, transformWhereClause(), CreateTrigStmt::transitionRels, CreateTrigStmt::trigname, TupleDescAttr, values, Var::varattno, Var::varno, and CreateTrigStmt::whenClause.

Referenced by CloneRowTriggersToPartition(), CreateTrigger(), and CreateTriggerFiringOn().

178 {
179  int16 tgtype;
180  int ncolumns;
181  int16 *columns;
182  int2vector *tgattr;
183  List *whenRtable;
184  char *qual;
185  Datum values[Natts_pg_trigger];
186  bool nulls[Natts_pg_trigger];
187  Relation rel;
188  AclResult aclresult;
189  Relation tgrel;
190  Relation pgrel;
191  HeapTuple tuple = NULL;
192  Oid funcrettype;
193  Oid trigoid = InvalidOid;
194  char internaltrigname[NAMEDATALEN];
195  char *trigname;
196  Oid constrrelid = InvalidOid;
197  ObjectAddress myself,
198  referenced;
199  char *oldtablename = NULL;
200  char *newtablename = NULL;
201  bool partition_recurse;
202  bool trigger_exists = false;
203  Oid existing_constraint_oid = InvalidOid;
204  bool existing_isInternal = false;
205 
206  if (OidIsValid(relOid))
207  rel = table_open(relOid, ShareRowExclusiveLock);
208  else
210 
211  /*
212  * Triggers must be on tables or views, and there are additional
213  * relation-type-specific restrictions.
214  */
215  if (rel->rd_rel->relkind == RELKIND_RELATION)
216  {
217  /* Tables can't have INSTEAD OF triggers */
218  if (stmt->timing != TRIGGER_TYPE_BEFORE &&
219  stmt->timing != TRIGGER_TYPE_AFTER)
220  ereport(ERROR,
221  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
222  errmsg("\"%s\" is a table",
224  errdetail("Tables cannot have INSTEAD OF triggers.")));
225  }
226  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
227  {
228  /* Partitioned tables can't have INSTEAD OF triggers */
229  if (stmt->timing != TRIGGER_TYPE_BEFORE &&
230  stmt->timing != TRIGGER_TYPE_AFTER)
231  ereport(ERROR,
232  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
233  errmsg("\"%s\" is a table",
235  errdetail("Tables cannot have INSTEAD OF triggers.")));
236 
237  /*
238  * FOR EACH ROW triggers have further restrictions
239  */
240  if (stmt->row)
241  {
242  /*
243  * Disallow use of transition tables.
244  *
245  * Note that we have another restriction about transition tables
246  * in partitions; search for 'has_superclass' below for an
247  * explanation. The check here is just to protect from the fact
248  * that if we allowed it here, the creation would succeed for a
249  * partitioned table with no partitions, but would be blocked by
250  * the other restriction when the first partition was created,
251  * which is very unfriendly behavior.
252  */
253  if (stmt->transitionRels != NIL)
254  ereport(ERROR,
255  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
256  errmsg("\"%s\" is a partitioned table",
258  errdetail("Triggers on partitioned tables cannot have transition tables.")));
259  }
260  }
261  else if (rel->rd_rel->relkind == RELKIND_VIEW)
262  {
263  /*
264  * Views can have INSTEAD OF triggers (which we check below are
265  * row-level), or statement-level BEFORE/AFTER triggers.
266  */
267  if (stmt->timing != TRIGGER_TYPE_INSTEAD && stmt->row)
268  ereport(ERROR,
269  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
270  errmsg("\"%s\" is a view",
272  errdetail("Views cannot have row-level BEFORE or AFTER triggers.")));
273  /* Disallow TRUNCATE triggers on VIEWs */
274  if (TRIGGER_FOR_TRUNCATE(stmt->events))
275  ereport(ERROR,
276  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
277  errmsg("\"%s\" is a view",
279  errdetail("Views cannot have TRUNCATE triggers.")));
280  }
281  else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
282  {
283  if (stmt->timing != TRIGGER_TYPE_BEFORE &&
284  stmt->timing != TRIGGER_TYPE_AFTER)
285  ereport(ERROR,
286  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
287  errmsg("\"%s\" is a foreign table",
289  errdetail("Foreign tables cannot have INSTEAD OF triggers.")));
290 
291  if (TRIGGER_FOR_TRUNCATE(stmt->events))
292  ereport(ERROR,
293  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
294  errmsg("\"%s\" is a foreign table",
296  errdetail("Foreign tables cannot have TRUNCATE triggers.")));
297 
298  /*
299  * We disallow constraint triggers to protect the assumption that
300  * triggers on FKs can't be deferred. See notes with AfterTriggers
301  * data structures, below.
302  */
303  if (stmt->isconstraint)
304  ereport(ERROR,
305  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
306  errmsg("\"%s\" is a foreign table",
308  errdetail("Foreign tables cannot have constraint triggers.")));
309  }
310  else
311  ereport(ERROR,
312  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
313  errmsg("relation \"%s\" cannot have triggers",
315  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
316 
318  ereport(ERROR,
319  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
320  errmsg("permission denied: \"%s\" is a system catalog",
321  RelationGetRelationName(rel))));
322 
323  if (stmt->isconstraint)
324  {
325  /*
326  * We must take a lock on the target relation to protect against
327  * concurrent drop. It's not clear that AccessShareLock is strong
328  * enough, but we certainly need at least that much... otherwise, we
329  * might end up creating a pg_constraint entry referencing a
330  * nonexistent table.
331  */
332  if (OidIsValid(refRelOid))
333  {
334  LockRelationOid(refRelOid, AccessShareLock);
335  constrrelid = refRelOid;
336  }
337  else if (stmt->constrrel != NULL)
338  constrrelid = RangeVarGetRelid(stmt->constrrel, AccessShareLock,
339  false);
340  }
341 
342  /* permission checks */
343  if (!isInternal)
344  {
345  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
346  ACL_TRIGGER);
347  if (aclresult != ACLCHECK_OK)
348  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
350 
351  if (OidIsValid(constrrelid))
352  {
353  aclresult = pg_class_aclcheck(constrrelid, GetUserId(),
354  ACL_TRIGGER);
355  if (aclresult != ACLCHECK_OK)
356  aclcheck_error(aclresult, get_relkind_objtype(get_rel_relkind(constrrelid)),
357  get_rel_name(constrrelid));
358  }
359  }
360 
361  /*
362  * When called on a partitioned table to create a FOR EACH ROW trigger
363  * that's not internal, we create one trigger for each partition, too.
364  *
365  * For that, we'd better hold lock on all of them ahead of time.
366  */
367  partition_recurse = !isInternal && stmt->row &&
368  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
369  if (partition_recurse)
371  ShareRowExclusiveLock, NULL));
372 
373  /* Compute tgtype */
374  TRIGGER_CLEAR_TYPE(tgtype);
375  if (stmt->row)
376  TRIGGER_SETT_ROW(tgtype);
377  tgtype |= stmt->timing;
378  tgtype |= stmt->events;
379 
380  /* Disallow ROW-level TRUNCATE triggers */
381  if (TRIGGER_FOR_ROW(tgtype) && TRIGGER_FOR_TRUNCATE(tgtype))
382  ereport(ERROR,
383  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
384  errmsg("TRUNCATE FOR EACH ROW triggers are not supported")));
385 
386  /* INSTEAD triggers must be row-level, and can't have WHEN or columns */
387  if (TRIGGER_FOR_INSTEAD(tgtype))
388  {
389  if (!TRIGGER_FOR_ROW(tgtype))
390  ereport(ERROR,
391  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
392  errmsg("INSTEAD OF triggers must be FOR EACH ROW")));
393  if (stmt->whenClause)
394  ereport(ERROR,
395  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
396  errmsg("INSTEAD OF triggers cannot have WHEN conditions")));
397  if (stmt->columns != NIL)
398  ereport(ERROR,
399  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
400  errmsg("INSTEAD OF triggers cannot have column lists")));
401  }
402 
403  /*
404  * We don't yet support naming ROW transition variables, but the parser
405  * recognizes the syntax so we can give a nicer message here.
406  *
407  * Per standard, REFERENCING TABLE names are only allowed on AFTER
408  * triggers. Per standard, REFERENCING ROW names are not allowed with FOR
409  * EACH STATEMENT. Per standard, each OLD/NEW, ROW/TABLE permutation is
410  * only allowed once. Per standard, OLD may not be specified when
411  * creating a trigger only for INSERT, and NEW may not be specified when
412  * creating a trigger only for DELETE.
413  *
414  * Notice that the standard allows an AFTER ... FOR EACH ROW trigger to
415  * reference both ROW and TABLE transition data.
416  */
417  if (stmt->transitionRels != NIL)
418  {
419  List *varList = stmt->transitionRels;
420  ListCell *lc;
421 
422  foreach(lc, varList)
423  {
425 
426  if (!(tt->isTable))
427  ereport(ERROR,
428  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
429  errmsg("ROW variable naming in the REFERENCING clause is not supported"),
430  errhint("Use OLD TABLE or NEW TABLE for naming transition tables.")));
431 
432  /*
433  * Because of the above test, we omit further ROW-related testing
434  * below. If we later allow naming OLD and NEW ROW variables,
435  * adjustments will be needed below.
436  */
437 
438  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
439  ereport(ERROR,
440  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
441  errmsg("\"%s\" is a foreign table",
443  errdetail("Triggers on foreign tables cannot have transition tables.")));
444 
445  if (rel->rd_rel->relkind == RELKIND_VIEW)
446  ereport(ERROR,
447  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
448  errmsg("\"%s\" is a view",
450  errdetail("Triggers on views cannot have transition tables.")));
451 
452  /*
453  * We currently don't allow row-level triggers with transition
454  * tables on partition or inheritance children. Such triggers
455  * would somehow need to see tuples converted to the format of the
456  * table they're attached to, and it's not clear which subset of
457  * tuples each child should see. See also the prohibitions in
458  * ATExecAttachPartition() and ATExecAddInherit().
459  */
460  if (TRIGGER_FOR_ROW(tgtype) && has_superclass(rel->rd_id))
461  {
462  /* Use appropriate error message. */
463  if (rel->rd_rel->relispartition)
464  ereport(ERROR,
465  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
466  errmsg("ROW triggers with transition tables are not supported on partitions")));
467  else
468  ereport(ERROR,
469  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
470  errmsg("ROW triggers with transition tables are not supported on inheritance children")));
471  }
472 
473  if (stmt->timing != TRIGGER_TYPE_AFTER)
474  ereport(ERROR,
475  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
476  errmsg("transition table name can only be specified for an AFTER trigger")));
477 
478  if (TRIGGER_FOR_TRUNCATE(tgtype))
479  ereport(ERROR,
480  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
481  errmsg("TRUNCATE triggers with transition tables are not supported")));
482 
483  /*
484  * We currently don't allow multi-event triggers ("INSERT OR
485  * UPDATE") with transition tables, because it's not clear how to
486  * handle INSERT ... ON CONFLICT statements which can fire both
487  * INSERT and UPDATE triggers. We show the inserted tuples to
488  * INSERT triggers and the updated tuples to UPDATE triggers, but
489  * it's not yet clear what INSERT OR UPDATE trigger should see.
490  * This restriction could be lifted if we can decide on the right
491  * semantics in a later release.
492  */
493  if (((TRIGGER_FOR_INSERT(tgtype) ? 1 : 0) +
494  (TRIGGER_FOR_UPDATE(tgtype) ? 1 : 0) +
495  (TRIGGER_FOR_DELETE(tgtype) ? 1 : 0)) != 1)
496  ereport(ERROR,
497  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
498  errmsg("transition tables cannot be specified for triggers with more than one event")));
499 
500  /*
501  * We currently don't allow column-specific triggers with
502  * transition tables. Per spec, that seems to require
503  * accumulating separate transition tables for each combination of
504  * columns, which is a lot of work for a rather marginal feature.
505  */
506  if (stmt->columns != NIL)
507  ereport(ERROR,
508  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
509  errmsg("transition tables cannot be specified for triggers with column lists")));
510 
511  /*
512  * We disallow constraint triggers with transition tables, to
513  * protect the assumption that such triggers can't be deferred.
514  * See notes with AfterTriggers data structures, below.
515  *
516  * Currently this is enforced by the grammar, so just Assert here.
517  */
518  Assert(!stmt->isconstraint);
519 
520  if (tt->isNew)
521  {
522  if (!(TRIGGER_FOR_INSERT(tgtype) ||
523  TRIGGER_FOR_UPDATE(tgtype)))
524  ereport(ERROR,
525  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
526  errmsg("NEW TABLE can only be specified for an INSERT or UPDATE trigger")));
527 
528  if (newtablename != NULL)
529  ereport(ERROR,
530  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
531  errmsg("NEW TABLE cannot be specified multiple times")));
532 
533  newtablename = tt->name;
534  }
535  else
536  {
537  if (!(TRIGGER_FOR_DELETE(tgtype) ||
538  TRIGGER_FOR_UPDATE(tgtype)))
539  ereport(ERROR,
540  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
541  errmsg("OLD TABLE can only be specified for a DELETE or UPDATE trigger")));
542 
543  if (oldtablename != NULL)
544  ereport(ERROR,
545  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
546  errmsg("OLD TABLE cannot be specified multiple times")));
547 
548  oldtablename = tt->name;
549  }
550  }
551 
552  if (newtablename != NULL && oldtablename != NULL &&
553  strcmp(newtablename, oldtablename) == 0)
554  ereport(ERROR,
555  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
556  errmsg("OLD TABLE name and NEW TABLE name cannot be the same")));
557  }
558 
559  /*
560  * Parse the WHEN clause, if any and we weren't passed an already
561  * transformed one.
562  *
563  * Note that as a side effect, we fill whenRtable when parsing. If we got
564  * an already parsed clause, this does not occur, which is what we want --
565  * no point in adding redundant dependencies below.
566  */
567  if (!whenClause && stmt->whenClause)
568  {
569  ParseState *pstate;
570  ParseNamespaceItem *nsitem;
571  List *varList;
572  ListCell *lc;
573 
574  /* Set up a pstate to parse with */
575  pstate = make_parsestate(NULL);
576  pstate->p_sourcetext = queryString;
577 
578  /*
579  * Set up nsitems for OLD and NEW references.
580  *
581  * 'OLD' must always have varno equal to 1 and 'NEW' equal to 2.
582  */
583  nsitem = addRangeTableEntryForRelation(pstate, rel,
585  makeAlias("old", NIL),
586  false, false);
587  addNSItemToQuery(pstate, nsitem, false, true, true);
588  nsitem = addRangeTableEntryForRelation(pstate, rel,
590  makeAlias("new", NIL),
591  false, false);
592  addNSItemToQuery(pstate, nsitem, false, true, true);
593 
594  /* Transform expression. Copy to be sure we don't modify original */
595  whenClause = transformWhereClause(pstate,
596  copyObject(stmt->whenClause),
598  "WHEN");
599  /* we have to fix its collations too */
600  assign_expr_collations(pstate, whenClause);
601 
602  /*
603  * Check for disallowed references to OLD/NEW.
604  *
605  * NB: pull_var_clause is okay here only because we don't allow
606  * subselects in WHEN clauses; it would fail to examine the contents
607  * of subselects.
608  */
609  varList = pull_var_clause(whenClause, 0);
610  foreach(lc, varList)
611  {
612  Var *var = (Var *) lfirst(lc);
613 
614  switch (var->varno)
615  {
616  case PRS2_OLD_VARNO:
617  if (!TRIGGER_FOR_ROW(tgtype))
618  ereport(ERROR,
619  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
620  errmsg("statement trigger's WHEN condition cannot reference column values"),
621  parser_errposition(pstate, var->location)));
622  if (TRIGGER_FOR_INSERT(tgtype))
623  ereport(ERROR,
624  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
625  errmsg("INSERT trigger's WHEN condition cannot reference OLD values"),
626  parser_errposition(pstate, var->location)));
627  /* system columns are okay here */
628  break;
629  case PRS2_NEW_VARNO:
630  if (!TRIGGER_FOR_ROW(tgtype))
631  ereport(ERROR,
632  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
633  errmsg("statement trigger's WHEN condition cannot reference column values"),
634  parser_errposition(pstate, var->location)));
635  if (TRIGGER_FOR_DELETE(tgtype))
636  ereport(ERROR,
637  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
638  errmsg("DELETE trigger's WHEN condition cannot reference NEW values"),
639  parser_errposition(pstate, var->location)));
640  if (var->varattno < 0 && TRIGGER_FOR_BEFORE(tgtype))
641  ereport(ERROR,
642  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
643  errmsg("BEFORE trigger's WHEN condition cannot reference NEW system columns"),
644  parser_errposition(pstate, var->location)));
645  if (TRIGGER_FOR_BEFORE(tgtype) &&
646  var->varattno == 0 &&
647  RelationGetDescr(rel)->constr &&
648  RelationGetDescr(rel)->constr->has_generated_stored)
649  ereport(ERROR,
650  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
651  errmsg("BEFORE trigger's WHEN condition cannot reference NEW generated columns"),
652  errdetail("A whole-row reference is used and the table contains generated columns."),
653  parser_errposition(pstate, var->location)));
654  if (TRIGGER_FOR_BEFORE(tgtype) &&
655  var->varattno > 0 &&
656  TupleDescAttr(RelationGetDescr(rel), var->varattno - 1)->attgenerated)
657  ereport(ERROR,
658  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
659  errmsg("BEFORE trigger's WHEN condition cannot reference NEW generated columns"),
660  errdetail("Column \"%s\" is a generated column.",
661  NameStr(TupleDescAttr(RelationGetDescr(rel), var->varattno - 1)->attname)),
662  parser_errposition(pstate, var->location)));
663  break;
664  default:
665  /* can't happen without add_missing_from, so just elog */
666  elog(ERROR, "trigger WHEN condition cannot contain references to other relations");
667  break;
668  }
669  }
670 
671  /* we'll need the rtable for recordDependencyOnExpr */
672  whenRtable = pstate->p_rtable;
673 
674  qual = nodeToString(whenClause);
675 
676  free_parsestate(pstate);
677  }
678  else if (!whenClause)
679  {
680  whenClause = NULL;
681  whenRtable = NIL;
682  qual = NULL;
683  }
684  else
685  {
686  qual = nodeToString(whenClause);
687  whenRtable = NIL;
688  }
689 
690  /*
691  * Find and validate the trigger function.
692  */
693  if (!OidIsValid(funcoid))
694  funcoid = LookupFuncName(stmt->funcname, 0, NULL, false);
695  if (!isInternal)
696  {
697  aclresult = pg_proc_aclcheck(funcoid, GetUserId(), ACL_EXECUTE);
698  if (aclresult != ACLCHECK_OK)
699  aclcheck_error(aclresult, OBJECT_FUNCTION,
700  NameListToString(stmt->funcname));
701  }
702  funcrettype = get_func_rettype(funcoid);
703  if (funcrettype != TRIGGEROID)
704  ereport(ERROR,
705  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
706  errmsg("function %s must return type %s",
707  NameListToString(stmt->funcname), "trigger")));
708 
709  /*
710  * Scan pg_trigger to see if there is already a trigger of the same name.
711  * Skip this for internally generated triggers, since we'll modify the
712  * name to be unique below.
713  *
714  * NOTE that this is cool only because we have ShareRowExclusiveLock on
715  * the relation, so the trigger set won't be changing underneath us.
716  */
717  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
718  if (!isInternal)
719  {
720  ScanKeyData skeys[2];
721  SysScanDesc tgscan;
722 
723  ScanKeyInit(&skeys[0],
724  Anum_pg_trigger_tgrelid,
725  BTEqualStrategyNumber, F_OIDEQ,
727 
728  ScanKeyInit(&skeys[1],
729  Anum_pg_trigger_tgname,
730  BTEqualStrategyNumber, F_NAMEEQ,
731  CStringGetDatum(stmt->trigname));
732 
733  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
734  NULL, 2, skeys);
735 
736  /* There should be at most one matching tuple */
737  if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
738  {
739  Form_pg_trigger oldtrigger = (Form_pg_trigger) GETSTRUCT(tuple);
740 
741  trigoid = oldtrigger->oid;
742  existing_constraint_oid = oldtrigger->tgconstraint;
743  existing_isInternal = oldtrigger->tgisinternal;
744  trigger_exists = true;
745  /* copy the tuple to use in CatalogTupleUpdate() */
746  tuple = heap_copytuple(tuple);
747  }
748  systable_endscan(tgscan);
749  }
750 
751  if (!trigger_exists)
752  {
753  /* Generate the OID for the new trigger. */
754  trigoid = GetNewOidWithIndex(tgrel, TriggerOidIndexId,
755  Anum_pg_trigger_oid);
756  }
757  else
758  {
759  /*
760  * If OR REPLACE was specified, we'll replace the old trigger;
761  * otherwise complain about the duplicate name.
762  */
763  if (!stmt->replace)
764  ereport(ERROR,
766  errmsg("trigger \"%s\" for relation \"%s\" already exists",
767  stmt->trigname, RelationGetRelationName(rel))));
768 
769  /*
770  * An internal trigger cannot be replaced by a user-defined trigger.
771  * However, skip this test when in_partition, because then we're
772  * recursing from a partitioned table and the check was made at the
773  * parent level. Child triggers will always be marked "internal" (so
774  * this test does protect us from the user trying to replace a child
775  * trigger directly).
776  */
777  if (existing_isInternal && !isInternal && !in_partition)
778  ereport(ERROR,
780  errmsg("trigger \"%s\" for relation \"%s\" is an internal trigger",
781  stmt->trigname, RelationGetRelationName(rel))));
782 
783  /*
784  * It is not allowed to replace with a constraint trigger; gram.y
785  * should have enforced this already.
786  */
787  Assert(!stmt->isconstraint);
788 
789  /*
790  * It is not allowed to replace an existing constraint trigger,
791  * either. (The reason for these restrictions is partly that it seems
792  * difficult to deal with pending trigger events in such cases, and
793  * partly that the command might imply changing the constraint's
794  * properties as well, which doesn't seem nice.)
795  */
796  if (OidIsValid(existing_constraint_oid))
797  ereport(ERROR,
799  errmsg("trigger \"%s\" for relation \"%s\" is a constraint trigger",
800  stmt->trigname, RelationGetRelationName(rel))));
801  }
802 
803  /*
804  * If it's a user-entered CREATE CONSTRAINT TRIGGER command, make a
805  * corresponding pg_constraint entry.
806  */
807  if (stmt->isconstraint && !OidIsValid(constraintOid))
808  {
809  /* Internal callers should have made their own constraints */
810  Assert(!isInternal);
811  constraintOid = CreateConstraintEntry(stmt->trigname,
813  CONSTRAINT_TRIGGER,
814  stmt->deferrable,
815  stmt->initdeferred,
816  true,
817  InvalidOid, /* no parent */
818  RelationGetRelid(rel),
819  NULL, /* no conkey */
820  0,
821  0,
822  InvalidOid, /* no domain */
823  InvalidOid, /* no index */
824  InvalidOid, /* no foreign key */
825  NULL,
826  NULL,
827  NULL,
828  NULL,
829  0,
830  ' ',
831  ' ',
832  ' ',
833  NULL, /* no exclusion */
834  NULL, /* no check constraint */
835  NULL,
836  true, /* islocal */
837  0, /* inhcount */
838  true, /* noinherit */
839  isInternal); /* is_internal */
840  }
841 
842  /*
843  * If trigger is internally generated, modify the provided trigger name to
844  * ensure uniqueness by appending the trigger OID. (Callers will usually
845  * supply a simple constant trigger name in these cases.)
846  */
847  if (isInternal)
848  {
849  snprintf(internaltrigname, sizeof(internaltrigname),
850  "%s_%u", stmt->trigname, trigoid);
851  trigname = internaltrigname;
852  }
853  else
854  {
855  /* user-defined trigger; use the specified trigger name as-is */
856  trigname = stmt->trigname;
857  }
858 
859  /*
860  * Build the new pg_trigger tuple.
861  *
862  * When we're creating a trigger in a partition, we mark it as internal,
863  * even though we don't do the isInternal magic in this function. This
864  * makes the triggers in partitions identical to the ones in the
865  * partitioned tables, except that they are marked internal.
866  */
867  memset(nulls, false, sizeof(nulls));
868 
869  values[Anum_pg_trigger_oid - 1] = ObjectIdGetDatum(trigoid);
870  values[Anum_pg_trigger_tgrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
871  values[Anum_pg_trigger_tgparentid - 1] = ObjectIdGetDatum(parentTriggerOid);
872  values[Anum_pg_trigger_tgname - 1] = DirectFunctionCall1(namein,
873  CStringGetDatum(trigname));
874  values[Anum_pg_trigger_tgfoid - 1] = ObjectIdGetDatum(funcoid);
875  values[Anum_pg_trigger_tgtype - 1] = Int16GetDatum(tgtype);
876  values[Anum_pg_trigger_tgenabled - 1] = trigger_fires_when;
877  values[Anum_pg_trigger_tgisinternal - 1] = BoolGetDatum(isInternal || in_partition);
878  values[Anum_pg_trigger_tgconstrrelid - 1] = ObjectIdGetDatum(constrrelid);
879  values[Anum_pg_trigger_tgconstrindid - 1] = ObjectIdGetDatum(indexOid);
880  values[Anum_pg_trigger_tgconstraint - 1] = ObjectIdGetDatum(constraintOid);
881  values[Anum_pg_trigger_tgdeferrable - 1] = BoolGetDatum(stmt->deferrable);
882  values[Anum_pg_trigger_tginitdeferred - 1] = BoolGetDatum(stmt->initdeferred);
883 
884  if (stmt->args)
885  {
886  ListCell *le;
887  char *args;
888  int16 nargs = list_length(stmt->args);
889  int len = 0;
890 
891  foreach(le, stmt->args)
892  {
893  char *ar = strVal(lfirst(le));
894 
895  len += strlen(ar) + 4;
896  for (; *ar; ar++)
897  {
898  if (*ar == '\\')
899  len++;
900  }
901  }
902  args = (char *) palloc(len + 1);
903  args[0] = '\0';
904  foreach(le, stmt->args)
905  {
906  char *s = strVal(lfirst(le));
907  char *d = args + strlen(args);
908 
909  while (*s)
910  {
911  if (*s == '\\')
912  *d++ = '\\';
913  *d++ = *s++;
914  }
915  strcpy(d, "\\000");
916  }
917  values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(nargs);
918  values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
919  CStringGetDatum(args));
920  }
921  else
922  {
923  values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(0);
924  values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
925  CStringGetDatum(""));
926  }
927 
928  /* build column number array if it's a column-specific trigger */
929  ncolumns = list_length(stmt->columns);
930  if (ncolumns == 0)
931  columns = NULL;
932  else
933  {
934  ListCell *cell;
935  int i = 0;
936 
937  columns = (int16 *) palloc(ncolumns * sizeof(int16));
938  foreach(cell, stmt->columns)
939  {
940  char *name = strVal(lfirst(cell));
941  int16 attnum;
942  int j;
943 
944  /* Lookup column name. System columns are not allowed */
945  attnum = attnameAttNum(rel, name, false);
946  if (attnum == InvalidAttrNumber)
947  ereport(ERROR,
948  (errcode(ERRCODE_UNDEFINED_COLUMN),
949  errmsg("column \"%s\" of relation \"%s\" does not exist",
950  name, RelationGetRelationName(rel))));
951 
952  /* Check for duplicates */
953  for (j = i - 1; j >= 0; j--)
954  {
955  if (columns[j] == attnum)
956  ereport(ERROR,
957  (errcode(ERRCODE_DUPLICATE_COLUMN),
958  errmsg("column \"%s\" specified more than once",
959  name)));
960  }
961 
962  columns[i++] = attnum;
963  }
964  }
965  tgattr = buildint2vector(columns, ncolumns);
966  values[Anum_pg_trigger_tgattr - 1] = PointerGetDatum(tgattr);
967 
968  /* set tgqual if trigger has WHEN clause */
969  if (qual)
970  values[Anum_pg_trigger_tgqual - 1] = CStringGetTextDatum(qual);
971  else
972  nulls[Anum_pg_trigger_tgqual - 1] = true;
973 
974  if (oldtablename)
975  values[Anum_pg_trigger_tgoldtable - 1] = DirectFunctionCall1(namein,
976  CStringGetDatum(oldtablename));
977  else
978  nulls[Anum_pg_trigger_tgoldtable - 1] = true;
979  if (newtablename)
980  values[Anum_pg_trigger_tgnewtable - 1] = DirectFunctionCall1(namein,
981  CStringGetDatum(newtablename));
982  else
983  nulls[Anum_pg_trigger_tgnewtable - 1] = true;
984 
985  /*
986  * Insert or replace tuple in pg_trigger.
987  */
988  if (!trigger_exists)
989  {
990  tuple = heap_form_tuple(tgrel->rd_att, values, nulls);
991  CatalogTupleInsert(tgrel, tuple);
992  }
993  else
994  {
995  HeapTuple newtup;
996 
997  newtup = heap_form_tuple(tgrel->rd_att, values, nulls);
998  CatalogTupleUpdate(tgrel, &tuple->t_self, newtup);
999  heap_freetuple(newtup);
1000  }
1001 
1002  heap_freetuple(tuple); /* free either original or new tuple */
1003  table_close(tgrel, RowExclusiveLock);
1004 
1005  pfree(DatumGetPointer(values[Anum_pg_trigger_tgname - 1]));
1006  pfree(DatumGetPointer(values[Anum_pg_trigger_tgargs - 1]));
1007  pfree(DatumGetPointer(values[Anum_pg_trigger_tgattr - 1]));
1008  if (oldtablename)
1009  pfree(DatumGetPointer(values[Anum_pg_trigger_tgoldtable - 1]));
1010  if (newtablename)
1011  pfree(DatumGetPointer(values[Anum_pg_trigger_tgnewtable - 1]));
1012 
1013  /*
1014  * Update relation's pg_class entry; if necessary; and if not, send an SI
1015  * message to make other backends (and this one) rebuild relcache entries.
1016  */
1017  pgrel = table_open(RelationRelationId, RowExclusiveLock);
1018  tuple = SearchSysCacheCopy1(RELOID,
1020  if (!HeapTupleIsValid(tuple))
1021  elog(ERROR, "cache lookup failed for relation %u",
1022  RelationGetRelid(rel));
1023  if (!((Form_pg_class) GETSTRUCT(tuple))->relhastriggers)
1024  {
1025  ((Form_pg_class) GETSTRUCT(tuple))->relhastriggers = true;
1026 
1027  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
1028 
1030  }
1031  else
1033 
1034  heap_freetuple(tuple);
1035  table_close(pgrel, RowExclusiveLock);
1036 
1037  /*
1038  * If we're replacing a trigger, flush all the old dependencies before
1039  * recording new ones.
1040  */
1041  if (trigger_exists)
1042  deleteDependencyRecordsFor(TriggerRelationId, trigoid, true);
1043 
1044  /*
1045  * Record dependencies for trigger. Always place a normal dependency on
1046  * the function.
1047  */
1048  myself.classId = TriggerRelationId;
1049  myself.objectId = trigoid;
1050  myself.objectSubId = 0;
1051 
1052  referenced.classId = ProcedureRelationId;
1053  referenced.objectId = funcoid;
1054  referenced.objectSubId = 0;
1055  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1056 
1057  if (isInternal && OidIsValid(constraintOid))
1058  {
1059  /*
1060  * Internally-generated trigger for a constraint, so make it an
1061  * internal dependency of the constraint. We can skip depending on
1062  * the relation(s), as there'll be an indirect dependency via the
1063  * constraint.
1064  */
1065  referenced.classId = ConstraintRelationId;
1066  referenced.objectId = constraintOid;
1067  referenced.objectSubId = 0;
1068  recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
1069  }
1070  else
1071  {
1072  /*
1073  * User CREATE TRIGGER, so place dependencies. We make trigger be
1074  * auto-dropped if its relation is dropped or if the FK relation is
1075  * dropped. (Auto drop is compatible with our pre-7.3 behavior.)
1076  */
1077  referenced.classId = RelationRelationId;
1078  referenced.objectId = RelationGetRelid(rel);
1079  referenced.objectSubId = 0;
1080  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
1081 
1082  if (OidIsValid(constrrelid))
1083  {
1084  referenced.classId = RelationRelationId;
1085  referenced.objectId = constrrelid;
1086  referenced.objectSubId = 0;
1087  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
1088  }
1089  /* Not possible to have an index dependency in this case */
1090  Assert(!OidIsValid(indexOid));
1091 
1092  /*
1093  * If it's a user-specified constraint trigger, make the constraint
1094  * internally dependent on the trigger instead of vice versa.
1095  */
1096  if (OidIsValid(constraintOid))
1097  {
1098  referenced.classId = ConstraintRelationId;
1099  referenced.objectId = constraintOid;
1100  referenced.objectSubId = 0;
1101  recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL);
1102  }
1103 
1104  /*
1105  * If it's a partition trigger, create the partition dependencies.
1106  */
1107  if (OidIsValid(parentTriggerOid))
1108  {
1109  ObjectAddressSet(referenced, TriggerRelationId, parentTriggerOid);
1110  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
1111  ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
1112  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
1113  }
1114  }
1115 
1116  /* If column-specific trigger, add normal dependencies on columns */
1117  if (columns != NULL)
1118  {
1119  int i;
1120 
1121  referenced.classId = RelationRelationId;
1122  referenced.objectId = RelationGetRelid(rel);
1123  for (i = 0; i < ncolumns; i++)
1124  {
1125  referenced.objectSubId = columns[i];
1126  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1127  }
1128  }
1129 
1130  /*
1131  * If it has a WHEN clause, add dependencies on objects mentioned in the
1132  * expression (eg, functions, as well as any columns used).
1133  */
1134  if (whenRtable != NIL)
1135  recordDependencyOnExpr(&myself, whenClause, whenRtable,
1137 
1138  /* Post creation hook for new trigger */
1139  InvokeObjectPostCreateHookArg(TriggerRelationId, trigoid, 0,
1140  isInternal);
1141 
1142  /*
1143  * Lastly, create the trigger on child relations, if needed.
1144  */
1145  if (partition_recurse)
1146  {
1147  PartitionDesc partdesc = RelationGetPartitionDesc(rel, true);
1148  List *idxs = NIL;
1149  List *childTbls = NIL;
1150  ListCell *l;
1151  int i;
1152  MemoryContext oldcxt,
1153  perChildCxt;
1154 
1156  "part trig clone",
1158 
1159  /*
1160  * When a trigger is being created associated with an index, we'll
1161  * need to associate the trigger in each child partition with the
1162  * corresponding index on it.
1163  */
1164  if (OidIsValid(indexOid))
1165  {
1166  ListCell *l;
1167  List *idxs = NIL;
1168 
1170  foreach(l, idxs)
1171  childTbls = lappend_oid(childTbls,
1173  false));
1174  }
1175 
1176  oldcxt = MemoryContextSwitchTo(perChildCxt);
1177 
1178  /* Iterate to create the trigger on each existing partition */
1179  for (i = 0; i < partdesc->nparts; i++)
1180  {
1181  Oid indexOnChild = InvalidOid;
1182  ListCell *l2;
1183  CreateTrigStmt *childStmt;
1184  Relation childTbl;
1185  Node *qual;
1186 
1187  childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
1188 
1189  /* Find which of the child indexes is the one on this partition */
1190  if (OidIsValid(indexOid))
1191  {
1192  forboth(l, idxs, l2, childTbls)
1193  {
1194  if (lfirst_oid(l2) == partdesc->oids[i])
1195  {
1196  indexOnChild = lfirst_oid(l);
1197  break;
1198  }
1199  }
1200  if (!OidIsValid(indexOnChild))
1201  elog(ERROR, "failed to find index matching index \"%s\" in partition \"%s\"",
1202  get_rel_name(indexOid),
1203  get_rel_name(partdesc->oids[i]));
1204  }
1205 
1206  /*
1207  * Initialize our fabricated parse node by copying the original
1208  * one, then resetting fields that we pass separately.
1209  */
1210  childStmt = (CreateTrigStmt *) copyObject(stmt);
1211  childStmt->funcname = NIL;
1212  childStmt->whenClause = NULL;
1213 
1214  /* If there is a WHEN clause, create a modified copy of it */
1215  qual = copyObject(whenClause);
1216  qual = (Node *)
1218  childTbl, rel);
1219  qual = (Node *)
1221  childTbl, rel);
1222 
1223  CreateTriggerFiringOn(childStmt, queryString,
1224  partdesc->oids[i], refRelOid,
1225  InvalidOid, indexOnChild,
1226  funcoid, trigoid, qual,
1227  isInternal, true, trigger_fires_when);
1228 
1229  table_close(childTbl, NoLock);
1230 
1231  MemoryContextReset(perChildCxt);
1232  }
1233 
1234  MemoryContextSwitchTo(oldcxt);
1235  MemoryContextDelete(perChildCxt);
1236  list_free(idxs);
1237  list_free(childTbls);
1238  }
1239 
1240  /* Keep lock on target rel until end of xact */
1241  table_close(rel, NoLock);
1242 
1243  return myself;
1244 }
signed short int16
Definition: c.h:428
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
#define NIL
Definition: pg_list.h:65
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:381
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3475
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
bool IsSystemRelation(Relation relation)
Definition: catalog.c:74
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
#define PointerGetDatum(X)
Definition: postgres.h:600
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
ObjectAddress CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition, char trigger_fires_when)
Definition: trigger.c:173
Node * whenClause
Definition: parsenodes.h:2540
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid parentConstrId, Oid relId, const int16 *constraintKey, int constraintNKeys, int constraintNTotalKeys, Oid domainId, Oid indexRelId, Oid foreignRelId, const int16 *foreignKey, const Oid *pfEqOp, const Oid *ppEqOp, const Oid *ffEqOp, int foreignNKeys, char foreignUpdateType, char foreignDeleteType, char foreignMatchType, const Oid *exclOp, Node *conExpr, const char *conBin, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:50
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:205
int2vector * buildint2vector(const int16 *int2s, int n)
Definition: int.c:114
long deleteDependencyRecordsFor(Oid classId, Oid objectId, bool skipExtensionDeps)
Definition: pg_depend.c:236
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Int16GetDatum(X)
Definition: postgres.h:495
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:539
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
AttrNumber varattno
Definition: primnodes.h:191
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
List * pull_var_clause(Node *node, int flags)
Definition: var.c:562
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1626
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define NAMEDATALEN
void assign_expr_collations(ParseState *pstate, Node *expr)
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:387
RangeVar * constrrel
Definition: parsenodes.h:2546
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
Definition: parse_func.c:2145
ItemPointerData t_self
Definition: htup.h:65
bool has_superclass(Oid relationId)
Definition: pg_inherits.c:378
Datum byteain(PG_FUNCTION_ARGS)
Definition: varlena.c:296
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define ACL_TRIGGER
Definition: parsenodes.h:88
int location
Definition: primnodes.h:201
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition: partdesc.c:72
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define CStringGetDatum(X)
Definition: postgres.h:622
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
Definition: dependency.c:1568
#define RelationGetRelationName(relation)
Definition: rel.h:511
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
const char * p_sourcetext
Definition: parse_node.h:181
List * transitionRels
Definition: parsenodes.h:2542
Oid rd_id
Definition: rel.h:111
#define PRS2_OLD_VARNO
Definition: primnodes.h:183
Index varno
Definition: primnodes.h:189
char * NameListToString(List *names)
Definition: namespace.c:3147
Definition: c.h:649
AclResult
Definition: acl.h:177
uintptr_t Datum
Definition: postgres.h:411
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define InvokeObjectPostCreateHookArg(classId, objectId, subId, is_internal)
Definition: objectaccess.h:153
TupleDesc rd_att
Definition: rel.h:110
#define BoolGetDatum(X)
Definition: postgres.h:446
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102
bool allowSystemTableMods
Definition: globals.c:123
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:83
List * find_inheritance_children(Oid parentrelId, LOCKMODE lockmode)
Definition: pg_inherits.c:59
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
static int list_length(const List *l)
Definition: pg_list.h:149
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
const char * name
Definition: encode.c:515
#define InvalidAttrNumber
Definition: attnum.h:23
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4680
#define DatumGetPointer(X)
Definition: postgres.h:593
static Datum values[MAXATTR]
Definition: bootstrap.c:166
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:256
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ACL_EXECUTE
Definition: parsenodes.h:89
void list_free(List *list)
Definition: list.c:1391
#define elog(elevel,...)
Definition: elog.h:232
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4718
int i
RangeVar * relation
Definition: parsenodes.h:2531
ObjectType get_relkind_objtype(char relkind)
#define NameStr(name)
Definition: c.h:681
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define CStringGetTextDatum(s)
Definition: builtins.h:82
char * nodeToString(const void *obj)
Definition: outfuncs.c:4542
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition: inval.c:1315
#define copyObject(obj)
Definition: nodes.h:655
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define snprintf
Definition: port.h:216
List * map_partition_varattnos(List *expr, int fromrel_varno, Relation to_rel, Relation from_rel)
Definition: partition.c:221
#define RelationGetRelid(relation)
Definition: rel.h:477
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define PRS2_NEW_VARNO
Definition: primnodes.h:184
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:171
#define RelationGetNamespace(relation)
Definition: rel.h:518
List * p_rtable
Definition: parse_node.h:182

◆ EnableDisableTrigger()

void EnableDisableTrigger ( Relation  rel,
const char *  tgname,
char  fires_when,
bool  skip_system,
LOCKMODE  lockmode 
)

Definition at line 1683 of file trigger.c.

References BTEqualStrategyNumber, CacheInvalidateRelcache(), CatalogTupleUpdate(), CStringGetDatum, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_copytuple(), heap_freetuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, NameStr, ObjectIdGetDatum, RelationGetRelationName, RelationGetRelid, RowExclusiveLock, ScanKeyInit(), superuser(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by ATExecEnableDisableTrigger().

1685 {
1686  Relation tgrel;
1687  int nkeys;
1688  ScanKeyData keys[2];
1689  SysScanDesc tgscan;
1690  HeapTuple tuple;
1691  bool found;
1692  bool changed;
1693 
1694  /* Scan the relevant entries in pg_triggers */
1695  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1696 
1697  ScanKeyInit(&keys[0],
1698  Anum_pg_trigger_tgrelid,
1699  BTEqualStrategyNumber, F_OIDEQ,
1701  if (tgname)
1702  {
1703  ScanKeyInit(&keys[1],
1704  Anum_pg_trigger_tgname,
1705  BTEqualStrategyNumber, F_NAMEEQ,
1706  CStringGetDatum(tgname));
1707  nkeys = 2;
1708  }
1709  else
1710  nkeys = 1;
1711 
1712  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1713  NULL, nkeys, keys);
1714 
1715  found = changed = false;
1716 
1717  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1718  {
1719  Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1720 
1721  if (oldtrig->tgisinternal)
1722  {
1723  /* system trigger ... ok to process? */
1724  if (skip_system)
1725  continue;
1726  if (!superuser())
1727  ereport(ERROR,
1728  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1729  errmsg("permission denied: \"%s\" is a system trigger",
1730  NameStr(oldtrig->tgname))));
1731  }
1732 
1733  found = true;
1734 
1735  if (oldtrig->tgenabled != fires_when)
1736  {
1737  /* need to change this one ... make a copy to scribble on */
1738  HeapTuple newtup = heap_copytuple(tuple);
1739  Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1740 
1741  newtrig->tgenabled = fires_when;
1742 
1743  CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1744 
1745  heap_freetuple(newtup);
1746 
1747  changed = true;
1748  }
1749 
1750  InvokeObjectPostAlterHook(TriggerRelationId,
1751  oldtrig->oid, 0);
1752  }
1753 
1754  systable_endscan(tgscan);
1755 
1756  table_close(tgrel, RowExclusiveLock);
1757 
1758  if (tgname && !found)
1759  ereport(ERROR,
1760  (errcode(ERRCODE_UNDEFINED_OBJECT),
1761  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1762  tgname, RelationGetRelationName(rel))));
1763 
1764  /*
1765  * If we changed anything, broadcast a SI inval message to force each
1766  * backend (including our own!) to rebuild relation's relcache entry.
1767  * Otherwise they will fail to apply the change promptly.
1768  */
1769  if (changed)
1771 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:622
#define RelationGetRelationName(relation)
Definition: rel.h:511
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1279
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define NameStr(name)
Definition: c.h:681
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:477
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ ExecARDeleteTriggers()

void ExecARDeleteTriggers ( EState estate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple,
TransitionCaptureState transition_capture 
)

Definition at line 2691 of file trigger.c.

References AfterTriggerSaveEvent(), Assert, ExecForceStoreHeapTuple(), ExecGetTriggerOldSlot(), GetTupleForTrigger(), HeapTupleIsValid, ItemPointerIsValid, LockTupleExclusive, NIL, ResultRelInfo::ri_TrigDesc, TransitionCaptureState::tcs_delete_old_table, TriggerDesc::trig_delete_after_row, and TRIGGER_EVENT_DELETE.

Referenced by ExecDelete(), and ExecSimpleRelationDelete().

2695 {
2696  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2697 
2698  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2699  (transition_capture && transition_capture->tcs_delete_old_table))
2700  {
2701  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2702 
2703  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2704  if (fdw_trigtuple == NULL)
2705  GetTupleForTrigger(estate,
2706  NULL,
2707  relinfo,
2708  tupleid,
2710  slot,
2711  NULL);
2712  else
2713  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2714 
2716  true, slot, NULL, NIL, NULL,
2717  transition_capture);
2718  }
2719 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define NIL
Definition: pg_list.h:65
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:3145
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1166
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
bool trig_delete_after_row
Definition: reltrigger.h:67
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5597
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804

◆ ExecARInsertTriggers()

void ExecARInsertTriggers ( EState estate,
ResultRelInfo relinfo,
TupleTableSlot slot,
List recheckIndexes,
TransitionCaptureState transition_capture 
)

Definition at line 2461 of file trigger.c.

References AfterTriggerSaveEvent(), ResultRelInfo::ri_TrigDesc, TransitionCaptureState::tcs_insert_new_table, TriggerDesc::trig_insert_after_row, and TRIGGER_EVENT_INSERT.

Referenced by CopyFrom(), CopyMultiInsertBufferFlush(), ExecBatchInsert(), ExecInsert(), and ExecSimpleRelationInsert().

2464 {
2465  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2466 
2467  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2468  (transition_capture && transition_capture->tcs_insert_new_table))
2470  true, NULL, slot,
2471  recheckIndexes, NULL,
2472  transition_capture);
2473 }
bool trig_insert_after_row
Definition: reltrigger.h:57
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5597
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91

◆ ExecARUpdateTriggers()

void ExecARUpdateTriggers ( EState estate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple,
TupleTableSlot slot,
List recheckIndexes,
TransitionCaptureState transition_capture 
)

Definition at line 2975 of file trigger.c.

References AfterTriggerSaveEvent(), ExecClearTuple(), ExecForceStoreHeapTuple(), ExecGetAllUpdatedCols(), ExecGetTriggerOldSlot(), GetTupleForTrigger(), ItemPointerIsValid, LockTupleExclusive, ResultRelInfo::ri_TrigDesc, TransitionCaptureState::tcs_update_new_table, TransitionCaptureState::tcs_update_old_table, TriggerDesc::trig_update_after_row, and TRIGGER_EVENT_UPDATE.

Referenced by ExecDelete(), ExecInsert(), ExecSimpleRelationUpdate(), and ExecUpdate().

2981 {
2982  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2983 
2984  if ((trigdesc && trigdesc->trig_update_after_row) ||
2985  (transition_capture &&
2986  (transition_capture->tcs_update_old_table ||
2987  transition_capture->tcs_update_new_table)))
2988  {
2989  /*
2990  * Note: if the UPDATE is converted into a DELETE+INSERT as part of
2991  * update-partition-key operation, then this function is also called
2992  * separately for DELETE and INSERT to capture transition table rows.
2993  * In such case, either old tuple or new tuple can be NULL.
2994  */
2995  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2996 
2997  if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
2998  GetTupleForTrigger(estate,
2999  NULL,
3000  relinfo,
3001  tupleid,
3003  oldslot,
3004  NULL);
3005  else if (fdw_trigtuple != NULL)
3006  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
3007  else
3008  ExecClearTuple(oldslot);
3009 
3011  true, oldslot, newslot, recheckIndexes,
3012  ExecGetAllUpdatedCols(relinfo, estate),
3013  transition_capture);
3014  }
3015 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:3145
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1347
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1166
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
bool trig_update_after_row
Definition: reltrigger.h:62
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5597
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93

◆ ExecASDeleteTriggers()

void ExecASDeleteTriggers ( EState estate,
ResultRelInfo relinfo,
TransitionCaptureState transition_capture 
)

Definition at line 2588 of file trigger.c.

References AfterTriggerSaveEvent(), NIL, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_delete_after_statement, and TRIGGER_EVENT_DELETE.

Referenced by fireASTriggers().

2590 {
2591  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2592 
2593  if (trigdesc && trigdesc->trig_delete_after_statement)
2595  false, NULL, NULL, NIL, NULL, transition_capture);
2596 }
#define NIL
Definition: pg_list.h:65
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5597
bool trig_delete_after_statement
Definition: reltrigger.h:70

◆ ExecASInsertTriggers()

void ExecASInsertTriggers ( EState estate,
ResultRelInfo relinfo,
TransitionCaptureState transition_capture 
)

Definition at line 2374 of file trigger.c.

References AfterTriggerSaveEvent(), NIL, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_insert_after_statement, and TRIGGER_EVENT_INSERT.

Referenced by CopyFrom(), and fireASTriggers().

2376 {
2377  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2378 
2379  if (trigdesc && trigdesc->trig_insert_after_statement)
2381  false, NULL, NULL, NIL, NULL, transition_capture);
2382 }
#define NIL
Definition: pg_list.h:65
bool trig_insert_after_statement
Definition: reltrigger.h:60
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5597
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91

◆ ExecASTruncateTriggers()

void ExecASTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 3131 of file trigger.c.

References AfterTriggerSaveEvent(), NIL, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_truncate_after_statement, and TRIGGER_EVENT_TRUNCATE.

Referenced by ExecuteTruncateGuts().

3132 {
3133  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3134 
3135  if (trigdesc && trigdesc->trig_truncate_after_statement)
3137  false, NULL, NULL, NIL, NULL, NULL);
3138 }
#define NIL
Definition: pg_list.h:65
bool trig_truncate_after_statement
Definition: reltrigger.h:73
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5597
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:94

◆ ExecASUpdateTriggers()

void ExecASUpdateTriggers ( EState estate,
ResultRelInfo relinfo,
TransitionCaptureState transition_capture 
)

Definition at line 2827 of file trigger.c.

References AfterTriggerSaveEvent(), Assert, ExecGetAllUpdatedCols(), NIL, ResultRelInfo::ri_RootResultRelInfo, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_update_after_statement, and TRIGGER_EVENT_UPDATE.

Referenced by fireASTriggers().

2829 {
2830  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2831 
2832  /* statement-level triggers operate on the parent table */
2833  Assert(relinfo->ri_RootResultRelInfo == NULL);
2834 
2835  if (trigdesc && trigdesc->trig_update_after_statement)
2837  false, NULL, NULL, NIL,
2838  ExecGetAllUpdatedCols(relinfo, estate),
2839  transition_capture);
2840 }
#define NIL
Definition: pg_list.h:65
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1347
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:512
bool trig_update_after_statement
Definition: reltrigger.h:65
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5597
#define Assert(condition)
Definition: c.h:804
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93

◆ ExecBRDeleteTriggers()

bool ExecBRDeleteTriggers ( EState estate,
EPQState epqstate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple,
TupleTableSlot **  epqslot 
)

Definition at line 2606 of file trigger.c.

References Assert, ExecCallTriggerFunc(), ExecFetchSlotHeapTuple(), ExecForceStoreHeapTuple(), ExecGetTriggerOldSlot(), GetPerTupleMemoryContext, GetTupleForTrigger(), heap_freetuple(), HeapTupleIsValid, i, ItemPointerIsValid, LockTupleExclusive, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, TriggerData::tg_trigtuple, Trigger::tgtype, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_DELETE, TRIGGER_EVENT_ROW, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecDelete(), and ExecSimpleRelationDelete().

2611 {
2612  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2613  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2614  bool result = true;
2615  TriggerData LocTriggerData = {0};
2616  HeapTuple trigtuple;
2617  bool should_free = false;
2618  int i;
2619 
2620  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2621  if (fdw_trigtuple == NULL)
2622  {
2623  TupleTableSlot *epqslot_candidate = NULL;
2624 
2625  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2626  LockTupleExclusive, slot, &epqslot_candidate))
2627  return false;
2628 
2629  /*
2630  * If the tuple was concurrently updated and the caller of this
2631  * function requested for the updated tuple, skip the trigger
2632  * execution.
2633  */
2634  if (epqslot_candidate != NULL && epqslot != NULL)
2635  {
2636  *epqslot = epqslot_candidate;
2637  return false;
2638  }
2639 
2640  trigtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2641 
2642  }
2643  else
2644  {
2645  trigtuple = fdw_trigtuple;
2646  ExecForceStoreHeapTuple(trigtuple, slot, false);
2647  }
2648 
2649  LocTriggerData.type = T_TriggerData;
2650  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2653  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2654  for (i = 0; i < trigdesc->numtriggers; i++)
2655  {
2656  HeapTuple newtuple;
2657  Trigger *trigger = &trigdesc->triggers[i];
2658 
2659  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2660  TRIGGER_TYPE_ROW,
2661  TRIGGER_TYPE_BEFORE,
2662  TRIGGER_TYPE_DELETE))
2663  continue;
2664  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2665  NULL, slot, NULL))
2666  continue;
2667 
2668  LocTriggerData.tg_trigslot = slot;
2669  LocTriggerData.tg_trigtuple = trigtuple;
2670  LocTriggerData.tg_trigger = trigger;
2671  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2672  i,
2673  relinfo->ri_TrigFunctions,
2674  relinfo->ri_TrigInstrument,
2675  GetPerTupleMemoryContext(estate));
2676  if (newtuple == NULL)
2677  {
2678  result = false; /* tell caller to suppress delete */
2679  break;
2680  }
2681  if (newtuple != trigtuple)
2682  heap_freetuple(newtuple);
2683  }
2684  if (should_free)
2685  heap_freetuple(trigtuple);
2686 
2687  return result;
2688 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:3145
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1166
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
HeapTuple tg_trigtuple
Definition: trigger.h:35
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ ExecBRInsertTriggers()

bool ExecBRInsertTriggers ( EState estate,
ResultRelInfo relinfo,
TupleTableSlot slot 
)

Definition at line 2385 of file trigger.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, ExecCallTriggerFunc(), ExecFetchSlotHeapTuple(), ExecForceStoreHeapTuple(), ExecPartitionCheck(), get_namespace_name(), GetPerTupleMemoryContext, heap_freetuple(), i, TriggerDesc::numtriggers, RelationGetNamespace, RelationGetRelationName, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, TriggerData::tg_trigtuple, Trigger::tgisclone, Trigger::tgname, Trigger::tgtype, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_INSERT, TRIGGER_EVENT_ROW, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by CopyFrom(), ExecInsert(), and ExecSimpleRelationInsert().

2387 {
2388  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2389  HeapTuple newtuple = NULL;
2390  bool should_free;
2391  TriggerData LocTriggerData = {0};
2392  int i;
2393 
2394  LocTriggerData.type = T_TriggerData;
2395  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2398  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2399  for (i = 0; i < trigdesc->numtriggers; i++)
2400  {
2401  Trigger *trigger = &trigdesc->triggers[i];
2402  HeapTuple oldtuple;
2403 
2404  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2405  TRIGGER_TYPE_ROW,
2406  TRIGGER_TYPE_BEFORE,
2407  TRIGGER_TYPE_INSERT))
2408  continue;
2409  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2410  NULL, NULL, slot))
2411  continue;
2412 
2413  if (!newtuple)
2414  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2415 
2416  LocTriggerData.tg_trigslot = slot;
2417  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2418  LocTriggerData.tg_trigger = trigger;
2419  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2420  i,
2421  relinfo->ri_TrigFunctions,
2422  relinfo->ri_TrigInstrument,
2423  GetPerTupleMemoryContext(estate));
2424  if (newtuple == NULL)
2425  {
2426  if (should_free)
2427  heap_freetuple(oldtuple);
2428  return false; /* "do nothing" */
2429  }
2430  else if (newtuple != oldtuple)
2431  {
2432  ExecForceStoreHeapTuple(newtuple, slot, false);
2433 
2434  /*
2435  * After a tuple in a partition goes through a trigger, the user
2436  * could have changed the partition key enough that the tuple no
2437  * longer fits the partition. Verify that.
2438  */
2439  if (trigger->tgisclone &&
2440  !ExecPartitionCheck(relinfo, slot, estate, false))
2441  ereport(ERROR,
2442  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2443  errmsg("moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported"),
2444  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2445  trigger->tgname,
2448 
2449  if (should_free)
2450  heap_freetuple(oldtuple);
2451 
2452  /* signal tuple should be re-fetched if used */
2453  newtuple = NULL;
2454  }
2455  }
2456 
2457  return true;
2458 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
int errcode(int sqlerrcode)
Definition: elog.c:698
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:46
char * tgname
Definition: reltrigger.h:27
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define RelationGetRelationName(relation)
Definition: rel.h:511
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
bool tgisclone
Definition: reltrigger.h:32
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:157
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:909
NodeTag type
Definition: trigger.h:32
int i
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1697
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34
#define RelationGetNamespace(relation)
Definition: rel.h:518

◆ ExecBRUpdateTriggers()

bool ExecBRUpdateTriggers ( EState estate,
EPQState epqstate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple,
TupleTableSlot slot 
)

Definition at line 2843 of file trigger.c.

References Assert, ExecCallTriggerFunc(), ExecCopySlot(), ExecFetchSlotHeapTuple(), ExecForceStoreHeapTuple(), ExecGetAllUpdatedCols(), ExecGetTriggerOldSlot(), ExecGetUpdateNewTuple(), ExecMaterializeSlot(), ExecUpdateLockMode(), GetPerTupleMemoryContext, GetTupleForTrigger(), heap_freetuple(), HeapTupleIsValid, i, ItemPointerIsValid, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newslot, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, TriggerData::tg_trigtuple, TriggerData::tg_updatedcols, Trigger::tgtype, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_ROW, TRIGGER_EVENT_UPDATE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecSimpleRelationUpdate(), and ExecUpdate().

2848 {
2849  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2850  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2851  HeapTuple newtuple = NULL;
2852  HeapTuple trigtuple;
2853  bool should_free_trig = false;
2854  bool should_free_new = false;
2855  TriggerData LocTriggerData = {0};
2856  int i;
2857  Bitmapset *updatedCols;
2858  LockTupleMode lockmode;
2859 
2860  /* Determine lock mode to use */
2861  lockmode = ExecUpdateLockMode(estate, relinfo);
2862 
2863  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2864  if (fdw_trigtuple == NULL)
2865  {
2866  TupleTableSlot *epqslot_candidate = NULL;
2867 
2868  /* get a copy of the on-disk tuple we are planning to update */
2869  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2870  lockmode, oldslot, &epqslot_candidate))
2871  return false; /* cancel the update action */
2872 
2873  /*
2874  * In READ COMMITTED isolation level it's possible that target tuple
2875  * was changed due to concurrent update. In that case we have a raw
2876  * subplan output tuple in epqslot_candidate, and need to form a new
2877  * insertable tuple using ExecGetUpdateNewTuple to replace the one we
2878  * received in newslot. Neither we nor our callers have any further
2879  * interest in the passed-in tuple, so it's okay to overwrite newslot
2880  * with the newer data.
2881  *
2882  * (Typically, newslot was also generated by ExecGetUpdateNewTuple, so
2883  * that epqslot_clean will be that same slot and the copy step below
2884  * is not needed.)
2885  */
2886  if (epqslot_candidate != NULL)
2887  {
2888  TupleTableSlot *epqslot_clean;
2889 
2890  epqslot_clean = ExecGetUpdateNewTuple(relinfo, epqslot_candidate,
2891  oldslot);
2892 
2893  if (newslot != epqslot_clean)
2894  ExecCopySlot(newslot, epqslot_clean);
2895  }
2896 
2897  trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
2898  }
2899  else
2900  {
2901  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
2902  trigtuple = fdw_trigtuple;
2903  }
2904 
2905  LocTriggerData.type = T_TriggerData;
2906  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2909  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2910  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2911  LocTriggerData.tg_updatedcols = updatedCols;
2912  for (i = 0; i < trigdesc->numtriggers; i++)
2913  {
2914  Trigger *trigger = &trigdesc->triggers[i];
2915  HeapTuple oldtuple;
2916 
2917  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2918  TRIGGER_TYPE_ROW,
2919  TRIGGER_TYPE_BEFORE,
2920  TRIGGER_TYPE_UPDATE))
2921  continue;
2922  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2923  updatedCols, oldslot, newslot))
2924  continue;
2925 
2926  if (!newtuple)
2927  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
2928 
2929  LocTriggerData.tg_trigslot = oldslot;
2930  LocTriggerData.tg_trigtuple = trigtuple;
2931  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2932  LocTriggerData.tg_newslot = newslot;
2933  LocTriggerData.tg_trigger = trigger;
2934  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2935  i,
2936  relinfo->ri_TrigFunctions,
2937  relinfo->ri_TrigInstrument,
2938  GetPerTupleMemoryContext(estate));
2939 
2940  if (newtuple == NULL)
2941  {
2942  if (should_free_trig)
2943  heap_freetuple(trigtuple);
2944  if (should_free_new)
2945  heap_freetuple(oldtuple);
2946  return false; /* "do nothing" */
2947  }
2948  else if (newtuple != oldtuple)
2949  {
2950  ExecForceStoreHeapTuple(newtuple, newslot, false);
2951 
2952  /*
2953  * If the tuple returned by the trigger / being stored, is the old
2954  * row version, and the heap tuple passed to the trigger was
2955  * allocated locally, materialize the slot. Otherwise we might
2956  * free it while still referenced by the slot.
2957  */
2958  if (should_free_trig && newtuple == trigtuple)
2959  ExecMaterializeSlot(newslot);
2960 
2961  if (should_free_new)
2962  heap_freetuple(oldtuple);
2963 
2964  /* signal tuple should be re-fetched if used */
2965  newtuple = NULL;
2966  }
2967  }
2968  if (should_free_trig)
2969  heap_freetuple(trigtuple);
2970 
2971  return true;
2972 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:411
LockTupleMode
Definition: lockoptions.h:49
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:3145
TupleTableSlot * ExecGetUpdateNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot)
const Bitmapset * tg_updatedcols
Definition: trigger.h:42
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1347
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1166
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
HeapTuple tg_trigtuple
Definition: trigger.h:35
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
TupleTableSlot * tg_newslot
Definition: trigger.h:39
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2240
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSDeleteTriggers()

void ExecBSDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2537 of file trigger.c.

References before_stmt_triggers_fired(), CMD_DELETE, ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetPerTupleMemoryContext, i, TriggerDesc::numtriggers, RelationGetRelid, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, Trigger::tgtype, TriggerDesc::trig_delete_before_statement, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_DELETE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by fireBSTriggers().

2538 {
2539  TriggerDesc *trigdesc;
2540  int i;
2541  TriggerData LocTriggerData = {0};
2542 
2543  trigdesc = relinfo->ri_TrigDesc;
2544 
2545  if (trigdesc == NULL)
2546  return;
2547  if (!trigdesc->trig_delete_before_statement)
2548  return;
2549 
2550  /* no-op if we already fired BS triggers in this context */
2552  CMD_DELETE))
2553  return;
2554 
2555  LocTriggerData.type = T_TriggerData;
2556  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2558  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2559  for (i = 0; i < trigdesc->numtriggers; i++)
2560  {
2561  Trigger *trigger = &trigdesc->triggers[i];
2562  HeapTuple newtuple;
2563 
2564  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2565  TRIGGER_TYPE_STATEMENT,
2566  TRIGGER_TYPE_BEFORE,
2567  TRIGGER_TYPE_DELETE))
2568  continue;
2569  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2570  NULL, NULL, NULL))
2571  continue;
2572 
2573  LocTriggerData.tg_trigger = trigger;
2574  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2575  i,
2576  relinfo->ri_TrigFunctions,
2577  relinfo->ri_TrigInstrument,
2578  GetPerTupleMemoryContext(estate));
2579 
2580  if (newtuple)
2581  ereport(ERROR,
2582  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2583  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2584  }
2585 }
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
int errcode(int sqlerrcode)
Definition: elog.c:698
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5915
#define ERROR
Definition: elog.h:46
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
bool trig_delete_before_statement
Definition: reltrigger.h:69
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:157
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
int errmsg(const char *fmt,...)
Definition: elog.c:909
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
#define RelationGetRelid(relation)
Definition: rel.h:477
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSInsertTriggers()

void ExecBSInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2323 of file trigger.c.

References before_stmt_triggers_fired(), CMD_INSERT, ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetPerTupleMemoryContext, i, TriggerDesc::numtriggers, RelationGetRelid, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, Trigger::tgtype, TriggerDesc::trig_insert_before_statement, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_INSERT, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by CopyFrom(), and fireBSTriggers().

2324 {
2325  TriggerDesc *trigdesc;
2326  int i;
2327  TriggerData LocTriggerData = {0};
2328 
2329  trigdesc = relinfo->ri_TrigDesc;
2330 
2331  if (trigdesc == NULL)
2332  return;
2333  if (!trigdesc->trig_insert_before_statement)
2334  return;
2335 
2336  /* no-op if we already fired BS triggers in this context */
2338  CMD_INSERT))
2339  return;
2340 
2341  LocTriggerData.type = T_TriggerData;
2342  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2344  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2345  for (i = 0; i < trigdesc->numtriggers; i++)
2346  {
2347  Trigger *trigger = &trigdesc->triggers[i];
2348  HeapTuple newtuple;
2349 
2350  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2351  TRIGGER_TYPE_STATEMENT,
2352  TRIGGER_TYPE_BEFORE,
2353  TRIGGER_TYPE_INSERT))
2354  continue;
2355  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2356  NULL, NULL, NULL))
2357  continue;
2358 
2359  LocTriggerData.tg_trigger = trigger;
2360  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2361  i,
2362  relinfo->ri_TrigFunctions,
2363  relinfo->ri_TrigInstrument,
2364  GetPerTupleMemoryContext(estate));
2365 
2366  if (newtuple)
2367  ereport(ERROR,
2368  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2369  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2370  }
2371 }
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
int errcode(int sqlerrcode)
Definition: elog.c:698
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5915
#define ERROR
Definition: elog.h:46
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:157
TriggerEvent tg_event
Definition: trigger.h:33
bool trig_insert_before_statement
Definition: reltrigger.h:59
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:909
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
#define RelationGetRelid(relation)
Definition: rel.h:477
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSTruncateTriggers()

void ExecBSTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 3084 of file trigger.c.

References ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetPerTupleMemoryContext, i, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, Trigger::tgtype, TriggerDesc::trig_truncate_before_statement, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_TRUNCATE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecuteTruncateGuts().

3085 {
3086  TriggerDesc *trigdesc;
3087  int i;
3088  TriggerData LocTriggerData = {0};
3089 
3090  trigdesc = relinfo->ri_TrigDesc;
3091 
3092  if (trigdesc == NULL)
3093  return;
3094  if (!trigdesc->trig_truncate_before_statement)
3095  return;
3096 
3097  LocTriggerData.type = T_TriggerData;
3098  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
3100  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3101 
3102  for (i = 0; i < trigdesc->numtriggers; i++)
3103  {
3104  Trigger *trigger = &trigdesc->triggers[i];
3105  HeapTuple newtuple;
3106 
3107  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3108  TRIGGER_TYPE_STATEMENT,
3109  TRIGGER_TYPE_BEFORE,
3110  TRIGGER_TYPE_TRUNCATE))
3111  continue;
3112  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3113  NULL, NULL, NULL))
3114  continue;
3115 
3116  LocTriggerData.tg_trigger = trigger;
3117  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3118  i,
3119  relinfo->ri_TrigFunctions,
3120  relinfo->ri_TrigInstrument,
3121  GetPerTupleMemoryContext(estate));
3122 
3123  if (newtuple)
3124  ereport(ERROR,
3125  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
3126  errmsg("BEFORE STATEMENT trigger cannot return a value")));
3127  }
3128 }
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
bool trig_truncate_before_statement
Definition: reltrigger.h:72
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:157
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:94
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
int errmsg(const char *fmt,...)
Definition: elog.c:909
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSUpdateTriggers()

void ExecBSUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2769 of file trigger.c.

References Assert, before_stmt_triggers_fired(), CMD_UPDATE, ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), ExecGetAllUpdatedCols(), GetPerTupleMemoryContext, i, TriggerDesc::numtriggers, RelationGetRelid, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_RootResultRelInfo, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_updatedcols, Trigger::tgtype, TriggerDesc::trig_update_before_statement, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_UPDATE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by fireBSTriggers().

2770 {
2771  TriggerDesc *trigdesc;
2772  int i;
2773  TriggerData LocTriggerData = {0};
2774  Bitmapset *updatedCols;
2775 
2776  trigdesc = relinfo->ri_TrigDesc;
2777 
2778  if (trigdesc == NULL)
2779  return;
2780  if (!trigdesc->trig_update_before_statement)
2781  return;
2782 
2783  /* no-op if we already fired BS triggers in this context */
2785  CMD_UPDATE))
2786  return;
2787 
2788  /* statement-level triggers operate on the parent table */
2789  Assert(relinfo->ri_RootResultRelInfo == NULL);
2790 
2791  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2792 
2793  LocTriggerData.type = T_TriggerData;
2794  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2796  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2797  LocTriggerData.tg_updatedcols = updatedCols;
2798  for (i = 0; i < trigdesc->numtriggers; i++)
2799  {
2800  Trigger *trigger = &trigdesc->triggers[i];
2801  HeapTuple newtuple;
2802 
2803  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2804  TRIGGER_TYPE_STATEMENT,
2805  TRIGGER_TYPE_BEFORE,
2806  TRIGGER_TYPE_UPDATE))
2807  continue;
2808  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2809  updatedCols, NULL, NULL))
2810  continue;
2811 
2812  LocTriggerData.tg_trigger = trigger;
2813  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2814  i,
2815  relinfo->ri_TrigFunctions,
2816  relinfo->ri_TrigInstrument,
2817  GetPerTupleMemoryContext(estate));
2818 
2819  if (newtuple)
2820  ereport(ERROR,
2821  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2822  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2823  }
2824 }
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
const Bitmapset * tg_updatedcols
Definition: trigger.h:42
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1347
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
int errcode(int sqlerrcode)
Definition: elog.c:698
bool trig_update_before_statement
Definition: reltrigger.h:64
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5915
#define ERROR
Definition: elog.h:46
int16 tgtype
Definition: reltrigger.h:29
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:512
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
int errmsg(const char *fmt,...)
Definition: elog.c:909
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
#define RelationGetRelid(relation)
Definition: rel.h:477
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRDeleteTriggers()

bool ExecIRDeleteTriggers ( EState estate,
ResultRelInfo relinfo,
HeapTuple  trigtuple 
)

Definition at line 2722 of file trigger.c.

References ExecCallTriggerFunc(), ExecForceStoreHeapTuple(), ExecGetTriggerOldSlot(), GetPerTupleMemoryContext, heap_freetuple(), i, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, TriggerData::tg_trigtuple, Trigger::tgtype, TRIGGER_EVENT_DELETE, TRIGGER_EVENT_INSTEAD, TRIGGER_EVENT_ROW, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecDelete().

2724 {
2725  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2726  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2727  TriggerData LocTriggerData = {0};
2728  int i;
2729 
2730  LocTriggerData.type = T_TriggerData;
2731  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2734  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2735 
2736  ExecForceStoreHeapTuple(trigtuple, slot, false);
2737 
2738  for (i = 0; i < trigdesc->numtriggers; i++)
2739  {
2740  HeapTuple rettuple;
2741  Trigger *trigger = &trigdesc->triggers[i];
2742 
2743  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2744  TRIGGER_TYPE_ROW,
2745  TRIGGER_TYPE_INSTEAD,
2746  TRIGGER_TYPE_DELETE))
2747  continue;
2748  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2749  NULL, slot, NULL))
2750  continue;
2751 
2752  LocTriggerData.tg_trigslot = slot;
2753  LocTriggerData.tg_trigtuple = trigtuple;
2754  LocTriggerData.tg_trigger = trigger;
2755  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2756  i,
2757  relinfo->ri_TrigFunctions,
2758  relinfo->ri_TrigInstrument,
2759  GetPerTupleMemoryContext(estate));
2760  if (rettuple == NULL)
2761  return false; /* Delete was suppressed */
2762  if (rettuple != trigtuple)
2763  heap_freetuple(rettuple);
2764  }
2765  return true;
2766 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1166
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:101
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRInsertTriggers()

bool ExecIRInsertTriggers ( EState estate,
ResultRelInfo relinfo,
TupleTableSlot slot 
)

Definition at line 2476 of file trigger.c.

References ExecCallTriggerFunc(), ExecFetchSlotHeapTuple(), ExecForceStoreHeapTuple(), GetPerTupleMemoryContext, heap_freetuple(), i, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, TriggerData::tg_trigtuple, Trigger::tgtype, TRIGGER_EVENT_INSERT, TRIGGER_EVENT_INSTEAD, TRIGGER_EVENT_ROW, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by CopyFrom(), and ExecInsert().

2478 {
2479  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2480  HeapTuple newtuple = NULL;
2481  bool should_free;
2482  TriggerData LocTriggerData = {0};
2483  int i;
2484 
2485  LocTriggerData.type = T_TriggerData;
2486  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2489  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2490  for (i = 0; i < trigdesc->numtriggers; i++)
2491  {
2492  Trigger *trigger = &trigdesc->triggers[i];
2493  HeapTuple oldtuple;
2494 
2495  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2496  TRIGGER_TYPE_ROW,
2497  TRIGGER_TYPE_INSTEAD,
2498  TRIGGER_TYPE_INSERT))
2499  continue;
2500  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2501  NULL, NULL, slot))
2502  continue;
2503 
2504  if (!newtuple)
2505  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2506 
2507  LocTriggerData.tg_trigslot = slot;
2508  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2509  LocTriggerData.tg_trigger = trigger;
2510  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2511  i,
2512  relinfo->ri_TrigFunctions,
2513  relinfo->ri_TrigInstrument,
2514  GetPerTupleMemoryContext(estate));
2515  if (newtuple == NULL)
2516  {
2517  if (should_free)
2518  heap_freetuple(oldtuple);
2519  return false; /* "do nothing" */
2520  }
2521  else if (newtuple != oldtuple)
2522  {
2523  ExecForceStoreHeapTuple(newtuple, slot, false);
2524 
2525  if (should_free)
2526  heap_freetuple(oldtuple);
2527 
2528  /* signal tuple should be re-fetched if used */
2529  newtuple = NULL;
2530  }
2531  }
2532 
2533  return true;
2534 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:101
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:49
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRUpdateTriggers()

bool ExecIRUpdateTriggers ( EState estate,
ResultRelInfo relinfo,
HeapTuple  trigtuple,
TupleTableSlot slot 
)

Definition at line 3018 of file trigger.c.

References ExecCallTriggerFunc(), ExecFetchSlotHeapTuple(), ExecForceStoreHeapTuple(), ExecGetTriggerOldSlot(), GetPerTupleMemoryContext, heap_freetuple(), i, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newslot, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, TriggerData::tg_trigtuple, Trigger::tgtype, TRIGGER_EVENT_INSTEAD, TRIGGER_EVENT_ROW, TRIGGER_EVENT_UPDATE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecUpdate().

3020 {
3021  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3022  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
3023  HeapTuple newtuple = NULL;
3024  bool should_free;
3025  TriggerData LocTriggerData = {0};
3026  int i;
3027 
3028  LocTriggerData.type = T_TriggerData;
3029  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
3032  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3033 
3034  ExecForceStoreHeapTuple(trigtuple, oldslot, false);
3035 
3036  for (i = 0; i < trigdesc->numtriggers; i++)
3037  {
3038  Trigger *trigger = &trigdesc->triggers[i];
3039  HeapTuple oldtuple;
3040 
3041  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3042  TRIGGER_TYPE_ROW,
3043  TRIGGER_TYPE_INSTEAD,
3044  TRIGGER_TYPE_UPDATE))
3045  continue;
3046  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3047  NULL, oldslot, newslot))
3048  continue;
3049 
3050  if (!newtuple)
3051  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
3052 
3053  LocTriggerData.tg_trigslot = oldslot;
3054  LocTriggerData.tg_trigtuple = trigtuple;
3055  LocTriggerData.tg_newslot = newslot;
3056  LocTriggerData.tg_newtuple = oldtuple = newtuple;
3057 
3058  LocTriggerData.tg_trigger = trigger;
3059  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3060  i,
3061  relinfo->ri_TrigFunctions,
3062  relinfo->ri_TrigInstrument,
3063  GetPerTupleMemoryContext(estate));
3064  if (newtuple == NULL)
3065  {
3066  return false; /* "do nothing" */
3067  }
3068  else if (newtuple != oldtuple)
3069  {
3070  ExecForceStoreHeapTuple(newtuple, newslot, false);
3071 
3072  if (should_free)
3073  heap_freetuple(oldtuple);
3074 
3075  /* signal tuple should be re-fetched if used */
3076  newtuple = NULL;
3077  }
3078  }
3079 
3080  return true;
3081 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:411
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3261
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:447
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1166
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:101
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:49
TupleTableSlot * tg_newslot
Definition: trigger.h:39
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:438
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:538
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2231
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:441
Relation tg_relation
Definition: trigger.h:34

◆ FindTriggerIncompatibleWithInheritance()

const char* FindTriggerIncompatibleWithInheritance ( TriggerDesc trigdesc)

Definition at line 2201 of file trigger.c.

References i, TriggerDesc::numtriggers, Trigger::tgname, Trigger::tgnewtable, Trigger::tgoldtable, and TriggerDesc::triggers.

Referenced by ATExecAddInherit(), and ATExecAttachPartition().

2202 {
2203  if (trigdesc != NULL)
2204  {
2205  int i;
2206 
2207  for (i = 0; i < trigdesc->numtriggers; ++i)
2208  {
2209  Trigger *trigger = &trigdesc->triggers[i];
2210 
2211  if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
2212  return trigger->tgname;
2213  }
2214  }
2215 
2216  return NULL;
2217 }
char * tgname
Definition: reltrigger.h:27
Trigger * triggers
Definition: reltrigger.h:49
int numtriggers
Definition: reltrigger.h:50
char * tgnewtable
Definition: reltrigger.h:44
int i
char * tgoldtable
Definition: reltrigger.h:43

◆ FreeTriggerDesc()

void FreeTriggerDesc ( TriggerDesc trigdesc)

Definition at line 2069 of file trigger.c.

References i, TriggerDesc::numtriggers, pfree(), Trigger::tgargs, Trigger::tgattr, Trigger::tgconstraint, Trigger::tgconstrindid, Trigger::tgconstrrelid, Trigger::tgdeferrable, Trigger::tgenabled, Trigger::tgfoid, Trigger::tginitdeferred, Trigger::tgisclone, Trigger::tgisinternal, Trigger::tgname, Trigger::tgnargs, Trigger::tgnattr, Trigger::tgnewtable, Trigger::tgoid, Trigger::tgoldtable, Trigger::tgqual, Trigger::tgtype, and TriggerDesc::triggers.

Referenced by RelationBuildTriggers(), and RelationDestroyRelation().

2070 {
2071  Trigger *trigger;
2072  int i;
2073 
2074  if (trigdesc == NULL)
2075  return;
2076 
2077  trigger = trigdesc->triggers;
2078  for (i = 0; i < trigdesc->numtriggers; i++)
2079  {
2080  pfree(trigger->tgname);
2081  if (trigger->tgnattr > 0)
2082  pfree(trigger->tgattr);
2083  if (trigger->tgnargs > 0)
2084  {
2085  while (--(trigger->tgnargs) >= 0)
2086  pfree(trigger->tgargs[trigger->tgnargs]);
2087  pfree(trigger->tgargs);
2088  }
2089  if (trigger->tgqual)
2090  pfree(trigger->tgqual);
2091  if (trigger->tgoldtable)
2092  pfree(trigger->tgoldtable);
2093  if (trigger->tgnewtable)
2094  pfree(trigger->tgnewtable);
2095  trigger++;
2096  }
2097  pfree(trigdesc->triggers);
2098  pfree(trigdesc);
2099 }
void pfree(void *pointer)
Definition: mcxt.c:1169
char * tgqual
Definition: reltrigger.h:42
char * tgname
Definition: reltrigger.h:27
Trigger * triggers
Definition: reltrigger.h:49
int numtriggers
Definition: reltrigger.h:50
char ** tgargs
Definition: reltrigger.h:41
int16 * tgattr
Definition: reltrigger.h:40
char * tgnewtable
Definition: reltrigger.h:44
int16 tgnattr
Definition: reltrigger.h:39
int i
int16 tgnargs
Definition: reltrigger.h:38
char * tgoldtable
Definition: reltrigger.h:43

◆ get_trigger_oid()

Oid get_trigger_oid ( Oid  relid,
const char *  name,
bool  missing_ok 
)

Definition at line 1330 of file trigger.c.

References AccessShareLock, BTEqualStrategyNumber, CStringGetDatum, ereport, errcode(), errmsg(), ERROR, get_rel_name(), GETSTRUCT, HeapTupleIsValid, InvalidOid, ObjectIdGetDatum, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by get_object_address_relobject().

1331 {
1332  Relation tgrel;
1333  ScanKeyData skey[2];
1334  SysScanDesc tgscan;
1335  HeapTuple tup;
1336  Oid oid;
1337 
1338  /*
1339  * Find the trigger, verify permissions, set up object address
1340  */
1341  tgrel = table_open(TriggerRelationId, AccessShareLock);
1342 
1343  ScanKeyInit(&skey[0],
1344  Anum_pg_trigger_tgrelid,
1345  BTEqualStrategyNumber, F_OIDEQ,
1346  ObjectIdGetDatum(relid));
1347  ScanKeyInit(&skey[1],
1348  Anum_pg_trigger_tgname,
1349  BTEqualStrategyNumber, F_NAMEEQ,
1350  CStringGetDatum(trigname));
1351 
1352  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1353  NULL, 2, skey);
1354 
1355  tup = systable_getnext(tgscan);
1356 
1357  if (!HeapTupleIsValid(tup))
1358  {
1359  if (!missing_ok)
1360  ereport(ERROR,
1361  (errcode(ERRCODE_UNDEFINED_OBJECT),
1362  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1363  trigname, get_rel_name(relid))));
1364  oid = InvalidOid;
1365  }
1366  else
1367  {
1368  oid = ((Form_pg_trigger) GETSTRUCT(tup))->oid;
1369  }
1370 
1371  systable_endscan(tgscan);
1372  table_close(tgrel, AccessShareLock);
1373  return oid;
1374 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:595
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:383
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:502
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define CStringGetDatum(X)
Definition: postgres.h:622
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
int errmsg(const char *fmt,...)
Definition: elog.c:909
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ MakeTransitionCaptureState()

TransitionCaptureState* MakeTransitionCaptureState ( TriggerDesc trigdesc,
Oid  relid,
CmdType  cmdType 
)

Definition at line 4548 of file trigger.c.

References AfterTriggerEnlargeQueryState(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, CurrentResourceOwner, CurTransactionContext, CurTransactionResourceOwner, elog, ERROR, GetAfterTriggersTableData(), AfterTriggersData::maxquerydepth, MemoryContextSwitchTo(), AfterTriggersTableData::new_tuplestore, AfterTriggersTableData::old_tuplestore, palloc0(), AfterTriggersData::query_depth, TransitionCaptureState::tcs_delete_old_table, TransitionCaptureState::tcs_insert_new_table, TransitionCaptureState::tcs_private, TransitionCaptureState::tcs_update_new_table, TransitionCaptureState::tcs_update_old_table, TriggerDesc::trig_delete_old_table, TriggerDesc::trig_insert_new_table, TriggerDesc::trig_update_new_table, TriggerDesc::trig_update_old_table, tuplestore_begin_heap(), and work_mem.

Referenced by CopyFrom(), and ExecSetupTransitionCaptureState().

4549 {
4551  bool need_old,
4552  need_new;
4553  AfterTriggersTableData *table;
4554  MemoryContext oldcxt;
4555  ResourceOwner saveResourceOwner;
4556 
4557  if (trigdesc == NULL)
4558  return NULL;
4559 
4560  /* Detect which table(s) we need. */
4561  switch (cmdType)
4562  {
4563  case CMD_INSERT:
4564  need_old = false;
4565  need_new = trigdesc->trig_insert_new_table;
4566  break;
4567  case CMD_UPDATE:
4568  need_old = trigdesc->trig_update_old_table;
4569  need_new = trigdesc->trig_update_new_table;
4570  break;
4571  case CMD_DELETE:
4572  need_old = trigdesc->trig_delete_old_table;
4573  need_new = false;
4574  break;
4575  default:
4576  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4577  need_old = need_new = false; /* keep compiler quiet */
4578  break;
4579  }
4580  if (!need_old && !need_new)
4581  return NULL;
4582 
4583  /* Check state, like AfterTriggerSaveEvent. */
4584  if (afterTriggers.query_depth < 0)
4585  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4586 
4587  /* Be sure we have enough space to record events at this query depth. */
4590 
4591  /*
4592  * Find or create an AfterTriggersTableData struct to hold the
4593  * tuplestore(s). If there's a matching struct but it's marked closed,
4594  * ignore it; we need a newer one.
4595  *
4596  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4597  * allocated in the current (sub)transaction's CurTransactionContext, and
4598  * the tuplestores are managed by the (sub)transaction's resource owner.
4599  * This is sufficient lifespan because we do not allow triggers using
4600  * transition tables to be deferrable; they will be fired during
4601  * AfterTriggerEndQuery, after which it's okay to delete the data.
4602  */
4603  table = GetAfterTriggersTableData(relid, cmdType);
4604 
4605  /* Now create required tuplestore(s), if we don't have them already. */
4607  saveResourceOwner = CurrentResourceOwner;
4609 
4610  if (need_old && table->old_tuplestore == NULL)
4611  table->old_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4612  if (need_new && table->new_tuplestore == NULL)
4613  table->new_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4614 
4615  CurrentResourceOwner = saveResourceOwner;
4616  MemoryContextSwitchTo(oldcxt);
4617 
4618  /* Now build the TransitionCaptureState struct, in caller's context */
4620  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4621  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4622  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4623  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4624  state->tcs_private = table;
4625 
4626  return state;
4627 }
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:147
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:54
Tuplestorestate * old_tuplestore
Definition: trigger.c:3674
bool trig_update_new_table
Definition: reltrigger.h:77
bool trig_insert_new_table
Definition: reltrigger.h:75
struct AfterTriggersTableData * tcs_private
Definition: trigger.h:80
#define ERROR
Definition: elog.h:46
static AfterTriggersTableData * GetAfterTriggersTableData(Oid relid, CmdType cmdType)
Definition: trigger.c:4464
bool trig_update_old_table
Definition: reltrigger.h:76
Tuplestorestate * new_tuplestore
Definition: trigger.c:3675
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
void * palloc0(Size size)
Definition: mcxt.c:1093
int work_mem
Definition: globals.c:124
static void AfterTriggerEnlargeQueryState(void)
Definition: trigger.c:5090
Definition: regguts.h:317
#define elog(elevel,...)
Definition: elog.h:232
bool trig_delete_old_table
Definition: reltrigger.h:78
static AfterTriggersData afterTriggers
Definition: trigger.c:3679

◆ RelationBuildTriggers()

void RelationBuildTriggers ( Relation  relation)

Definition at line 1785 of file trigger.c.

References AccessShareLock, BTEqualStrategyNumber, CacheMemoryContext, CopyTriggerDesc(), DatumGetByteaPP, DatumGetCString, DirectFunctionCall1, elog, ERROR, fastgetattr, FreeTriggerDesc(), GETSTRUCT, HeapTupleIsValid, i, MemoryContextSwitchTo(), NameGetDatum, nameout(), TriggerDesc::numtriggers, ObjectIdGetDatum, OidIsValid, palloc(), palloc0(), pfree(), pstrdup(), RelationData::rd_att, RelationGetRelationName, RelationGetRelid, repalloc(), ScanKeyInit(), SetTriggerFlags(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), TextDatumGetCString, Trigger::tgargs, Trigger::tgattr, Trigger::tgconstraint, Trigger::tgconstrindid, Trigger::tgconstrrelid, Trigger::tgdeferrable, Trigger::tgenabled, Trigger::tgfoid, Trigger::tginitdeferred, Trigger::tgisclone, Trigger::tgisinternal, Trigger::tgname, Trigger::tgnargs, Trigger::tgnattr, Trigger::tgnewtable, Trigger::tgoid, Trigger::tgoldtable, Trigger::tgqual, Trigger::tgtype, RelationData::trigdesc, TriggerDesc::triggers, val, and VARDATA_ANY.

Referenced by RelationBuildDesc(), and RelationCacheInitializePhase3().

1786 {
1787  TriggerDesc *trigdesc;
1788  int numtrigs;
1789  int maxtrigs;
1790  Trigger *triggers;
1791  Relation tgrel;
1792  ScanKeyData skey;
1793  SysScanDesc tgscan;
1794  HeapTuple htup;
1795  MemoryContext oldContext;
1796  int i;
1797 
1798  /*
1799  * Allocate a working array to hold the triggers (the array is extended if
1800  * necessary)
1801  */
1802  maxtrigs = 16;
1803  triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
1804  numtrigs = 0;
1805 
1806  /*
1807  * Note: since we scan the triggers using TriggerRelidNameIndexId, we will
1808  * be reading the triggers in name order, except possibly during
1809  * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
1810  * ensures that triggers will be fired in name order.
1811  */
1812