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)
 
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 264 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 265 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 263 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 4500 of file trigger.c.

References AfterTriggersData::query_depth.

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

4501 {
4502  /* Increase the query stack depth */
4504 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3538

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 4768 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().

4769 {
4770  int my_level = GetCurrentTransactionNestLevel();
4771 
4772  /*
4773  * Allocate more space in the trans_stack if needed. (Note: because the
4774  * minimum nest level of a subtransaction is 2, we waste the first couple
4775  * entries of the array; not worth the notational effort to avoid it.)
4776  */
4777  while (my_level >= afterTriggers.maxtransdepth)
4778  {
4779  if (afterTriggers.maxtransdepth == 0)
4780  {
4781  /* Arbitrarily initialize for max of 8 subtransaction levels */
4784  8 * sizeof(AfterTriggersTransData));
4786  }
4787  else
4788  {
4789  /* repalloc will keep the stack in the same context */
4790  int new_alloc = afterTriggers.maxtransdepth * 2;
4791 
4794  new_alloc * sizeof(AfterTriggersTransData));
4795  afterTriggers.maxtransdepth = new_alloc;
4796  }
4797  }
4798 
4799  /*
4800  * Push the current information into the stack. The SET CONSTRAINTS state
4801  * is not saved until/unless changed. Likewise, we don't make a
4802  * per-subtransaction event context until needed.
4803  */
4804  afterTriggers.trans_stack[my_level].state = NULL;
4808 }
AfterTriggersTransData * trans_stack
Definition: trigger.c:3504
MemoryContext TopTransactionContext
Definition: mcxt.c:49
AfterTriggerEventList events
Definition: trigger.c:3519
CommandId firing_counter
Definition: trigger.c:3521
CommandId firing_counter
Definition: trigger.c:3493
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
AfterTriggerEventList events
Definition: trigger.c:3495
static AfterTriggersData afterTriggers
Definition: trigger.c:3538
SetConstraintState state
Definition: trigger.c:3518

◆ AfterTriggerBeginXact()

void AfterTriggerBeginXact ( void  )

Definition at line 4468 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().

4469 {
4470  /*
4471  * Initialize after-trigger state structure to empty
4472  */
4473  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4475 
4476  /*
4477  * Verify that there is no leftover state remaining. If these assertions
4478  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4479  * up properly.
4480  */
4481  Assert(afterTriggers.state == NULL);
4482  Assert(afterTriggers.query_stack == NULL);
4484  Assert(afterTriggers.event_cxt == NULL);
4485  Assert(afterTriggers.events.head == NULL);
4486  Assert(afterTriggers.trans_stack == NULL);
4488 }
uint32 CommandId
Definition: c.h:589
AfterTriggersTransData * trans_stack
Definition: trigger.c:3504
AfterTriggersQueryData * query_stack
Definition: trigger.c:3499
SetConstraintState state
Definition: trigger.c:3494
CommandId firing_counter
Definition: trigger.c:3493
#define Assert(condition)
Definition: c.h:792
AfterTriggerEventChunk * head
Definition: trigger.c:3387
MemoryContext event_cxt
Definition: trigger.c:3496
AfterTriggerEventList events
Definition: trigger.c:3495
static AfterTriggersData afterTriggers
Definition: trigger.c:3538

◆ AfterTriggerEndQuery()

void AfterTriggerEndQuery ( EState estate)

Definition at line 4520 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 apply_handle_delete(), apply_handle_insert(), apply_handle_update(), CopyFrom(), ExecuteTruncateGuts(), and standard_ExecutorFinish().

4521 {
4523 
4524  /* Must be inside a query, too */
4526 
4527  /*
4528  * If we never even got as far as initializing the event stack, there
4529  * certainly won't be any events, so exit quickly.
4530  */
4532  {
4534  return;
4535  }
4536 
4537  /*
4538  * Process all immediate-mode triggers queued by the query, and move the
4539  * deferred ones to the main list of deferred events.
4540  *
4541  * Notice that we decide which ones will be fired, and put the deferred
4542  * ones on the main list, before anything is actually fired. This ensures
4543  * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
4544  * IMMEDIATE: all events we have decided to defer will be available for it
4545  * to fire.
4546  *
4547  * We loop in case a trigger queues more events at the same query level.
4548  * Ordinary trigger functions, including all PL/pgSQL trigger functions,
4549  * will instead fire any triggers in a dedicated query level. Foreign key
4550  * enforcement triggers do add to the current query level, thanks to their
4551  * passing fire_triggers = false to SPI_execute_snapshot(). Other
4552  * C-language triggers might do likewise.
4553  *
4554  * If we find no firable events, we don't have to increment
4555  * firing_counter.
4556  */
4558 
4559  for (;;)
4560  {
4562  {
4563  CommandId firing_id = afterTriggers.firing_counter++;
4564  AfterTriggerEventChunk *oldtail = qs->events.tail;
4565 
4566  if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
4567  break; /* all fired */
4568 
4569  /*
4570  * Firing a trigger could result in query_stack being repalloc'd,
4571  * so we must recalculate qs after each afterTriggerInvokeEvents
4572  * call. Furthermore, it's unsafe to pass delete_ok = true here,
4573  * because that could cause afterTriggerInvokeEvents to try to
4574  * access qs->events after the stack has been repalloc'd.
4575  */
4577 
4578  /*
4579  * We'll need to scan the events list again. To reduce the cost
4580  * of doing so, get rid of completely-fired chunks. We know that
4581  * all events were marked IN_PROGRESS or DONE at the conclusion of
4582  * afterTriggerMarkEvents, so any still-interesting events must
4583  * have been added after that, and so must be in the chunk that
4584  * was then the tail chunk, or in later chunks. So, zap all
4585  * chunks before oldtail. This is approximately the same set of
4586  * events we would have gotten rid of by passing delete_ok = true.
4587  */
4588  Assert(oldtail != NULL);
4589  while (qs->events.head != oldtail)
4591  }
4592  else
4593  break;
4594  }
4595 
4596  /* Release query-level-local storage, including tuplestores if any */
4598 
4600 }
uint32 CommandId
Definition: c.h:589
static void afterTriggerDeleteHeadEventChunk(AfterTriggersQueryData *qs)
Definition: trigger.c:3823
AfterTriggersQueryData * query_stack
Definition: trigger.c:3499
AfterTriggerEventChunk * tail
Definition: trigger.c:3388
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4175
CommandId firing_counter
Definition: trigger.c:3493
#define Assert(condition)
Definition: c.h:792
AfterTriggerEventChunk * head
Definition: trigger.c:3387
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4091
AfterTriggerEventList events
Definition: trigger.c:3495
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:4611
AfterTriggerEventList events
Definition: trigger.c:3510
static AfterTriggersData afterTriggers
Definition: trigger.c:3538

◆ AfterTriggerEndSubXact()

void AfterTriggerEndSubXact ( bool  isCommit)

Definition at line 4816 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().

4817 {
4818  int my_level = GetCurrentTransactionNestLevel();
4820  AfterTriggerEvent event;
4821  AfterTriggerEventChunk *chunk;
4822  CommandId subxact_firing_id;
4823 
4824  /*
4825  * Pop the prior state if needed.
4826  */
4827  if (isCommit)
4828  {
4829  Assert(my_level < afterTriggers.maxtransdepth);
4830  /* If we saved a prior state, we don't need it anymore */
4831  state = afterTriggers.trans_stack[my_level].state;
4832  if (state != NULL)
4833  pfree(state);
4834  /* this avoids double pfree if error later: */
4835  afterTriggers.trans_stack[my_level].state = NULL;
4838  }
4839  else
4840  {
4841  /*
4842  * Aborting. It is possible subxact start failed before calling
4843  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
4844  * trans_stack levels that aren't there.
4845  */
4846  if (my_level >= afterTriggers.maxtransdepth)
4847  return;
4848 
4849  /*
4850  * Release query-level storage for queries being aborted, and restore
4851  * query_depth to its pre-subxact value. This assumes that a
4852  * subtransaction will not add events to query levels started in a
4853  * earlier transaction state.
4854  */
4856  {
4860  }
4863 
4864  /*
4865  * Restore the global deferred-event list to its former length,
4866  * discarding any events queued by the subxact.
4867  */
4869  &afterTriggers.trans_stack[my_level].events);
4870 
4871  /*
4872  * Restore the trigger state. If the saved state is NULL, then this
4873  * subxact didn't save it, so it doesn't need restoring.
4874  */
4875  state = afterTriggers.trans_stack[my_level].state;
4876  if (state != NULL)
4877  {
4879  afterTriggers.state = state;
4880  }
4881  /* this avoids double pfree if error later: */
4882  afterTriggers.trans_stack[my_level].state = NULL;
4883 
4884  /*
4885  * Scan for any remaining deferred events that were marked DONE or IN
4886  * PROGRESS by this subxact or a child, and un-mark them. We can
4887  * recognize such events because they have a firing ID greater than or
4888  * equal to the firing_counter value we saved at subtransaction start.
4889  * (This essentially assumes that the current subxact includes all
4890  * subxacts started after it.)
4891  */
4892  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
4894  {
4895  AfterTriggerShared evtshared = GetTriggerSharedData(event);
4896 
4897  if (event->ate_flags &
4899  {
4900  if (evtshared->ats_firing_id >= subxact_firing_id)
4901  event->ate_flags &=
4903  }
4904  }
4905  }
4906 }
uint32 CommandId
Definition: c.h:589
AfterTriggersTransData * trans_stack
Definition: trigger.c:3504
TriggerFlags ate_flags
Definition: trigger.c:3338
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3313
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3400
AfterTriggerEventList events
Definition: trigger.c:3519
AfterTriggersQueryData * query_stack
Definition: trigger.c:3499
CommandId firing_counter
Definition: trigger.c:3521
#define GetTriggerSharedData(evt)
Definition: trigger.c:3363
void pfree(void *pointer)
Definition: mcxt.c:1057
SetConstraintState state
Definition: trigger.c:3494
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
#define Assert(condition)
Definition: c.h:792
Definition: regguts.h:298
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:3783
CommandId ats_firing_id
Definition: trigger.c:3329
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3314
AfterTriggerEventList events
Definition: trigger.c:3495
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:4611
static AfterTriggersData afterTriggers
Definition: trigger.c:3538
SetConstraintState state
Definition: trigger.c:3518

◆ AfterTriggerEndXact()

void AfterTriggerEndXact ( bool  isCommit)

Definition at line 4720 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().

4721 {
4722  /*
4723  * Forget the pending-events list.
4724  *
4725  * Since all the info is in TopTransactionContext or children thereof, we
4726  * don't really need to do anything to reclaim memory. However, the
4727  * pending-events list could be large, and so it's useful to discard it as
4728  * soon as possible --- especially if we are aborting because we ran out
4729  * of memory for the list!
4730  */
4732  {
4734  afterTriggers.event_cxt = NULL;
4735  afterTriggers.events.head = NULL;
4736  afterTriggers.events.tail = NULL;
4737  afterTriggers.events.tailfree = NULL;
4738  }
4739 
4740  /*
4741  * Forget any subtransaction state as well. Since this can't be very
4742  * large, we let the eventual reset of TopTransactionContext free the
4743  * memory instead of doing it here.
4744  */
4745  afterTriggers.trans_stack = NULL;
4747 
4748 
4749  /*
4750  * Forget the query stack and constraint-related state information. As
4751  * with the subtransaction state information, we don't bother freeing the
4752  * memory here.
4753  */
4754  afterTriggers.query_stack = NULL;
4756  afterTriggers.state = NULL;
4757 
4758  /* No more afterTriggers manipulation until next transaction starts. */
4760 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
AfterTriggersTransData * trans_stack
Definition: trigger.c:3504
AfterTriggersQueryData * query_stack
Definition: trigger.c:3499
AfterTriggerEventChunk * tail
Definition: trigger.c:3388
SetConstraintState state
Definition: trigger.c:3494
AfterTriggerEventChunk * head
Definition: trigger.c:3387
MemoryContext event_cxt
Definition: trigger.c:3496
AfterTriggerEventList events
Definition: trigger.c:3495
static AfterTriggersData afterTriggers
Definition: trigger.c:3538

◆ AfterTriggerFireDeferred()

void AfterTriggerFireDeferred ( void  )

Definition at line 4664 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().

4665 {
4666  AfterTriggerEventList *events;
4667  bool snap_pushed = false;
4668 
4669  /* Must not be inside a query */
4671 
4672  /*
4673  * If there are any triggers to fire, make sure we have set a snapshot for
4674  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
4675  * can't assume ActiveSnapshot is valid on entry.)
4676  */
4677  events = &afterTriggers.events;
4678  if (events->head != NULL)
4679  {
4681  snap_pushed = true;
4682  }
4683 
4684  /*
4685  * Run all the remaining triggers. Loop until they are all gone, in case
4686  * some trigger queues more for us to do.
4687  */
4688  while (afterTriggerMarkEvents(events, NULL, false))
4689  {
4690  CommandId firing_id = afterTriggers.firing_counter++;
4691 
4692  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
4693  break; /* all fired */
4694  }
4695 
4696  /*
4697  * We don't bother freeing the event list, since it will go away anyway
4698  * (and more efficiently than via pfree) in AfterTriggerEndXact.
4699  */
4700 
4701  if (snap_pushed)
4703 }
uint32 CommandId
Definition: c.h:589
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4175
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:3493
#define Assert(condition)
Definition: c.h:792
AfterTriggerEventChunk * head
Definition: trigger.c:3387
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4091
AfterTriggerEventList events
Definition: trigger.c:3495
static AfterTriggersData afterTriggers
Definition: trigger.c:3538

◆ AfterTriggerPendingOnRel()

bool AfterTriggerPendingOnRel ( Oid  relid)

Definition at line 5355 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().

5356 {
5357  AfterTriggerEvent event;
5358  AfterTriggerEventChunk *chunk;
5359  int depth;
5360 
5361  /* Scan queued events */
5363  {
5364  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5365 
5366  /*
5367  * We can ignore completed events. (Even if a DONE flag is rolled
5368  * back by subxact abort, it's OK because the effects of the TRUNCATE
5369  * or whatever must get rolled back too.)
5370  */
5371  if (event->ate_flags & AFTER_TRIGGER_DONE)
5372  continue;
5373 
5374  if (evtshared->ats_relid == relid)
5375  return true;
5376  }
5377 
5378  /*
5379  * Also scan events queued by incomplete queries. This could only matter
5380  * if TRUNCATE/etc is executed by a function or trigger within an updating
5381  * query on the same relation, which is pretty perverse, but let's check.
5382  */
5383  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
5384  {
5386  {
5387  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5388 
5389  if (event->ate_flags & AFTER_TRIGGER_DONE)
5390  continue;
5391 
5392  if (evtshared->ats_relid == relid)
5393  return true;
5394  }
5395  }
5396 
5397  return false;
5398 }
TriggerFlags ate_flags
Definition: trigger.c:3338
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3313
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3400
AfterTriggersQueryData * query_stack
Definition: trigger.c:3499
#define GetTriggerSharedData(evt)
Definition: trigger.c:3363
AfterTriggerEventList events
Definition: trigger.c:3495
AfterTriggerEventList events
Definition: trigger.c:3510
static AfterTriggersData afterTriggers
Definition: trigger.c:3538

◆ AfterTriggerSetState()

void AfterTriggerSetState ( ConstraintsSetStmt stmt)

Definition at line 5040 of file trigger.c.

References AccessShareLock, afterTriggerInvokeEvents(), afterTriggerMarkEvents(), SetConstraintStateData::all_isdeferred, SetConstraintStateData::all_isset, BTEqualStrategyNumber, RangeVar::catalogname, ConstraintNameNspIndexId, ConstraintParentIndexId, 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, TriggerConstraintIndexId, and SetConstraintStateData::trigstates.

Referenced by standard_ProcessUtility().

5041 {
5042  int my_level = GetCurrentTransactionNestLevel();
5043 
5044  /* If we haven't already done so, initialize our state. */
5045  if (afterTriggers.state == NULL)
5047 
5048  /*
5049  * If in a subtransaction, and we didn't save the current state already,
5050  * save it so it can be restored if the subtransaction aborts.
5051  */
5052  if (my_level > 1 &&
5053  afterTriggers.trans_stack[my_level].state == NULL)
5054  {
5055  afterTriggers.trans_stack[my_level].state =
5057  }
5058 
5059  /*
5060  * Handle SET CONSTRAINTS ALL ...
5061  */
5062  if (stmt->constraints == NIL)
5063  {
5064  /*
5065  * Forget any previous SET CONSTRAINTS commands in this transaction.
5066  */
5068 
5069  /*
5070  * Set the per-transaction ALL state to known.
5071  */
5072  afterTriggers.state->all_isset = true;
5074  }
5075  else
5076  {
5077  Relation conrel;
5078  Relation tgrel;
5079  List *conoidlist = NIL;
5080  List *tgoidlist = NIL;
5081  ListCell *lc;
5082 
5083  /*
5084  * Handle SET CONSTRAINTS constraint-name [, ...]
5085  *
5086  * First, identify all the named constraints and make a list of their
5087  * OIDs. Since, unlike the SQL spec, we allow multiple constraints of
5088  * the same name within a schema, the specifications are not
5089  * necessarily unique. Our strategy is to target all matching
5090  * constraints within the first search-path schema that has any
5091  * matches, but disregard matches in schemas beyond the first match.
5092  * (This is a bit odd but it's the historical behavior.)
5093  *
5094  * A constraint in a partitioned table may have corresponding
5095  * constraints in the partitions. Grab those too.
5096  */
5097  conrel = table_open(ConstraintRelationId, AccessShareLock);
5098 
5099  foreach(lc, stmt->constraints)
5100  {
5101  RangeVar *constraint = lfirst(lc);
5102  bool found;
5103  List *namespacelist;
5104  ListCell *nslc;
5105 
5106  if (constraint->catalogname)
5107  {
5108  if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
5109  ereport(ERROR,
5110  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5111  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
5112  constraint->catalogname, constraint->schemaname,
5113  constraint->relname)));
5114  }
5115 
5116  /*
5117  * If we're given the schema name with the constraint, look only
5118  * in that schema. If given a bare constraint name, use the
5119  * search path to find the first matching constraint.
5120  */
5121  if (constraint->schemaname)
5122  {
5123  Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
5124  false);
5125 
5126  namespacelist = list_make1_oid(namespaceId);
5127  }
5128  else
5129  {
5130  namespacelist = fetch_search_path(true);
5131  }
5132 
5133  found = false;
5134  foreach(nslc, namespacelist)
5135  {
5136  Oid namespaceId = lfirst_oid(nslc);
5137  SysScanDesc conscan;
5138  ScanKeyData skey[2];
5139  HeapTuple tup;
5140 
5141  ScanKeyInit(&skey[0],
5142  Anum_pg_constraint_conname,
5143  BTEqualStrategyNumber, F_NAMEEQ,
5144  CStringGetDatum(constraint->relname));
5145  ScanKeyInit(&skey[1],
5146  Anum_pg_constraint_connamespace,
5147  BTEqualStrategyNumber, F_OIDEQ,
5148  ObjectIdGetDatum(namespaceId));
5149 
5150  conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
5151  true, NULL, 2, skey);
5152 
5153  while (HeapTupleIsValid(tup = systable_getnext(conscan)))
5154  {
5156 
5157  if (con->condeferrable)
5158  conoidlist = lappend_oid(conoidlist, con->oid);
5159  else if (stmt->deferred)
5160  ereport(ERROR,
5161  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5162  errmsg("constraint \"%s\" is not deferrable",
5163  constraint->relname)));
5164  found = true;
5165  }
5166 
5167  systable_endscan(conscan);
5168 
5169  /*
5170  * Once we've found a matching constraint we do not search
5171  * later parts of the search path.
5172  */
5173  if (found)
5174  break;
5175  }
5176 
5177  list_free(namespacelist);
5178 
5179  /*
5180  * Not found ?
5181  */
5182  if (!found)
5183  ereport(ERROR,
5184  (errcode(ERRCODE_UNDEFINED_OBJECT),
5185  errmsg("constraint \"%s\" does not exist",
5186  constraint->relname)));
5187  }
5188 
5189  /*
5190  * Scan for any possible descendants of the constraints. We append
5191  * whatever we find to the same list that we're scanning; this has the
5192  * effect that we create new scans for those, too, so if there are
5193  * further descendents, we'll also catch them.
5194  */
5195  foreach(lc, conoidlist)
5196  {
5197  Oid parent = lfirst_oid(lc);
5198  ScanKeyData key;
5199  SysScanDesc scan;
5200  HeapTuple tuple;
5201 
5202  ScanKeyInit(&key,
5203  Anum_pg_constraint_conparentid,
5204  BTEqualStrategyNumber, F_OIDEQ,
5205  ObjectIdGetDatum(parent));
5206 
5207  scan = systable_beginscan(conrel, ConstraintParentIndexId, true, NULL, 1, &key);
5208 
5209  while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5210  {
5212 
5213  conoidlist = lappend_oid(conoidlist, con->oid);
5214  }
5215 
5216  systable_endscan(scan);
5217  }
5218 
5219  table_close(conrel, AccessShareLock);
5220 
5221  /*
5222  * Now, locate the trigger(s) implementing each of these constraints,
5223  * and make a list of their OIDs.
5224  */
5225  tgrel = table_open(TriggerRelationId, AccessShareLock);
5226 
5227  foreach(lc, conoidlist)
5228  {
5229  Oid conoid = lfirst_oid(lc);
5230  ScanKeyData skey;
5231  SysScanDesc tgscan;
5232  HeapTuple htup;
5233 
5234  ScanKeyInit(&skey,
5235  Anum_pg_trigger_tgconstraint,
5236  BTEqualStrategyNumber, F_OIDEQ,
5237  ObjectIdGetDatum(conoid));
5238 
5239  tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
5240  NULL, 1, &skey);
5241 
5242  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
5243  {
5244  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
5245 
5246  /*
5247  * Silently skip triggers that are marked as non-deferrable in
5248  * pg_trigger. This is not an error condition, since a
5249  * deferrable RI constraint may have some non-deferrable
5250  * actions.
5251  */
5252  if (pg_trigger->tgdeferrable)
5253  tgoidlist = lappend_oid(tgoidlist, pg_trigger->oid);
5254  }
5255 
5256  systable_endscan(tgscan);
5257  }
5258 
5259  table_close(tgrel, AccessShareLock);
5260 
5261  /*
5262  * Now we can set the trigger states of individual triggers for this
5263  * xact.
5264  */
5265  foreach(lc, tgoidlist)
5266  {
5267  Oid tgoid = lfirst_oid(lc);
5269  bool found = false;
5270  int i;
5271 
5272  for (i = 0; i < state->numstates; i++)
5273  {
5274  if (state->trigstates[i].sct_tgoid == tgoid)
5275  {
5276  state->trigstates[i].sct_tgisdeferred = stmt->deferred;
5277  found = true;
5278  break;
5279  }
5280  }
5281  if (!found)
5282  {
5284  SetConstraintStateAddItem(state, tgoid, stmt->deferred);
5285  }
5286  }
5287  }
5288 
5289  /*
5290  * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
5291  * checks against that constraint must be made when the SET CONSTRAINTS
5292  * command is executed -- i.e. the effects of the SET CONSTRAINTS command
5293  * apply retroactively. We've updated the constraints state, so scan the
5294  * list of previously deferred events to fire any that have now become
5295  * immediate.
5296  *
5297  * Obviously, if this was SET ... DEFERRED then it can't have converted
5298  * any unfired events to immediate, so we need do nothing in that case.
5299  */
5300  if (!stmt->deferred)
5301  {
5303  bool snapshot_set = false;
5304 
5305  while (afterTriggerMarkEvents(events, NULL, true))
5306  {
5307  CommandId firing_id = afterTriggers.firing_counter++;
5308 
5309  /*
5310  * Make sure a snapshot has been established in case trigger
5311  * functions need one. Note that we avoid setting a snapshot if
5312  * we don't find at least one trigger that has to be fired now.
5313  * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
5314  * ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
5315  * at the start of a transaction it's not possible for any trigger
5316  * events to be queued yet.)
5317  */
5318  if (!snapshot_set)
5319  {
5321  snapshot_set = true;
5322  }
5323 
5324  /*
5325  * We can delete fired events if we are at top transaction level,
5326  * but we'd better not if inside a subtransaction, since the
5327  * subtransaction could later get rolled back.
5328  */
5329  if (afterTriggerInvokeEvents(events, firing_id, NULL,
5330  !IsSubTransaction()))
5331  break; /* all fired */
5332  }
5333 
5334  if (snapshot_set)
5336  }
5337 }
#define NIL
Definition: pg_list.h:65
uint32 CommandId
Definition: c.h:589
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2892
AfterTriggersTransData * trans_stack
Definition: trigger.c:3504
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:593
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define TriggerConstraintIndexId
Definition: pg_trigger.h:78
#define ConstraintNameNspIndexId
SetConstraintTriggerData trigstates[FLEXIBLE_ARRAY_MEMBER]
Definition: trigger.c:3267
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:704
static SetConstraintState SetConstraintStateAddItem(SetConstraintState state, Oid tgoid, bool tgisdeferred)
Definition: trigger.c:5010
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4175
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:357
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:381
char * schemaname
Definition: primnodes.h:67
char * relname
Definition: primnodes.h:68
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:500
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
SetConstraintState state
Definition: trigger.c:3494
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define CStringGetDatum(X)
Definition: postgres.h:578
static SetConstraintState SetConstraintStateCreate(int numalloc)
Definition: trigger.c:4965
#define list_make1_oid(x1)
Definition: pg_list.h:228
Oid MyDatabaseId
Definition: globals.c:86
CommandId firing_counter
Definition: trigger.c:3493
#define ereport(elevel,...)
Definition: elog.h:155
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:298
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:73
bool IsSubTransaction(void)
Definition: xact.c:4758
int errmsg(const char *fmt,...)
Definition: elog.c:915
void list_free(List *list)
Definition: list.c:1376
int i
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4091
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
AfterTriggerEventList events
Definition: trigger.c:3495
#define ConstraintParentIndexId
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:4382
static AfterTriggersData afterTriggers
Definition: trigger.c:3538
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:3518
static SetConstraintState SetConstraintStateCopy(SetConstraintState state)
Definition: trigger.c:4990

◆ CopyTriggerDesc()

TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 1873 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().

1874 {
1875  TriggerDesc *newdesc;
1876  Trigger *trigger;
1877  int i;
1878 
1879  if (trigdesc == NULL || trigdesc->numtriggers <= 0)
1880  return NULL;
1881 
1882  newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
1883  memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
1884 
1885  trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
1886  memcpy(trigger, trigdesc->triggers,
1887  trigdesc->numtriggers * sizeof(Trigger));
1888  newdesc->triggers = trigger;
1889 
1890  for (i = 0; i < trigdesc->numtriggers; i++)
1891  {
1892  trigger->tgname = pstrdup(trigger->tgname);
1893  if (trigger->tgnattr > 0)
1894  {
1895  int16 *newattr;
1896 
1897  newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
1898  memcpy(newattr, trigger->tgattr,
1899  trigger->tgnattr * sizeof(int16));
1900  trigger->tgattr = newattr;
1901  }
1902  if (trigger->tgnargs > 0)
1903  {
1904  char **newargs;
1905  int16 j;
1906 
1907  newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
1908  for (j = 0; j < trigger->tgnargs; j++)
1909  newargs[j] = pstrdup(trigger->tgargs[j]);
1910  trigger->tgargs = newargs;
1911  }
1912  if (trigger->tgqual)
1913  trigger->tgqual = pstrdup(trigger->tgqual);
1914  if (trigger->tgoldtable)
1915  trigger->tgoldtable = pstrdup(trigger->tgoldtable);
1916  if (trigger->tgnewtable)
1917  trigger->tgnewtable = pstrdup(trigger->tgnewtable);
1918  trigger++;
1919  }
1920 
1921  return newdesc;
1922 }
signed short int16
Definition: c.h:416
char * pstrdup(const char *in)
Definition: mcxt.c:1187
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:950
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 158 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(), CharGetDatum, ObjectAddress::classId, CreateTrigStmt::columns, CommandCounterIncrement(), CreateTrigStmt::constrrel, copyObject, CreateConstraintEntry(), CreateTrigger(), 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(), 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, TRIGGER_FIRES_ON_ORIGIN, TriggerOidIndexId, TriggerRelidNameIndexId, CreateTrigStmt::trigname, TupleDescAttr, values, Var::varattno, Var::varno, and CreateTrigStmt::whenClause.

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

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

◆ EnableDisableTrigger()

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

Definition at line 1542 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(), table_open(), and TriggerRelidNameIndexId.

Referenced by ATExecEnableDisableTrigger().

1544 {
1545  Relation tgrel;
1546  int nkeys;
1547  ScanKeyData keys[2];
1548  SysScanDesc tgscan;
1549  HeapTuple tuple;
1550  bool found;
1551  bool changed;
1552 
1553  /* Scan the relevant entries in pg_triggers */
1554  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1555 
1556  ScanKeyInit(&keys[0],
1557  Anum_pg_trigger_tgrelid,
1558  BTEqualStrategyNumber, F_OIDEQ,
1560  if (tgname)
1561  {
1562  ScanKeyInit(&keys[1],
1563  Anum_pg_trigger_tgname,
1564  BTEqualStrategyNumber, F_NAMEEQ,
1565  CStringGetDatum(tgname));
1566  nkeys = 2;
1567  }
1568  else
1569  nkeys = 1;
1570 
1571  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1572  NULL, nkeys, keys);
1573 
1574  found = changed = false;
1575 
1576  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1577  {
1578  Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1579 
1580  if (oldtrig->tgisinternal)
1581  {
1582  /* system trigger ... ok to process? */
1583  if (skip_system)
1584  continue;
1585  if (!superuser())
1586  ereport(ERROR,
1587  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1588  errmsg("permission denied: \"%s\" is a system trigger",
1589  NameStr(oldtrig->tgname))));
1590  }
1591 
1592  found = true;
1593 
1594  if (oldtrig->tgenabled != fires_when)
1595  {
1596  /* need to change this one ... make a copy to scribble on */
1597  HeapTuple newtup = heap_copytuple(tuple);
1598  Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1599 
1600  newtrig->tgenabled = fires_when;
1601 
1602  CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1603 
1604  heap_freetuple(newtup);
1605 
1606  changed = true;
1607  }
1608 
1609  InvokeObjectPostAlterHook(TriggerRelationId,
1610  oldtrig->oid, 0);
1611  }
1612 
1613  systable_endscan(tgscan);
1614 
1615  table_close(tgrel, RowExclusiveLock);
1616 
1617  if (tgname && !found)
1618  ereport(ERROR,
1619  (errcode(ERRCODE_UNDEFINED_OBJECT),
1620  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1621  tgname, RelationGetRelationName(rel))));
1622 
1623  /*
1624  * If we changed anything, broadcast a SI inval message to force each
1625  * backend (including our own!) to rebuild relation's relcache entry.
1626  * Otherwise they will fail to apply the change promptly.
1627  */
1628  if (changed)
1630 }
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:593
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define TriggerRelidNameIndexId
Definition: pg_trigger.h:80
int errcode(int sqlerrcode)
Definition: elog.c:704
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:381
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:500
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:302
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:73
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define NameStr(name)
Definition: c.h:669
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:457
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ ExecARDeleteTriggers()

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

Definition at line 2550 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().

2554 {
2555  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2556  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2557 
2558  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2559  (transition_capture && transition_capture->tcs_delete_old_table))
2560  {
2561  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2562  if (fdw_trigtuple == NULL)
2563  GetTupleForTrigger(estate,
2564  NULL,
2565  relinfo,
2566  tupleid,
2568  slot,
2569  NULL);
2570  else
2571  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2572 
2574  true, slot, NULL, NIL, NULL,
2575  transition_capture);
2576  }
2577 }
#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:3004
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
bool trig_delete_after_row
Definition: reltrigger.h:67
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5425
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:792

◆ ExecARInsertTriggers()

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

Definition at line 2320 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(), ExecInsert(), and ExecSimpleRelationInsert().

2323 {
2324  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2325 
2326  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2327  (transition_capture && transition_capture->tcs_insert_new_table))
2329  true, NULL, slot,
2330  recheckIndexes, NULL,
2331  transition_capture);
2332 }
bool trig_insert_after_row
Definition: reltrigger.h:57
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5425
#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 2835 of file trigger.c.

References AfterTriggerSaveEvent(), ExecClearTuple(), ExecForceStoreHeapTuple(), ExecGetTriggerOldSlot(), GetAllUpdatedColumns, 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().

2841 {
2842  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2843  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2844 
2845  ExecClearTuple(oldslot);
2846 
2847  if ((trigdesc && trigdesc->trig_update_after_row) ||
2848  (transition_capture &&
2849  (transition_capture->tcs_update_old_table ||
2850  transition_capture->tcs_update_new_table)))
2851  {
2852  /*
2853  * Note: if the UPDATE is converted into a DELETE+INSERT as part of
2854  * update-partition-key operation, then this function is also called
2855  * separately for DELETE and INSERT to capture transition table rows.
2856  * In such case, either old tuple or new tuple can be NULL.
2857  */
2858  if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
2859  GetTupleForTrigger(estate,
2860  NULL,
2861  relinfo,
2862  tupleid,
2864  oldslot,
2865  NULL);
2866  else if (fdw_trigtuple != NULL)
2867  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
2868 
2870  true, oldslot, newslot, recheckIndexes,
2871  GetAllUpdatedColumns(relinfo, estate),
2872  transition_capture);
2873  }
2874 }
#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:3004
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5425
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:77
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93

◆ ExecASDeleteTriggers()

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

Definition at line 2447 of file trigger.c.

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

Referenced by fireASTriggers().

2449 {
2450  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2451 
2452  if (trigdesc && trigdesc->trig_delete_after_statement)
2454  false, NULL, NULL, NIL, NULL, transition_capture);
2455 }
#define NIL
Definition: pg_list.h:65
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5425
bool trig_delete_after_statement
Definition: reltrigger.h:70

◆ ExecASInsertTriggers()

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

Definition at line 2233 of file trigger.c.

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

Referenced by CopyFrom(), and fireASTriggers().

2235 {
2236  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2237 
2238  if (trigdesc && trigdesc->trig_insert_after_statement)
2240  false, NULL, NULL, NIL, NULL, transition_capture);
2241 }
#define NIL
Definition: pg_list.h:65
bool trig_insert_after_statement
Definition: reltrigger.h:60
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5425
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91

◆ ExecASTruncateTriggers()

void ExecASTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2990 of file trigger.c.

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

Referenced by ExecuteTruncateGuts().

2991 {
2992  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2993 
2994  if (trigdesc && trigdesc->trig_truncate_after_statement)
2996  false, NULL, NULL, NIL, NULL, NULL);
2997 }
#define NIL
Definition: pg_list.h:65
bool trig_truncate_after_statement
Definition: reltrigger.h:73
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5425
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:94

◆ ExecASUpdateTriggers()

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

Definition at line 2682 of file trigger.c.

References AfterTriggerSaveEvent(), GetAllUpdatedColumns, NIL, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_update_after_statement, and TRIGGER_EVENT_UPDATE.

Referenced by fireASTriggers().

2684 {
2685  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2686 
2687  if (trigdesc && trigdesc->trig_update_after_statement)
2689  false, NULL, NULL, NIL,
2690  GetAllUpdatedColumns(relinfo, estate),
2691  transition_capture);
2692 }
#define NIL
Definition: pg_list.h:65
bool trig_update_after_statement
Definition: reltrigger.h:65
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5425
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:77
#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 2465 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().

2470 {
2471  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2472  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2473  bool result = true;
2474  TriggerData LocTriggerData = {0};
2475  HeapTuple trigtuple;
2476  bool should_free = false;
2477  int i;
2478 
2479  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2480  if (fdw_trigtuple == NULL)
2481  {
2482  TupleTableSlot *epqslot_candidate = NULL;
2483 
2484  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2485  LockTupleExclusive, slot, &epqslot_candidate))
2486  return false;
2487 
2488  /*
2489  * If the tuple was concurrently updated and the caller of this
2490  * function requested for the updated tuple, skip the trigger
2491  * execution.
2492  */
2493  if (epqslot_candidate != NULL && epqslot != NULL)
2494  {
2495  *epqslot = epqslot_candidate;
2496  return false;
2497  }
2498 
2499  trigtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2500 
2501  }
2502  else
2503  {
2504  trigtuple = fdw_trigtuple;
2505  ExecForceStoreHeapTuple(trigtuple, slot, false);
2506  }
2507 
2508  LocTriggerData.type = T_TriggerData;
2509  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2512  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2513  for (i = 0; i < trigdesc->numtriggers; i++)
2514  {
2515  HeapTuple newtuple;
2516  Trigger *trigger = &trigdesc->triggers[i];
2517 
2518  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2519  TRIGGER_TYPE_ROW,
2520  TRIGGER_TYPE_BEFORE,
2521  TRIGGER_TYPE_DELETE))
2522  continue;
2523  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2524  NULL, slot, NULL))
2525  continue;
2526 
2527  LocTriggerData.tg_trigslot = slot;
2528  LocTriggerData.tg_trigtuple = trigtuple;
2529  LocTriggerData.tg_trigger = trigger;
2530  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2531  i,
2532  relinfo->ri_TrigFunctions,
2533  relinfo->ri_TrigInstrument,
2534  GetPerTupleMemoryContext(estate));
2535  if (newtuple == NULL)
2536  {
2537  result = false; /* tell caller to suppress delete */
2538  break;
2539  }
2540  if (newtuple != trigtuple)
2541  heap_freetuple(newtuple);
2542  }
2543  if (should_free)
2544  heap_freetuple(trigtuple);
2545 
2546  return result;
2547 }
#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:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:3004
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
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:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:792
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
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:2090
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecBRInsertTriggers()

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

Definition at line 2244 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().

2246 {
2247  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2248  HeapTuple newtuple = NULL;
2249  bool should_free;
2250  TriggerData LocTriggerData = {0};
2251  int i;
2252 
2253  LocTriggerData.type = T_TriggerData;
2254  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2257  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2258  for (i = 0; i < trigdesc->numtriggers; i++)
2259  {
2260  Trigger *trigger = &trigdesc->triggers[i];
2261  HeapTuple oldtuple;
2262 
2263  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2264  TRIGGER_TYPE_ROW,
2265  TRIGGER_TYPE_BEFORE,
2266  TRIGGER_TYPE_INSERT))
2267  continue;
2268  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2269  NULL, NULL, slot))
2270  continue;
2271 
2272  if (!newtuple)
2273  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2274 
2275  LocTriggerData.tg_trigslot = slot;
2276  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2277  LocTriggerData.tg_trigger = trigger;
2278  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2279  i,
2280  relinfo->ri_TrigFunctions,
2281  relinfo->ri_TrigInstrument,
2282  GetPerTupleMemoryContext(estate));
2283  if (newtuple == NULL)
2284  {
2285  if (should_free)
2286  heap_freetuple(oldtuple);
2287  return false; /* "do nothing" */
2288  }
2289  else if (newtuple != oldtuple)
2290  {
2291  ExecForceStoreHeapTuple(newtuple, slot, false);
2292 
2293  /*
2294  * After a tuple in a partition goes through a trigger, the user
2295  * could have changed the partition key enough that the tuple no
2296  * longer fits the partition. Verify that.
2297  */
2298  if (trigger->tgisclone &&
2299  !ExecPartitionCheck(relinfo, slot, estate, false))
2300  ereport(ERROR,
2301  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2302  errmsg("moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported"),
2303  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2304  trigger->tgname,
2307 
2308  if (should_free)
2309  heap_freetuple(oldtuple);
2310 
2311  /* signal tuple should be re-fetched if used */
2312  newtuple = NULL;
2313  }
2314  }
2315 
2316  return true;
2317 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
int errcode(int sqlerrcode)
Definition: elog.c:704
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:45
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:3289
int errdetail(const char *fmt,...)
Definition: elog.c:1048
#define RelationGetRelationName(relation)
Definition: rel.h:491
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:155
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:915
NodeTag type
Definition: trigger.h:32
int i
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1679
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2090
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34
#define RelationGetNamespace(relation)
Definition: rel.h:498

◆ ExecBRUpdateTriggers()

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

Definition at line 2695 of file trigger.c.

References Assert, ereport, errcode(), errdetail(), errmsg(), ERROR, ExecCallTriggerFunc(), ExecCopySlot(), ExecFetchSlotHeapTuple(), ExecFilterJunk(), ExecForceStoreHeapTuple(), ExecGetTriggerOldSlot(), ExecMaterializeSlot(), ExecPartitionCheck(), ExecUpdateLockMode(), get_namespace_name(), GetAllUpdatedColumns, GetPerTupleMemoryContext, GetTupleForTrigger(), heap_freetuple(), HeapTupleIsValid, i, ItemPointerIsValid, TriggerDesc::numtriggers, RelationGetNamespace, RelationGetRelationName, ResultRelInfo::ri_junkFilter, 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::tgisclone, Trigger::tgname, Trigger::tgtype, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_ROW, TRIGGER_EVENT_UPDATE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecSimpleRelationUpdate(), and ExecUpdate().

2700 {
2701  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2702  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2703  HeapTuple newtuple = NULL;
2704  HeapTuple trigtuple;
2705  bool should_free_trig = false;
2706  bool should_free_new = false;
2707  TriggerData LocTriggerData = {0};
2708  int i;
2709  Bitmapset *updatedCols;
2710  LockTupleMode lockmode;
2711 
2712  /* Determine lock mode to use */
2713  lockmode = ExecUpdateLockMode(estate, relinfo);
2714 
2715  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2716  if (fdw_trigtuple == NULL)
2717  {
2718  TupleTableSlot *epqslot_candidate = NULL;
2719 
2720  /* get a copy of the on-disk tuple we are planning to update */
2721  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2722  lockmode, oldslot, &epqslot_candidate))
2723  return false; /* cancel the update action */
2724 
2725  /*
2726  * In READ COMMITTED isolation level it's possible that target tuple
2727  * was changed due to concurrent update. In that case we have a raw
2728  * subplan output tuple in epqslot_candidate, and need to run it
2729  * through the junk filter to produce an insertable tuple.
2730  *
2731  * Caution: more than likely, the passed-in slot is the same as the
2732  * junkfilter's output slot, so we are clobbering the original value
2733  * of slottuple by doing the filtering. This is OK since neither we
2734  * nor our caller have any more interest in the prior contents of that
2735  * slot.
2736  */
2737  if (epqslot_candidate != NULL)
2738  {
2739  TupleTableSlot *epqslot_clean;
2740 
2741  epqslot_clean = ExecFilterJunk(relinfo->ri_junkFilter, epqslot_candidate);
2742 
2743  if (newslot != epqslot_clean)
2744  ExecCopySlot(newslot, epqslot_clean);
2745  }
2746 
2747  trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
2748  }
2749  else
2750  {
2751  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
2752  trigtuple = fdw_trigtuple;
2753  }
2754 
2755  LocTriggerData.type = T_TriggerData;
2756  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2759  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2760  updatedCols = GetAllUpdatedColumns(relinfo, estate);
2761  LocTriggerData.tg_updatedcols = updatedCols;
2762  for (i = 0; i < trigdesc->numtriggers; i++)
2763  {
2764  Trigger *trigger = &trigdesc->triggers[i];
2765  HeapTuple oldtuple;
2766 
2767  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2768  TRIGGER_TYPE_ROW,
2769  TRIGGER_TYPE_BEFORE,
2770  TRIGGER_TYPE_UPDATE))
2771  continue;
2772  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2773  updatedCols, oldslot, newslot))
2774  continue;
2775 
2776  if (!newtuple)
2777  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
2778 
2779  LocTriggerData.tg_trigslot = oldslot;
2780  LocTriggerData.tg_trigtuple = trigtuple;
2781  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2782  LocTriggerData.tg_newslot = newslot;
2783  LocTriggerData.tg_trigger = trigger;
2784  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2785  i,
2786  relinfo->ri_TrigFunctions,
2787  relinfo->ri_TrigInstrument,
2788  GetPerTupleMemoryContext(estate));
2789 
2790  if (newtuple == NULL)
2791  {
2792  if (should_free_trig)
2793  heap_freetuple(trigtuple);
2794  if (should_free_new)
2795  heap_freetuple(oldtuple);
2796  return false; /* "do nothing" */
2797  }
2798  else if (newtuple != oldtuple)
2799  {
2800  ExecForceStoreHeapTuple(newtuple, newslot, false);
2801 
2802  if (trigger->tgisclone &&
2803  !ExecPartitionCheck(relinfo, newslot, estate, false))
2804  ereport(ERROR,
2805  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2806  errmsg("moving row to another partition during a BEFORE trigger is not supported"),
2807  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2808  trigger->tgname,
2811 
2812  /*
2813  * If the tuple returned by the trigger / being stored, is the old
2814  * row version, and the heap tuple passed to the trigger was
2815  * allocated locally, materialize the slot. Otherwise we might
2816  * free it while still referenced by the slot.
2817  */
2818  if (should_free_trig && newtuple == trigtuple)
2819  ExecMaterializeSlot(newslot);
2820 
2821  if (should_free_new)
2822  heap_freetuple(oldtuple);
2823 
2824  /* signal tuple should be re-fetched if used */
2825  newtuple = NULL;
2826  }
2827  }
2828  if (should_free_trig)
2829  heap_freetuple(trigtuple);
2830 
2831  return true;
2832 }
#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
JunkFilter * ri_junkFilter
Definition: execnodes.h:465
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
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:3120
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:3004
const Bitmapset * tg_updatedcols
Definition: trigger.h:42
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
int errcode(int sqlerrcode)
Definition: elog.c:704
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:45
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:3289
int errdetail(const char *fmt,...)
Definition: elog.c:1048
#define RelationGetRelationName(relation)
Definition: rel.h:491
TupleTableSlot * tg_newslot
Definition: trigger.h:39
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
bool tgisclone
Definition: reltrigger.h:32
int numtriggers
Definition: reltrigger.h:50
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:287
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:792
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2217
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:77
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
int errmsg(const char *fmt,...)
Definition: elog.c:915
NodeTag type
Definition: trigger.h:32
int i
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1679
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2090
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34
#define RelationGetNamespace(relation)
Definition: rel.h:498

◆ ExecBSDeleteTriggers()

void ExecBSDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2396 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().

2397 {
2398  TriggerDesc *trigdesc;
2399  int i;
2400  TriggerData LocTriggerData = {0};
2401 
2402  trigdesc = relinfo->ri_TrigDesc;
2403 
2404  if (trigdesc == NULL)
2405  return;
2406  if (!trigdesc->trig_delete_before_statement)
2407  return;
2408 
2409  /* no-op if we already fired BS triggers in this context */
2411  CMD_DELETE))
2412  return;
2413 
2414  LocTriggerData.type = T_TriggerData;
2415  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2417  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2418  for (i = 0; i < trigdesc->numtriggers; i++)
2419  {
2420  Trigger *trigger = &trigdesc->triggers[i];
2421  HeapTuple newtuple;
2422 
2423  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2424  TRIGGER_TYPE_STATEMENT,
2425  TRIGGER_TYPE_BEFORE,
2426  TRIGGER_TYPE_DELETE))
2427  continue;
2428  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2429  NULL, NULL, NULL))
2430  continue;
2431 
2432  LocTriggerData.tg_trigger = trigger;
2433  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2434  i,
2435  relinfo->ri_TrigFunctions,
2436  relinfo->ri_TrigInstrument,
2437  GetPerTupleMemoryContext(estate));
2438 
2439  if (newtuple)
2440  ereport(ERROR,
2441  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2442  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2443  }
2444 }
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
int errcode(int sqlerrcode)
Definition: elog.c:704
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5758
#define ERROR
Definition: elog.h:45
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:424
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:155
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
int errmsg(const char *fmt,...)
Definition: elog.c:915
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:2090
#define RelationGetRelid(relation)
Definition: rel.h:457
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSInsertTriggers()

void ExecBSInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2182 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().

2183 {
2184  TriggerDesc *trigdesc;
2185  int i;
2186  TriggerData LocTriggerData = {0};
2187 
2188  trigdesc = relinfo->ri_TrigDesc;
2189 
2190  if (trigdesc == NULL)
2191  return;
2192  if (!trigdesc->trig_insert_before_statement)
2193  return;
2194 
2195  /* no-op if we already fired BS triggers in this context */
2197  CMD_INSERT))
2198  return;
2199 
2200  LocTriggerData.type = T_TriggerData;
2201  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2203  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2204  for (i = 0; i < trigdesc->numtriggers; i++)
2205  {
2206  Trigger *trigger = &trigdesc->triggers[i];
2207  HeapTuple newtuple;
2208 
2209  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2210  TRIGGER_TYPE_STATEMENT,
2211  TRIGGER_TYPE_BEFORE,
2212  TRIGGER_TYPE_INSERT))
2213  continue;
2214  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2215  NULL, NULL, NULL))
2216  continue;
2217 
2218  LocTriggerData.tg_trigger = trigger;
2219  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2220  i,
2221  relinfo->ri_TrigFunctions,
2222  relinfo->ri_TrigInstrument,
2223  GetPerTupleMemoryContext(estate));
2224 
2225  if (newtuple)
2226  ereport(ERROR,
2227  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2228  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2229  }
2230 }
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
int errcode(int sqlerrcode)
Definition: elog.c:704
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5758
#define ERROR
Definition: elog.h:45
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:424
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:155
TriggerEvent tg_event
Definition: trigger.h:33
bool trig_insert_before_statement
Definition: reltrigger.h:59
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:915
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:2090
#define RelationGetRelid(relation)
Definition: rel.h:457
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSTruncateTriggers()

void ExecBSTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2943 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().

2944 {
2945  TriggerDesc *trigdesc;
2946  int i;
2947  TriggerData LocTriggerData = {0};
2948 
2949  trigdesc = relinfo->ri_TrigDesc;
2950 
2951  if (trigdesc == NULL)
2952  return;
2953  if (!trigdesc->trig_truncate_before_statement)
2954  return;
2955 
2956  LocTriggerData.type = T_TriggerData;
2957  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
2959  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2960 
2961  for (i = 0; i < trigdesc->numtriggers; i++)
2962  {
2963  Trigger *trigger = &trigdesc->triggers[i];
2964  HeapTuple newtuple;
2965 
2966  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2967  TRIGGER_TYPE_STATEMENT,
2968  TRIGGER_TYPE_BEFORE,
2969  TRIGGER_TYPE_TRUNCATE))
2970  continue;
2971  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2972  NULL, NULL, NULL))
2973  continue;
2974 
2975  LocTriggerData.tg_trigger = trigger;
2976  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2977  i,
2978  relinfo->ri_TrigFunctions,
2979  relinfo->ri_TrigInstrument,
2980  GetPerTupleMemoryContext(estate));
2981 
2982  if (newtuple)
2983  ereport(ERROR,
2984  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2985  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2986  }
2987 }
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
int errcode(int sqlerrcode)
Definition: elog.c:704
#define ERROR
Definition: elog.h:45
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:424
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:155
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:94
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
int errmsg(const char *fmt,...)
Definition: elog.c:915
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:2090
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSUpdateTriggers()

void ExecBSUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2627 of file trigger.c.

References before_stmt_triggers_fired(), CMD_UPDATE, ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetAllUpdatedColumns, 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, 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().

2628 {
2629  TriggerDesc *trigdesc;
2630  int i;
2631  TriggerData LocTriggerData = {0};
2632  Bitmapset *updatedCols;
2633 
2634  trigdesc = relinfo->ri_TrigDesc;
2635 
2636  if (trigdesc == NULL)
2637  return;
2638  if (!trigdesc->trig_update_before_statement)
2639  return;
2640 
2641  /* no-op if we already fired BS triggers in this context */
2643  CMD_UPDATE))
2644  return;
2645 
2646  updatedCols = GetAllUpdatedColumns(relinfo, estate);
2647 
2648  LocTriggerData.type = T_TriggerData;
2649  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2651  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2652  LocTriggerData.tg_updatedcols = updatedCols;
2653  for (i = 0; i < trigdesc->numtriggers; i++)
2654  {
2655  Trigger *trigger = &trigdesc->triggers[i];
2656  HeapTuple newtuple;
2657 
2658  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2659  TRIGGER_TYPE_STATEMENT,
2660  TRIGGER_TYPE_BEFORE,
2661  TRIGGER_TYPE_UPDATE))
2662  continue;
2663  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2664  updatedCols, NULL, NULL))
2665  continue;
2666 
2667  LocTriggerData.tg_trigger = trigger;
2668  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2669  i,
2670  relinfo->ri_TrigFunctions,
2671  relinfo->ri_TrigInstrument,
2672  GetPerTupleMemoryContext(estate));
2673 
2674  if (newtuple)
2675  ereport(ERROR,
2676  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2677  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2678  }
2679 }
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
const Bitmapset * tg_updatedcols
Definition: trigger.h:42
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
int errcode(int sqlerrcode)
Definition: elog.c:704
bool trig_update_before_statement
Definition: reltrigger.h:64
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5758
#define ERROR
Definition: elog.h:45
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:424
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:155
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:77
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
int errmsg(const char *fmt,...)
Definition: elog.c:915
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:2090
#define RelationGetRelid(relation)
Definition: rel.h:457
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRDeleteTriggers()

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

Definition at line 2580 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().

2582 {
2583  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2584  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2585  TriggerData LocTriggerData = {0};
2586  int i;
2587 
2588  LocTriggerData.type = T_TriggerData;
2589  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2592  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2593 
2594  ExecForceStoreHeapTuple(trigtuple, slot, false);
2595 
2596  for (i = 0; i < trigdesc->numtriggers; i++)
2597  {
2598  HeapTuple rettuple;
2599  Trigger *trigger = &trigdesc->triggers[i];
2600 
2601  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2602  TRIGGER_TYPE_ROW,
2603  TRIGGER_TYPE_INSTEAD,
2604  TRIGGER_TYPE_DELETE))
2605  continue;
2606  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2607  NULL, slot, NULL))
2608  continue;
2609 
2610  LocTriggerData.tg_trigslot = slot;
2611  LocTriggerData.tg_trigtuple = trigtuple;
2612  LocTriggerData.tg_trigger = trigger;
2613  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2614  i,
2615  relinfo->ri_TrigFunctions,
2616  relinfo->ri_TrigInstrument,
2617  GetPerTupleMemoryContext(estate));
2618  if (rettuple == NULL)
2619  return false; /* Delete was suppressed */
2620  if (rettuple != trigtuple)
2621  heap_freetuple(rettuple);
2622  }
2623  return true;
2624 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
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:424
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:514
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:2090
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRInsertTriggers()

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

Definition at line 2335 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().

2337 {
2338  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2339  HeapTuple newtuple = NULL;
2340  bool should_free;
2341  TriggerData LocTriggerData = {0};
2342  int i;
2343 
2344  LocTriggerData.type = T_TriggerData;
2345  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2348  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2349  for (i = 0; i < trigdesc->numtriggers; i++)
2350  {
2351  Trigger *trigger = &trigdesc->triggers[i];
2352  HeapTuple oldtuple;
2353 
2354  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2355  TRIGGER_TYPE_ROW,
2356  TRIGGER_TYPE_INSTEAD,
2357  TRIGGER_TYPE_INSERT))
2358  continue;
2359  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2360  NULL, NULL, slot))
2361  continue;
2362 
2363  if (!newtuple)
2364  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2365 
2366  LocTriggerData.tg_trigslot = slot;
2367  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2368  LocTriggerData.tg_trigger = trigger;
2369  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2370  i,
2371  relinfo->ri_TrigFunctions,
2372  relinfo->ri_TrigInstrument,
2373  GetPerTupleMemoryContext(estate));
2374  if (newtuple == NULL)
2375  {
2376  if (should_free)
2377  heap_freetuple(oldtuple);
2378  return false; /* "do nothing" */
2379  }
2380  else if (newtuple != oldtuple)
2381  {
2382  ExecForceStoreHeapTuple(newtuple, slot, false);
2383 
2384  if (should_free)
2385  heap_freetuple(oldtuple);
2386 
2387  /* signal tuple should be re-fetched if used */
2388  newtuple = NULL;
2389  }
2390  }
2391 
2392  return true;
2393 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
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:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:514
#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:2090
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRUpdateTriggers()

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

Definition at line 2877 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().

2879 {
2880  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2881  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2882  HeapTuple newtuple = NULL;
2883  bool should_free;
2884  TriggerData LocTriggerData = {0};
2885  int i;
2886 
2887  LocTriggerData.type = T_TriggerData;
2888  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2891  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2892 
2893  ExecForceStoreHeapTuple(trigtuple, oldslot, false);
2894 
2895  for (i = 0; i < trigdesc->numtriggers; i++)
2896  {
2897  Trigger *trigger = &trigdesc->triggers[i];
2898  HeapTuple oldtuple;
2899 
2900  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2901  TRIGGER_TYPE_ROW,
2902  TRIGGER_TYPE_INSTEAD,
2903  TRIGGER_TYPE_UPDATE))
2904  continue;
2905  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2906  NULL, oldslot, newslot))
2907  continue;
2908 
2909  if (!newtuple)
2910  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
2911 
2912  LocTriggerData.tg_trigslot = oldslot;
2913  LocTriggerData.tg_trigtuple = trigtuple;
2914  LocTriggerData.tg_newslot = newslot;
2915  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2916 
2917  LocTriggerData.tg_trigger = trigger;
2918  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2919  i,
2920  relinfo->ri_TrigFunctions,
2921  relinfo->ri_TrigInstrument,
2922  GetPerTupleMemoryContext(estate));
2923  if (newtuple == NULL)
2924  {
2925  return false; /* "do nothing" */
2926  }
2927  else if (newtuple != oldtuple)
2928  {
2929  ExecForceStoreHeapTuple(newtuple, newslot, false);
2930 
2931  if (should_free)
2932  heap_freetuple(oldtuple);
2933 
2934  /* signal tuple should be re-fetched if used */
2935  newtuple = NULL;
2936  }
2937  }
2938 
2939  return true;
2940 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3120
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
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:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:514
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:2090
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ FindTriggerIncompatibleWithInheritance()

const char* FindTriggerIncompatibleWithInheritance ( TriggerDesc trigdesc)

Definition at line 2060 of file trigger.c.

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

Referenced by ATExecAddInherit(), and ATExecAttachPartition().

2061 {
2062  if (trigdesc != NULL)
2063  {
2064  int i;
2065 
2066  for (i = 0; i < trigdesc->numtriggers; ++i)
2067  {
2068  Trigger *trigger = &trigdesc->triggers[i];
2069 
2070  if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
2071  return trigger->tgname;
2072  }
2073  }
2074 
2075  return NULL;
2076 }
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 1928 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().

1929 {
1930  Trigger *trigger;
1931  int i;
1932 
1933  if (trigdesc == NULL)
1934  return;
1935 
1936  trigger = trigdesc->triggers;
1937  for (i = 0; i < trigdesc->numtriggers; i++)
1938  {
1939  pfree(trigger->tgname);
1940  if (trigger->tgnattr > 0)
1941  pfree(trigger->tgattr);
1942  if (trigger->tgnargs > 0)
1943  {
1944  while (--(trigger->tgnargs) >= 0)
1945  pfree(trigger->tgargs[trigger->tgnargs]);
1946  pfree(trigger->tgargs);
1947  }
1948  if (trigger->tgqual)
1949  pfree(trigger->tgqual);
1950  if (trigger->tgoldtable)
1951  pfree(trigger->tgoldtable);
1952  if (trigger->tgnewtable)
1953  pfree(trigger->tgnewtable);
1954  trigger++;
1955  }
1956  pfree(trigdesc->triggers);
1957  pfree(trigdesc);
1958 }
void pfree(void *pointer)
Definition: mcxt.c:1057
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 1312 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(), table_open(), and TriggerRelidNameIndexId.

Referenced by get_object_address_relobject().

1313 {
1314  Relation tgrel;
1315  ScanKeyData skey[2];
1316  SysScanDesc tgscan;
1317  HeapTuple tup;
1318  Oid oid;
1319 
1320  /*
1321  * Find the trigger, verify permissions, set up object address
1322  */
1323  tgrel = table_open(TriggerRelationId, AccessShareLock);
1324 
1325  ScanKeyInit(&skey[0],
1326  Anum_pg_trigger_tgrelid,
1327  BTEqualStrategyNumber, F_OIDEQ,
1328  ObjectIdGetDatum(relid));
1329  ScanKeyInit(&skey[1],
1330  Anum_pg_trigger_tgname,
1331  BTEqualStrategyNumber, F_NAMEEQ,
1332  CStringGetDatum(trigname));
1333 
1334  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1335  NULL, 2, skey);
1336 
1337  tup = systable_getnext(tgscan);
1338 
1339  if (!HeapTupleIsValid(tup))
1340  {
1341  if (!missing_ok)
1342  ereport(ERROR,
1343  (errcode(ERRCODE_UNDEFINED_OBJECT),
1344  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1345  trigname, get_rel_name(relid))));
1346  oid = InvalidOid;
1347  }
1348  else
1349  {
1350  oid = ((Form_pg_trigger) GETSTRUCT(tup))->oid;
1351  }
1352 
1353  systable_endscan(tgscan);
1354  table_close(tgrel, AccessShareLock);
1355  return oid;
1356 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:593
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define TriggerRelidNameIndexId
Definition: pg_trigger.h:80
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:704
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:381
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:500
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:45
#define CStringGetDatum(X)
Definition: postgres.h:578
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:73
int errmsg(const char *fmt,...)
Definition: elog.c:915
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:1872
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ MakeTransitionCaptureState()

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

Definition at line 4378 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().

4379 {
4381  bool need_old,
4382  need_new;
4383  AfterTriggersTableData *table;
4384  MemoryContext oldcxt;
4385  ResourceOwner saveResourceOwner;
4386 
4387  if (trigdesc == NULL)
4388  return NULL;
4389 
4390  /* Detect which table(s) we need. */
4391  switch (cmdType)
4392  {
4393  case CMD_INSERT:
4394  need_old = false;
4395  need_new = trigdesc->trig_insert_new_table;
4396  break;
4397  case CMD_UPDATE:
4398  need_old = trigdesc->trig_update_old_table;
4399  need_new = trigdesc->trig_update_new_table;
4400  break;
4401  case CMD_DELETE:
4402  need_old = trigdesc->trig_delete_old_table;
4403  need_new = false;
4404  break;
4405  default:
4406  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4407  need_old = need_new = false; /* keep compiler quiet */
4408  break;
4409  }
4410  if (!need_old && !need_new)
4411  return NULL;
4412 
4413  /* Check state, like AfterTriggerSaveEvent. */
4414  if (afterTriggers.query_depth < 0)
4415  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4416 
4417  /* Be sure we have enough space to record events at this query depth. */
4420 
4421  /*
4422  * Find or create an AfterTriggersTableData struct to hold the
4423  * tuplestore(s). If there's a matching struct but it's marked closed,
4424  * ignore it; we need a newer one.
4425  *
4426  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4427  * allocated in the current (sub)transaction's CurTransactionContext, and
4428  * the tuplestores are managed by the (sub)transaction's resource owner.
4429  * This is sufficient lifespan because we do not allow triggers using
4430  * transition tables to be deferrable; they will be fired during
4431  * AfterTriggerEndQuery, after which it's okay to delete the data.
4432  */
4433  table = GetAfterTriggersTableData(relid, cmdType);
4434 
4435  /* Now create required tuplestore(s), if we don't have them already. */
4437  saveResourceOwner = CurrentResourceOwner;
4439 
4440  if (need_old && table->old_tuplestore == NULL)
4441  table->old_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4442  if (need_new && table->new_tuplestore == NULL)
4443  table->new_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4444 
4445  CurrentResourceOwner = saveResourceOwner;
4446  MemoryContextSwitchTo(oldcxt);
4447 
4448  /* Now build the TransitionCaptureState struct, in caller's context */
4450  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4451  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4452  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4453  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4454  state->tcs_private = table;
4455 
4456  return state;
4457 }
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:145
ResourceOwner CurrentResourceOwner
Definition: resowner.c:144
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
Tuplestorestate * old_tuplestore
Definition: trigger.c:3533
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:45
static AfterTriggersTableData * GetAfterTriggersTableData(Oid relid, CmdType cmdType)
Definition: trigger.c:4319
bool trig_update_old_table
Definition: reltrigger.h:76
Tuplestorestate * new_tuplestore
Definition: trigger.c:3534
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
void * palloc0(Size size)
Definition: mcxt.c:981
int work_mem
Definition: globals.c:122
static void AfterTriggerEnlargeQueryState(void)
Definition: trigger.c:4918
Definition: regguts.h:298
#define elog(elevel,...)
Definition: elog.h:228
bool trig_delete_old_table
Definition: reltrigger.h:78
static AfterTriggersData afterTriggers
Definition: trigger.c:3538

◆ RelationBuildTriggers()

void RelationBuildTriggers ( Relation  relation)

Definition at line 1644 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, TriggerRelidNameIndexId, TriggerDesc::triggers, val, and VARDATA_ANY.

Referenced by RelationBuildDesc(), and RelationCacheInitializePhase3().

1645 {
1646  TriggerDesc *trigdesc;
1647  int numtrigs;
1648  int maxtrigs;
1649  Trigger *triggers;
1650  Relation tgrel;
1651  ScanKeyData skey;
1652  SysScanDesc tgscan;
1653  HeapTuple htup;
1654  MemoryContext oldContext;
1655  int i;
1656 
1657  /*
1658  * Allocate a working array to hold the triggers (the array is extended if
1659  * necessary)
1660  */
1661  maxtrigs = 16;
1662  triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
1663  numtrigs = 0;
1664 
1665  /*
1666  * Note: since we scan the triggers using TriggerRelidNameIndexId, we will
1667  * be reading the triggers in name order, except possibly dur