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

Go to the source code of this file.

Data Structures

struct  TriggerData
 
struct  TransitionCaptureState
 

Macros

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

Typedefs

typedef uint32 TriggerEvent
 
typedef struct TriggerData TriggerData
 
typedef struct TransitionCaptureState TransitionCaptureState
 

Functions

ObjectAddress CreateTrigger (CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition)
 
ObjectAddress CreateTriggerFiringOn (CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition, char trigger_fires_when)
 
void TriggerSetParentTrigger (Relation trigRel, Oid childTrigId, Oid parentTrigId, Oid childTableId)
 
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 is_crosspart_update)
 
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, TM_FailureData *tmfdp)
 
void ExecARUpdateTriggers (EState *estate, ResultRelInfo *relinfo, ResultRelInfo *src_partinfo, ResultRelInfo *dst_partinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture, bool is_crosspart_update)
 
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 107 of file trigger.h.

◆ AFTER_TRIGGER_INITDEFERRED

#define AFTER_TRIGGER_INITDEFERRED   0x00000040

Definition at line 108 of file trigger.h.

◆ CALLED_AS_TRIGGER

#define CALLED_AS_TRIGGER (   fcinfo)     ((fcinfo)->context != NULL && IsA((fcinfo)->context, TriggerData))

Definition at line 26 of file trigger.h.

◆ RI_TRIGGER_FK

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

Definition at line 279 of file trigger.h.

◆ RI_TRIGGER_NONE

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

Definition at line 280 of file trigger.h.

◆ RI_TRIGGER_PK

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

Definition at line 278 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_LOCAL

#define SESSION_REPLICATION_ROLE_LOCAL   2

Definition at line 142 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_ORIGIN

#define SESSION_REPLICATION_ROLE_ORIGIN   0

Definition at line 140 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_REPLICA

#define SESSION_REPLICATION_ROLE_REPLICA   1

Definition at line 141 of file trigger.h.

◆ TRIGGER_DISABLED

#define TRIGGER_DISABLED   'D'

Definition at line 152 of file trigger.h.

◆ TRIGGER_EVENT_AFTER

#define TRIGGER_EVENT_AFTER   0x00000000

Definition at line 101 of file trigger.h.

◆ TRIGGER_EVENT_BEFORE

#define TRIGGER_EVENT_BEFORE   0x00000008

Definition at line 100 of file trigger.h.

◆ TRIGGER_EVENT_DELETE

#define TRIGGER_EVENT_DELETE   0x00000001

Definition at line 93 of file trigger.h.

◆ TRIGGER_EVENT_INSERT

#define TRIGGER_EVENT_INSERT   0x00000000

Definition at line 92 of file trigger.h.

◆ TRIGGER_EVENT_INSTEAD

#define TRIGGER_EVENT_INSTEAD   0x00000010

Definition at line 102 of file trigger.h.

◆ TRIGGER_EVENT_OPMASK

#define TRIGGER_EVENT_OPMASK   0x00000003

Definition at line 96 of file trigger.h.

◆ TRIGGER_EVENT_ROW

#define TRIGGER_EVENT_ROW   0x00000004

Definition at line 98 of file trigger.h.

◆ TRIGGER_EVENT_TIMINGMASK

#define TRIGGER_EVENT_TIMINGMASK   0x00000018

Definition at line 103 of file trigger.h.

◆ TRIGGER_EVENT_TRUNCATE

#define TRIGGER_EVENT_TRUNCATE   0x00000003

Definition at line 95 of file trigger.h.

◆ TRIGGER_EVENT_UPDATE

#define TRIGGER_EVENT_UPDATE   0x00000002

Definition at line 94 of file trigger.h.

◆ TRIGGER_FIRED_AFTER

#define TRIGGER_FIRED_AFTER (   event)     (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_AFTER)

Definition at line 131 of file trigger.h.

◆ TRIGGER_FIRED_BEFORE

#define TRIGGER_FIRED_BEFORE (   event)     (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_BEFORE)

Definition at line 128 of file trigger.h.

◆ TRIGGER_FIRED_BY_DELETE

#define TRIGGER_FIRED_BY_DELETE (   event)     (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_DELETE)

Definition at line 113 of file trigger.h.

◆ TRIGGER_FIRED_BY_INSERT

#define TRIGGER_FIRED_BY_INSERT (   event)     (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_INSERT)

Definition at line 110 of file trigger.h.

◆ TRIGGER_FIRED_BY_TRUNCATE

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

Definition at line 119 of file trigger.h.

◆ TRIGGER_FIRED_BY_UPDATE

#define TRIGGER_FIRED_BY_UPDATE (   event)     (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_UPDATE)

Definition at line 116 of file trigger.h.

◆ TRIGGER_FIRED_FOR_ROW

#define TRIGGER_FIRED_FOR_ROW (   event)     ((event) & TRIGGER_EVENT_ROW)

Definition at line 122 of file trigger.h.

◆ TRIGGER_FIRED_FOR_STATEMENT

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

Definition at line 125 of file trigger.h.

◆ TRIGGER_FIRED_INSTEAD

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

Definition at line 134 of file trigger.h.

◆ TRIGGER_FIRES_ALWAYS

#define TRIGGER_FIRES_ALWAYS   'A'

Definition at line 150 of file trigger.h.

◆ TRIGGER_FIRES_ON_ORIGIN

#define TRIGGER_FIRES_ON_ORIGIN   'O'

Definition at line 149 of file trigger.h.

◆ TRIGGER_FIRES_ON_REPLICA

#define TRIGGER_FIRES_ON_REPLICA   'R'

Definition at line 151 of file trigger.h.

Typedef Documentation

◆ TransitionCaptureState

◆ TriggerData

typedef struct TriggerData TriggerData

◆ TriggerEvent

Definition at line 29 of file trigger.h.

Function Documentation

◆ AfterTriggerBeginQuery()

void AfterTriggerBeginQuery ( void  )

Definition at line 4961 of file trigger.c.

4962 {
4963  /* Increase the query stack depth */
4965 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3854

References afterTriggers, and AfterTriggersData::query_depth.

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

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 5239 of file trigger.c.

5240 {
5241  int my_level = GetCurrentTransactionNestLevel();
5242 
5243  /*
5244  * Allocate more space in the trans_stack if needed. (Note: because the
5245  * minimum nest level of a subtransaction is 2, we waste the first couple
5246  * entries of the array; not worth the notational effort to avoid it.)
5247  */
5248  while (my_level >= afterTriggers.maxtransdepth)
5249  {
5250  if (afterTriggers.maxtransdepth == 0)
5251  {
5252  /* Arbitrarily initialize for max of 8 subtransaction levels */
5255  8 * sizeof(AfterTriggersTransData));
5257  }
5258  else
5259  {
5260  /* repalloc will keep the stack in the same context */
5261  int new_alloc = afterTriggers.maxtransdepth * 2;
5262 
5265  new_alloc * sizeof(AfterTriggersTransData));
5266  afterTriggers.maxtransdepth = new_alloc;
5267  }
5268  }
5269 
5270  /*
5271  * Push the current information into the stack. The SET CONSTRAINTS state
5272  * is not saved until/unless changed. Likewise, we don't make a
5273  * per-subtransaction event context until needed.
5274  */
5275  afterTriggers.trans_stack[my_level].state = NULL;
5279 }
MemoryContext TopTransactionContext
Definition: mcxt.c:53
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1188
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
CommandId firing_counter
Definition: trigger.c:3794
AfterTriggersTransData * trans_stack
Definition: trigger.c:3805
AfterTriggerEventList events
Definition: trigger.c:3796
AfterTriggerEventList events
Definition: trigger.c:3820
SetConstraintState state
Definition: trigger.c:3819
CommandId firing_counter
Definition: trigger.c:3822
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:910

References afterTriggers, 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().

◆ AfterTriggerBeginXact()

void AfterTriggerBeginXact ( void  )

Definition at line 4929 of file trigger.c.

4930 {
4931  /*
4932  * Initialize after-trigger state structure to empty
4933  */
4934  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4936 
4937  /*
4938  * Verify that there is no leftover state remaining. If these assertions
4939  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4940  * up properly.
4941  */
4942  Assert(afterTriggers.state == NULL);
4943  Assert(afterTriggers.query_stack == NULL);
4945  Assert(afterTriggers.event_cxt == NULL);
4946  Assert(afterTriggers.events.head == NULL);
4947  Assert(afterTriggers.trans_stack == NULL);
4949 }
uint32 CommandId
Definition: c.h:612
Assert(fmt[strlen(fmt) - 1] !='\n')
AfterTriggerEventChunk * head
Definition: trigger.c:3688
SetConstraintState state
Definition: trigger.c:3795
AfterTriggersQueryData * query_stack
Definition: trigger.c:3800
MemoryContext event_cxt
Definition: trigger.c:3797

References afterTriggers, 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().

◆ AfterTriggerEndQuery()

void AfterTriggerEndQuery ( EState estate)

Definition at line 4981 of file trigger.c.

4982 {
4984 
4985  /* Must be inside a query, too */
4987 
4988  /*
4989  * If we never even got as far as initializing the event stack, there
4990  * certainly won't be any events, so exit quickly.
4991  */
4993  {
4995  return;
4996  }
4997 
4998  /*
4999  * Process all immediate-mode triggers queued by the query, and move the
5000  * deferred ones to the main list of deferred events.
5001  *
5002  * Notice that we decide which ones will be fired, and put the deferred
5003  * ones on the main list, before anything is actually fired. This ensures
5004  * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
5005  * IMMEDIATE: all events we have decided to defer will be available for it
5006  * to fire.
5007  *
5008  * We loop in case a trigger queues more events at the same query level.
5009  * Ordinary trigger functions, including all PL/pgSQL trigger functions,
5010  * will instead fire any triggers in a dedicated query level. Foreign key
5011  * enforcement triggers do add to the current query level, thanks to their
5012  * passing fire_triggers = false to SPI_execute_snapshot(). Other
5013  * C-language triggers might do likewise.
5014  *
5015  * If we find no firable events, we don't have to increment
5016  * firing_counter.
5017  */
5019 
5020  for (;;)
5021  {
5023  {
5024  CommandId firing_id = afterTriggers.firing_counter++;
5025  AfterTriggerEventChunk *oldtail = qs->events.tail;
5026 
5027  if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
5028  break; /* all fired */
5029 
5030  /*
5031  * Firing a trigger could result in query_stack being repalloc'd,
5032  * so we must recalculate qs after each afterTriggerInvokeEvents
5033  * call. Furthermore, it's unsafe to pass delete_ok = true here,
5034  * because that could cause afterTriggerInvokeEvents to try to
5035  * access qs->events after the stack has been repalloc'd.
5036  */
5038 
5039  /*
5040  * We'll need to scan the events list again. To reduce the cost
5041  * of doing so, get rid of completely-fired chunks. We know that
5042  * all events were marked IN_PROGRESS or DONE at the conclusion of
5043  * afterTriggerMarkEvents, so any still-interesting events must
5044  * have been added after that, and so must be in the chunk that
5045  * was then the tail chunk, or in later chunks. So, zap all
5046  * chunks before oldtail. This is approximately the same set of
5047  * events we would have gotten rid of by passing delete_ok = true.
5048  */
5049  Assert(oldtail != NULL);
5050  while (qs->events.head != oldtail)
5052  }
5053  else
5054  break;
5055  }
5056 
5057  /* Release query-level-local storage, including tuplestores if any */
5059 
5061 }
AfterTriggerEventChunk * tail
Definition: trigger.c:3689
AfterTriggerEventList events
Definition: trigger.c:3811
static void afterTriggerDeleteHeadEventChunk(AfterTriggersQueryData *qs)
Definition: trigger.c:4153
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:5072
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4486
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4570

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

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

◆ AfterTriggerEndSubXact()

void AfterTriggerEndSubXact ( bool  isCommit)

Definition at line 5287 of file trigger.c.

5288 {
5289  int my_level = GetCurrentTransactionNestLevel();
5291  AfterTriggerEvent event;
5292  AfterTriggerEventChunk *chunk;
5293  CommandId subxact_firing_id;
5294 
5295  /*
5296  * Pop the prior state if needed.
5297  */
5298  if (isCommit)
5299  {
5300  Assert(my_level < afterTriggers.maxtransdepth);
5301  /* If we saved a prior state, we don't need it anymore */
5302  state = afterTriggers.trans_stack[my_level].state;
5303  if (state != NULL)
5304  pfree(state);
5305  /* this avoids double pfree if error later: */
5306  afterTriggers.trans_stack[my_level].state = NULL;
5309  }
5310  else
5311  {
5312  /*
5313  * Aborting. It is possible subxact start failed before calling
5314  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
5315  * trans_stack levels that aren't there.
5316  */
5317  if (my_level >= afterTriggers.maxtransdepth)
5318  return;
5319 
5320  /*
5321  * Release query-level storage for queries being aborted, and restore
5322  * query_depth to its pre-subxact value. This assumes that a
5323  * subtransaction will not add events to query levels started in a
5324  * earlier transaction state.
5325  */
5327  {
5331  }
5334 
5335  /*
5336  * Restore the global deferred-event list to its former length,
5337  * discarding any events queued by the subxact.
5338  */
5340  &afterTriggers.trans_stack[my_level].events);
5341 
5342  /*
5343  * Restore the trigger state. If the saved state is NULL, then this
5344  * subxact didn't save it, so it doesn't need restoring.
5345  */
5346  state = afterTriggers.trans_stack[my_level].state;
5347  if (state != NULL)
5348  {
5351  }
5352  /* this avoids double pfree if error later: */
5353  afterTriggers.trans_stack[my_level].state = NULL;
5354 
5355  /*
5356  * Scan for any remaining deferred events that were marked DONE or IN
5357  * PROGRESS by this subxact or a child, and un-mark them. We can
5358  * recognize such events because they have a firing ID greater than or
5359  * equal to the firing_counter value we saved at subtransaction start.
5360  * (This essentially assumes that the current subxact includes all
5361  * subxacts started after it.)
5362  */
5363  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
5365  {
5366  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5367 
5368  if (event->ate_flags &
5370  {
5371  if (evtshared->ats_firing_id >= subxact_firing_id)
5372  event->ate_flags &=
5374  }
5375  }
5376  }
5377 }
void pfree(void *pointer)
Definition: mcxt.c:1175
TriggerFlags ate_flags
Definition: trigger.c:3621
CommandId ats_firing_id
Definition: trigger.c:3612
Definition: regguts.h:318
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3597
#define GetTriggerSharedData(evt)
Definition: trigger.c:3664
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:4113
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3596
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3701

References AFTER_TRIGGER_DONE, AFTER_TRIGGER_IN_PROGRESS, AfterTriggerFreeQuery(), afterTriggerRestoreEventList(), afterTriggers, 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().

◆ AfterTriggerEndXact()

void AfterTriggerEndXact ( bool  isCommit)

Definition at line 5191 of file trigger.c.

5192 {
5193  /*
5194  * Forget the pending-events list.
5195  *
5196  * Since all the info is in TopTransactionContext or children thereof, we
5197  * don't really need to do anything to reclaim memory. However, the
5198  * pending-events list could be large, and so it's useful to discard it as
5199  * soon as possible --- especially if we are aborting because we ran out
5200  * of memory for the list!
5201  */
5203  {
5205  afterTriggers.event_cxt = NULL;
5206  afterTriggers.events.head = NULL;
5207  afterTriggers.events.tail = NULL;
5208  afterTriggers.events.tailfree = NULL;
5209  }
5210 
5211  /*
5212  * Forget any subtransaction state as well. Since this can't be very
5213  * large, we let the eventual reset of TopTransactionContext free the
5214  * memory instead of doing it here.
5215  */
5216  afterTriggers.trans_stack = NULL;
5218 
5219 
5220  /*
5221  * Forget the query stack and constraint-related state information. As
5222  * with the subtransaction state information, we don't bother freeing the
5223  * memory here.
5224  */
5225  afterTriggers.query_stack = NULL;
5227  afterTriggers.state = NULL;
5228 
5229  /* No more afterTriggers manipulation until next transaction starts. */
5231 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218

References afterTriggers, 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().

◆ AfterTriggerFireDeferred()

void AfterTriggerFireDeferred ( void  )

Definition at line 5135 of file trigger.c.

5136 {
5137  AfterTriggerEventList *events;
5138  bool snap_pushed = false;
5139 
5140  /* Must not be inside a query */
5142 
5143  /*
5144  * If there are any triggers to fire, make sure we have set a snapshot for
5145  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
5146  * can't assume ActiveSnapshot is valid on entry.)
5147  */
5148  events = &afterTriggers.events;
5149  if (events->head != NULL)
5150  {
5152  snap_pushed = true;
5153  }
5154 
5155  /*
5156  * Run all the remaining triggers. Loop until they are all gone, in case
5157  * some trigger queues more for us to do.
5158  */
5159  while (afterTriggerMarkEvents(events, NULL, false))
5160  {
5161  CommandId firing_id = afterTriggers.firing_counter++;
5162 
5163  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
5164  break; /* all fired */
5165  }
5166 
5167  /*
5168  * We don't bother freeing the event list, since it will go away anyway
5169  * (and more efficiently than via pfree) in AfterTriggerEndXact.
5170  */
5171 
5172  if (snap_pushed)
5174 }
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void PopActiveSnapshot(void)
Definition: snapmgr.c:776
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:682

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

Referenced by CommitTransaction(), and PrepareTransaction().

◆ AfterTriggerPendingOnRel()

bool AfterTriggerPendingOnRel ( Oid  relid)

Definition at line 5912 of file trigger.c.

5913 {
5914  AfterTriggerEvent event;
5915  AfterTriggerEventChunk *chunk;
5916  int depth;
5917 
5918  /* Scan queued events */
5920  {
5921  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5922 
5923  /*
5924  * We can ignore completed events. (Even if a DONE flag is rolled
5925  * back by subxact abort, it's OK because the effects of the TRUNCATE
5926  * or whatever must get rolled back too.)
5927  */
5928  if (event->ate_flags & AFTER_TRIGGER_DONE)
5929  continue;
5930 
5931  if (evtshared->ats_relid == relid)
5932  return true;
5933  }
5934 
5935  /*
5936  * Also scan events queued by incomplete queries. This could only matter
5937  * if TRUNCATE/etc is executed by a function or trigger within an updating
5938  * query on the same relation, which is pretty perverse, but let's check.
5939  */
5940  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
5941  {
5943  {
5944  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5945 
5946  if (event->ate_flags & AFTER_TRIGGER_DONE)
5947  continue;
5948 
5949  if (evtshared->ats_relid == relid)
5950  return true;
5951  }
5952  }
5953 
5954  return false;
5955 }

References AFTER_TRIGGER_DONE, afterTriggers, 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().

◆ AfterTriggerSetState()

void AfterTriggerSetState ( ConstraintsSetStmt stmt)

Definition at line 5597 of file trigger.c.

5598 {
5599  int my_level = GetCurrentTransactionNestLevel();
5600 
5601  /* If we haven't already done so, initialize our state. */
5602  if (afterTriggers.state == NULL)
5604 
5605  /*
5606  * If in a subtransaction, and we didn't save the current state already,
5607  * save it so it can be restored if the subtransaction aborts.
5608  */
5609  if (my_level > 1 &&
5610  afterTriggers.trans_stack[my_level].state == NULL)
5611  {
5612  afterTriggers.trans_stack[my_level].state =
5614  }
5615 
5616  /*
5617  * Handle SET CONSTRAINTS ALL ...
5618  */
5619  if (stmt->constraints == NIL)
5620  {
5621  /*
5622  * Forget any previous SET CONSTRAINTS commands in this transaction.
5623  */
5625 
5626  /*
5627  * Set the per-transaction ALL state to known.
5628  */
5629  afterTriggers.state->all_isset = true;
5631  }
5632  else
5633  {
5634  Relation conrel;
5635  Relation tgrel;
5636  List *conoidlist = NIL;
5637  List *tgoidlist = NIL;
5638  ListCell *lc;
5639 
5640  /*
5641  * Handle SET CONSTRAINTS constraint-name [, ...]
5642  *
5643  * First, identify all the named constraints and make a list of their
5644  * OIDs. Since, unlike the SQL spec, we allow multiple constraints of
5645  * the same name within a schema, the specifications are not
5646  * necessarily unique. Our strategy is to target all matching
5647  * constraints within the first search-path schema that has any
5648  * matches, but disregard matches in schemas beyond the first match.
5649  * (This is a bit odd but it's the historical behavior.)
5650  *
5651  * A constraint in a partitioned table may have corresponding
5652  * constraints in the partitions. Grab those too.
5653  */
5654  conrel = table_open(ConstraintRelationId, AccessShareLock);
5655 
5656  foreach(lc, stmt->constraints)
5657  {
5658  RangeVar *constraint = lfirst(lc);
5659  bool found;
5660  List *namespacelist;
5661  ListCell *nslc;
5662 
5663  if (constraint->catalogname)
5664  {
5665  if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
5666  ereport(ERROR,
5667  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5668  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
5669  constraint->catalogname, constraint->schemaname,
5670  constraint->relname)));
5671  }
5672 
5673  /*
5674  * If we're given the schema name with the constraint, look only
5675  * in that schema. If given a bare constraint name, use the
5676  * search path to find the first matching constraint.
5677  */
5678  if (constraint->schemaname)
5679  {
5680  Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
5681  false);
5682 
5683  namespacelist = list_make1_oid(namespaceId);
5684  }
5685  else
5686  {
5687  namespacelist = fetch_search_path(true);
5688  }
5689 
5690  found = false;
5691  foreach(nslc, namespacelist)
5692  {
5693  Oid namespaceId = lfirst_oid(nslc);
5694  SysScanDesc conscan;
5695  ScanKeyData skey[2];
5696  HeapTuple tup;
5697 
5698  ScanKeyInit(&skey[0],
5699  Anum_pg_constraint_conname,
5700  BTEqualStrategyNumber, F_NAMEEQ,
5701  CStringGetDatum(constraint->relname));
5702  ScanKeyInit(&skey[1],
5703  Anum_pg_constraint_connamespace,
5704  BTEqualStrategyNumber, F_OIDEQ,
5705  ObjectIdGetDatum(namespaceId));
5706 
5707  conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
5708  true, NULL, 2, skey);
5709 
5710  while (HeapTupleIsValid(tup = systable_getnext(conscan)))
5711  {
5713 
5714  if (con->condeferrable)
5715  conoidlist = lappend_oid(conoidlist, con->oid);
5716  else if (stmt->deferred)
5717  ereport(ERROR,
5718  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5719  errmsg("constraint \"%s\" is not deferrable",
5720  constraint->relname)));
5721  found = true;
5722  }
5723 
5724  systable_endscan(conscan);
5725 
5726  /*
5727  * Once we've found a matching constraint we do not search
5728  * later parts of the search path.
5729  */
5730  if (found)
5731  break;
5732  }
5733 
5734  list_free(namespacelist);
5735 
5736  /*
5737  * Not found ?
5738  */
5739  if (!found)
5740  ereport(ERROR,
5741  (errcode(ERRCODE_UNDEFINED_OBJECT),
5742  errmsg("constraint \"%s\" does not exist",
5743  constraint->relname)));
5744  }
5745 
5746  /*
5747  * Scan for any possible descendants of the constraints. We append
5748  * whatever we find to the same list that we're scanning; this has the
5749  * effect that we create new scans for those, too, so if there are
5750  * further descendents, we'll also catch them.
5751  */
5752  foreach(lc, conoidlist)
5753  {
5754  Oid parent = lfirst_oid(lc);
5755  ScanKeyData key;
5756  SysScanDesc scan;
5757  HeapTuple tuple;
5758 
5759  ScanKeyInit(&key,
5760  Anum_pg_constraint_conparentid,
5761  BTEqualStrategyNumber, F_OIDEQ,
5762  ObjectIdGetDatum(parent));
5763 
5764  scan = systable_beginscan(conrel, ConstraintParentIndexId, true, NULL, 1, &key);
5765 
5766  while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5767  {
5769 
5770  conoidlist = lappend_oid(conoidlist, con->oid);
5771  }
5772 
5773  systable_endscan(scan);
5774  }
5775 
5776  table_close(conrel, AccessShareLock);
5777 
5778  /*
5779  * Now, locate the trigger(s) implementing each of these constraints,
5780  * and make a list of their OIDs.
5781  */
5782  tgrel = table_open(TriggerRelationId, AccessShareLock);
5783 
5784  foreach(lc, conoidlist)
5785  {
5786  Oid conoid = lfirst_oid(lc);
5787  ScanKeyData skey;
5788  SysScanDesc tgscan;
5789  HeapTuple htup;
5790 
5791  ScanKeyInit(&skey,
5792  Anum_pg_trigger_tgconstraint,
5793  BTEqualStrategyNumber, F_OIDEQ,
5794  ObjectIdGetDatum(conoid));
5795 
5796  tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
5797  NULL, 1, &skey);
5798 
5799  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
5800  {
5801  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
5802 
5803  /*
5804  * Silently skip triggers that are marked as non-deferrable in
5805  * pg_trigger. This is not an error condition, since a
5806  * deferrable RI constraint may have some non-deferrable
5807  * actions.
5808  */
5809  if (pg_trigger->tgdeferrable)
5810  tgoidlist = lappend_oid(tgoidlist, pg_trigger->oid);
5811  }
5812 
5813  systable_endscan(tgscan);
5814  }
5815 
5816  table_close(tgrel, AccessShareLock);
5817 
5818  /*
5819  * Now we can set the trigger states of individual triggers for this
5820  * xact.
5821  */
5822  foreach(lc, tgoidlist)
5823  {
5824  Oid tgoid = lfirst_oid(lc);
5826  bool found = false;
5827  int i;
5828 
5829  for (i = 0; i < state->numstates; i++)
5830  {
5831  if (state->trigstates[i].sct_tgoid == tgoid)
5832  {
5833  state->trigstates[i].sct_tgisdeferred = stmt->deferred;
5834  found = true;
5835  break;
5836  }
5837  }
5838  if (!found)
5839  {
5841  SetConstraintStateAddItem(state, tgoid, stmt->deferred);
5842  }
5843  }
5844  }
5845 
5846  /*
5847  * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
5848  * checks against that constraint must be made when the SET CONSTRAINTS
5849  * command is executed -- i.e. the effects of the SET CONSTRAINTS command
5850  * apply retroactively. We've updated the constraints state, so scan the
5851  * list of previously deferred events to fire any that have now become
5852  * immediate.
5853  *
5854  * Obviously, if this was SET ... DEFERRED then it can't have converted
5855  * any unfired events to immediate, so we need do nothing in that case.
5856  */
5857  if (!stmt->deferred)
5858  {
5860  bool snapshot_set = false;
5861 
5862  while (afterTriggerMarkEvents(events, NULL, true))
5863  {
5864  CommandId firing_id = afterTriggers.firing_counter++;
5865 
5866  /*
5867  * Make sure a snapshot has been established in case trigger
5868  * functions need one. Note that we avoid setting a snapshot if
5869  * we don't find at least one trigger that has to be fired now.
5870  * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
5871  * ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
5872  * at the start of a transaction it's not possible for any trigger
5873  * events to be queued yet.)
5874  */
5875  if (!snapshot_set)
5876  {
5878  snapshot_set = true;
5879  }
5880 
5881  /*
5882  * We can delete fired events if we are at top transaction level,
5883  * but we'd better not if inside a subtransaction, since the
5884  * subtransaction could later get rolled back.
5885  */
5886  if (afterTriggerInvokeEvents(events, firing_id, NULL,
5887  !IsSubTransaction()))
5888  break; /* all fired */
5889  }
5890 
5891  if (snapshot_set)
5893  }
5894 }
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2994
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
Oid MyDatabaseId
Definition: globals.c:89
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
int i
Definition: isn.c:73
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
void list_free(List *list)
Definition: list.c:1505
#define AccessShareLock
Definition: lockdefs.h:36
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2939
List * fetch_search_path(bool includeImplicit)
Definition: namespace.c:4431
FormData_pg_constraint * Form_pg_constraint
#define lfirst(lc)
Definition: pg_list.h:169
#define NIL
Definition: pg_list.h:65
#define list_make1_oid(x1)
Definition: pg_list.h:236
#define lfirst_oid(lc)
Definition: pg_list.h:171
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
#define CStringGetDatum(X)
Definition: postgres.h:622
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
unsigned int Oid
Definition: postgres_ext.h:31
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Definition: pg_list.h:51
char * relname
Definition: primnodes.h:68
char * catalogname
Definition: primnodes.h:66
char * schemaname
Definition: primnodes.h:67
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static SetConstraintState SetConstraintStateAddItem(SetConstraintState state, Oid tgoid, bool tgisdeferred)
Definition: trigger.c:5567
static SetConstraintState SetConstraintStateCopy(SetConstraintState state)
Definition: trigger.c:5547
static SetConstraintState SetConstraintStateCreate(int numalloc)
Definition: trigger.c:5522
bool IsSubTransaction(void)
Definition: xact.c:4839

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

Referenced by standard_ProcessUtility().

◆ CopyTriggerDesc()

TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 2099 of file trigger.c.

2100 {
2101  TriggerDesc *newdesc;
2102  Trigger *trigger;
2103  int i;
2104 
2105  if (trigdesc == NULL || trigdesc->numtriggers <= 0)
2106  return NULL;
2107 
2108  newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
2109  memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
2110 
2111  trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
2112  memcpy(trigger, trigdesc->triggers,
2113  trigdesc->numtriggers * sizeof(Trigger));
2114  newdesc->triggers = trigger;
2115 
2116  for (i = 0; i < trigdesc->numtriggers; i++)
2117  {
2118  trigger->tgname = pstrdup(trigger->tgname);
2119  if (trigger->tgnattr > 0)
2120  {
2121  int16 *newattr;
2122 
2123  newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
2124  memcpy(newattr, trigger->tgattr,
2125  trigger->tgnattr * sizeof(int16));
2126  trigger->tgattr = newattr;
2127  }
2128  if (trigger->tgnargs > 0)
2129  {
2130  char **newargs;
2131  int16 j;
2132 
2133  newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
2134  for (j = 0; j < trigger->tgnargs; j++)
2135  newargs[j] = pstrdup(trigger->tgargs[j]);
2136  trigger->tgargs = newargs;
2137  }
2138  if (trigger->tgqual)
2139  trigger->tgqual = pstrdup(trigger->tgqual);
2140  if (trigger->tgoldtable)
2141  trigger->tgoldtable = pstrdup(trigger->tgoldtable);
2142  if (trigger->tgnewtable)
2143  trigger->tgnewtable = pstrdup(trigger->tgnewtable);
2144  trigger++;
2145  }
2146 
2147  return newdesc;
2148 }
signed short int16
Definition: c.h:439
int j
Definition: isn.c:74
char * pstrdup(const char *in)
Definition: mcxt.c:1305
void * palloc(Size size)
Definition: mcxt.c:1068
int numtriggers
Definition: reltrigger.h:50
Trigger * triggers
Definition: reltrigger.h:49
char * tgoldtable
Definition: reltrigger.h:43
char * tgnewtable
Definition: reltrigger.h:44
char * tgname
Definition: reltrigger.h:27
int16 tgnargs
Definition: reltrigger.h:38
char * tgqual
Definition: reltrigger.h:42
int16 tgnattr
Definition: reltrigger.h:39
char ** tgargs
Definition: reltrigger.h:41
int16 * tgattr
Definition: reltrigger.h:40

References i, j, 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().

◆ 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 162 of file trigger.c.

166 {
167  return
168  CreateTriggerFiringOn(stmt, queryString, relOid, refRelOid,
169  constraintOid, indexOid, funcoid,
170  parentTriggerOid, whenClause, isInternal,
171  in_partition, TRIGGER_FIRES_ON_ORIGIN);
172 }
ObjectAddress CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, Oid funcoid, Oid parentTriggerOid, Node *whenClause, bool isInternal, bool in_partition, char trigger_fires_when)
Definition: trigger.c:179
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:149

References CreateTriggerFiringOn(), and TRIGGER_FIRES_ON_ORIGIN.

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

◆ CreateTriggerFiringOn()

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

Definition at line 179 of file trigger.c.

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

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

Referenced by CloneRowTriggersToPartition(), and CreateTrigger().

◆ EnableDisableTrigger()

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

Definition at line 1768 of file trigger.c.

1770 {
1771  Relation tgrel;
1772  int nkeys;
1773  ScanKeyData keys[2];
1774  SysScanDesc tgscan;
1775  HeapTuple tuple;
1776  bool found;
1777  bool changed;
1778 
1779  /* Scan the relevant entries in pg_triggers */
1780  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1781 
1782  ScanKeyInit(&keys[0],
1783  Anum_pg_trigger_tgrelid,
1784  BTEqualStrategyNumber, F_OIDEQ,
1786  if (tgname)
1787  {
1788  ScanKeyInit(&keys[1],
1789  Anum_pg_trigger_tgname,
1790  BTEqualStrategyNumber, F_NAMEEQ,
1791  CStringGetDatum(tgname));
1792  nkeys = 2;
1793  }
1794  else
1795  nkeys = 1;
1796 
1797  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1798  NULL, nkeys, keys);
1799 
1800  found = changed = false;
1801 
1802  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1803  {
1804  Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1805 
1806  if (oldtrig->tgisinternal)
1807  {
1808  /* system trigger ... ok to process? */
1809  if (skip_system)
1810  continue;
1811  if (!superuser())
1812  ereport(ERROR,
1813  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1814  errmsg("permission denied: \"%s\" is a system trigger",
1815  NameStr(oldtrig->tgname))));
1816  }
1817 
1818  found = true;
1819 
1820  if (oldtrig->tgenabled != fires_when)
1821  {
1822  /* need to change this one ... make a copy to scribble on */
1823  HeapTuple newtup = heap_copytuple(tuple);
1824  Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1825 
1826  newtrig->tgenabled = fires_when;
1827 
1828  CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1829 
1830  heap_freetuple(newtup);
1831 
1832  changed = true;
1833  }
1834 
1835  InvokeObjectPostAlterHook(TriggerRelationId,
1836  oldtrig->oid, 0);
1837  }
1838 
1839  systable_endscan(tgscan);
1840 
1841  table_close(tgrel, RowExclusiveLock);
1842 
1843  if (tgname && !found)
1844  ereport(ERROR,
1845  (errcode(ERRCODE_UNDEFINED_OBJECT),
1846  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1847  tgname, RelationGetRelationName(rel))));
1848 
1849  /*
1850  * If we changed anything, broadcast a SI inval message to force each
1851  * backend (including our own!) to rebuild relation's relcache entry.
1852  * Otherwise they will fail to apply the change promptly.
1853  */
1854  if (changed)
1856 }
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1363
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:195
bool superuser(void)
Definition: superuser.c:46

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

Referenced by ATExecEnableDisableTrigger().

◆ ExecARDeleteTriggers()

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

Definition at line 2786 of file trigger.c.

2792 {
2793  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2794 
2795  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2796  (transition_capture && transition_capture->tcs_delete_old_table))
2797  {
2798  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2799 
2800  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2801  if (fdw_trigtuple == NULL)
2802  GetTupleForTrigger(estate,
2803  NULL,
2804  relinfo,
2805  tupleid,
2807  slot,
2808  NULL,
2809  NULL);
2810  else
2811  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2812 
2813  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2815  true, slot, NULL, NIL, NULL,
2816  transition_capture,
2817  is_crosspart_update);
2818  }
2819 }
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1166
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
@ LockTupleExclusive
Definition: lockoptions.h:58
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:460
bool trig_delete_after_row
Definition: reltrigger.h:67
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, ResultRelInfo *src_partinfo, ResultRelInfo *dst_partinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture, bool is_crosspart_update)
Definition: trigger.c:5999
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot, TM_FailureData *tmfpd)
Definition: trigger.c:3277
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:93

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 ExecDeleteEpilogue(), and ExecSimpleRelationDelete().

◆ ExecARInsertTriggers()

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

Definition at line 2548 of file trigger.c.

2551 {
2552  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2553 
2554  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2555  (transition_capture && transition_capture->tcs_insert_new_table))
2556  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2558  true, NULL, slot,
2559  recheckIndexes, NULL,
2560  transition_capture,
2561  false);
2562 }
bool trig_insert_after_row
Definition: reltrigger.h:57
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:92

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

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

◆ ExecARUpdateTriggers()

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

Definition at line 3089 of file trigger.c.

3098 {
3099  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3100 
3101  if ((trigdesc && trigdesc->trig_update_after_row) ||
3102  (transition_capture &&
3103  (transition_capture->tcs_update_old_table ||
3104  transition_capture->tcs_update_new_table)))
3105  {
3106  /*
3107  * Note: if the UPDATE is converted into a DELETE+INSERT as part of
3108  * update-partition-key operation, then this function is also called
3109  * separately for DELETE and INSERT to capture transition table rows.
3110  * In such case, either old tuple or new tuple can be NULL.
3111  */
3112  TupleTableSlot *oldslot;
3113  ResultRelInfo *tupsrc;
3114 
3115  Assert((src_partinfo != NULL && dst_partinfo != NULL) ||
3116  !is_crosspart_update);
3117 
3118  tupsrc = src_partinfo ? src_partinfo : relinfo;
3119  oldslot = ExecGetTriggerOldSlot(estate, tupsrc);
3120 
3121  if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
3122  GetTupleForTrigger(estate,
3123  NULL,
3124  tupsrc,
3125  tupleid,
3127  oldslot,
3128  NULL,
3129  NULL);
3130  else if (fdw_trigtuple != NULL)
3131  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
3132  else
3133  ExecClearTuple(oldslot);
3134 
3135  AfterTriggerSaveEvent(estate, relinfo,
3136  src_partinfo, dst_partinfo,
3138  true,
3139  oldslot, newslot, recheckIndexes,
3140  ExecGetAllUpdatedCols(relinfo, estate),
3141  transition_capture,
3142  is_crosspart_update);
3143  }
3144 }
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1347
bool trig_update_after_row
Definition: reltrigger.h:62
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:94
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425

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

Referenced by ExecCrossPartitionUpdateForeignKey(), ExecDeleteEpilogue(), ExecInsert(), ExecSimpleRelationUpdate(), and ExecUpdateEpilogue().

◆ ExecASDeleteTriggers()

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

Definition at line 2677 of file trigger.c.

2679 {
2680  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2681 
2682  if (trigdesc && trigdesc->trig_delete_after_statement)
2683  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2685  false, NULL, NULL, NIL, NULL, transition_capture,
2686  false);
2687 }
bool trig_delete_after_statement
Definition: reltrigger.h:70

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

Referenced by fireASTriggers().

◆ ExecASInsertTriggers()

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

Definition at line 2459 of file trigger.c.

2461 {
2462  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2463 
2464  if (trigdesc && trigdesc->trig_insert_after_statement)
2465  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2467  false, NULL, NULL, NIL, NULL, transition_capture,
2468  false);
2469 }
bool trig_insert_after_statement
Definition: reltrigger.h:60

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

Referenced by CopyFrom(), and fireASTriggers().

◆ ExecASTruncateTriggers()

void ExecASTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 3260 of file trigger.c.

3261 {
3262  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3263 
3264  if (trigdesc && trigdesc->trig_truncate_after_statement)
3265  AfterTriggerSaveEvent(estate, relinfo,
3266  NULL, NULL,
3268  false, NULL, NULL, NIL, NULL, NULL,
3269  false);
3270 }
bool trig_truncate_after_statement
Definition: reltrigger.h:73
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:95

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

Referenced by ExecuteTruncateGuts().

◆ ExecASUpdateTriggers()

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

Definition at line 2927 of file trigger.c.

2929 {
2930  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2931 
2932  /* statement-level triggers operate on the parent table */
2933  Assert(relinfo->ri_RootResultRelInfo == NULL);
2934 
2935  if (trigdesc && trigdesc->trig_update_after_statement)
2936  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2938  false, NULL, NULL, NIL,
2939  ExecGetAllUpdatedCols(relinfo, estate),
2940  transition_capture,
2941  false);
2942 }
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:538
bool trig_update_after_statement
Definition: reltrigger.h:65

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

Referenced by fireASTriggers().

◆ ExecBRDeleteTriggers()

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

Definition at line 2697 of file trigger.c.

2702 {
2703  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2704  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2705  bool result = true;
2706  TriggerData LocTriggerData = {0};
2707  HeapTuple trigtuple;
2708  bool should_free = false;
2709  int i;
2710 
2711  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2712  if (fdw_trigtuple == NULL)
2713  {
2714  TupleTableSlot *epqslot_candidate = NULL;
2715 
2716  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2717  LockTupleExclusive, slot, &epqslot_candidate,
2718  NULL))
2719  return false;
2720 
2721  /*
2722  * If the tuple was concurrently updated and the caller of this
2723  * function requested for the updated tuple, skip the trigger
2724  * execution.
2725  */
2726  if (epqslot_candidate != NULL && epqslot != NULL)
2727  {
2728  *epqslot = epqslot_candidate;
2729  return false;
2730  }
2731 
2732  trigtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2733  }
2734  else
2735  {
2736  trigtuple = fdw_trigtuple;
2737  ExecForceStoreHeapTuple(trigtuple, slot, false);
2738  }
2739 
2740  LocTriggerData.type = T_TriggerData;
2741  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2744  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2745  for (i = 0; i < trigdesc->numtriggers; i++)
2746  {
2747  HeapTuple newtuple;
2748  Trigger *trigger = &trigdesc->triggers[i];
2749 
2750  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2751  TRIGGER_TYPE_ROW,
2752  TRIGGER_TYPE_BEFORE,
2753  TRIGGER_TYPE_DELETE))
2754  continue;
2755  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2756  NULL, slot, NULL))
2757  continue;
2758 
2759  LocTriggerData.tg_trigslot = slot;
2760  LocTriggerData.tg_trigtuple = trigtuple;
2761  LocTriggerData.tg_trigger = trigger;
2762  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2763  i,
2764  relinfo->ri_TrigFunctions,
2765  relinfo->ri_TrigInstrument,
2766  GetPerTupleMemoryContext(estate));
2767  if (newtuple == NULL)
2768  {
2769  result = false; /* tell caller to suppress delete */
2770  break;
2771  }
2772  if (newtuple != trigtuple)
2773  heap_freetuple(newtuple);
2774  }
2775  if (should_free)
2776  heap_freetuple(trigtuple);
2777 
2778  return result;
2779 }
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1644
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:542
@ T_TriggerData
Definition: nodes.h:547
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:469
Relation ri_RelationDesc
Definition: execnodes.h:433
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:463
NodeTag type
Definition: trigger.h:33
Relation tg_relation
Definition: trigger.h:35
TriggerEvent tg_event
Definition: trigger.h:34
TupleTableSlot * tg_trigslot
Definition: trigger.h:39
Trigger * tg_trigger
Definition: trigger.h:38
HeapTuple tg_trigtuple
Definition: trigger.h:36
int16 tgtype
Definition: reltrigger.h:29
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3398
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2316
#define TRIGGER_EVENT_ROW
Definition: trigger.h:98
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:100

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 ExecDeletePrologue(), and ExecSimpleRelationDelete().

◆ ExecBRInsertTriggers()

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

Definition at line 2472 of file trigger.c.

2474 {
2475  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2476  HeapTuple newtuple = NULL;
2477  bool should_free;
2478  TriggerData LocTriggerData = {0};
2479  int i;
2480 
2481  LocTriggerData.type = T_TriggerData;
2482  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2485  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2486  for (i = 0; i < trigdesc->numtriggers; i++)
2487  {
2488  Trigger *trigger = &trigdesc->triggers[i];
2489  HeapTuple oldtuple;
2490 
2491  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2492  TRIGGER_TYPE_ROW,
2493  TRIGGER_TYPE_BEFORE,
2494  TRIGGER_TYPE_INSERT))
2495  continue;
2496  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2497  NULL, NULL, slot))
2498  continue;
2499 
2500  if (!newtuple)
2501  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2502 
2503  LocTriggerData.tg_trigslot = slot;
2504  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2505  LocTriggerData.tg_trigger = trigger;
2506  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2507  i,
2508  relinfo->ri_TrigFunctions,
2509  relinfo->ri_TrigInstrument,
2510  GetPerTupleMemoryContext(estate));
2511  if (newtuple == NULL)
2512  {
2513  if (should_free)
2514  heap_freetuple(oldtuple);
2515  return false; /* "do nothing" */
2516  }
2517  else if (newtuple != oldtuple)
2518  {
2519  ExecForceStoreHeapTuple(newtuple, slot, false);
2520 
2521  /*
2522  * After a tuple in a partition goes through a trigger, the user
2523  * could have changed the partition key enough that the tuple no
2524  * longer fits the partition. Verify that.
2525  */
2526  if (trigger->tgisclone &&
2527  !ExecPartitionCheck(relinfo, slot, estate, false))
2528  ereport(ERROR,
2529  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2530  errmsg("moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported"),
2531  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2532  trigger->tgname,
2535 
2536  if (should_free)
2537  heap_freetuple(oldtuple);
2538 
2539  /* signal tuple should be re-fetched if used */
2540  newtuple = NULL;
2541  }
2542  }
2543 
2544  return true;
2545 }
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1782
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
bool tgisclone
Definition: reltrigger.h:32

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().

◆ ExecBRUpdateTriggers()

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

Definition at line 2945 of file trigger.c.

2951 {
2952  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2953  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2954  HeapTuple newtuple = NULL;
2955  HeapTuple trigtuple;
2956  bool should_free_trig = false;
2957  bool should_free_new = false;
2958  TriggerData LocTriggerData = {0};
2959  int i;
2960  Bitmapset *updatedCols;
2961  LockTupleMode lockmode;
2962 
2963  /* Determine lock mode to use */
2964  lockmode = ExecUpdateLockMode(estate, relinfo);
2965 
2966  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2967  if (fdw_trigtuple == NULL)
2968  {
2969  TupleTableSlot *epqslot_candidate = NULL;
2970 
2971  /* get a copy of the on-disk tuple we are planning to update */
2972  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2973  lockmode, oldslot, &epqslot_candidate,
2974  tmfd))
2975  return false; /* cancel the update action */
2976 
2977  /*
2978  * In READ COMMITTED isolation level it's possible that target tuple
2979  * was changed due to concurrent update. In that case we have a raw
2980  * subplan output tuple in epqslot_candidate, and need to form a new
2981  * insertable tuple using ExecGetUpdateNewTuple to replace the one we
2982  * received in newslot. Neither we nor our callers have any further
2983  * interest in the passed-in tuple, so it's okay to overwrite newslot
2984  * with the newer data.
2985  *
2986  * (Typically, newslot was also generated by ExecGetUpdateNewTuple, so
2987  * that epqslot_clean will be that same slot and the copy step below
2988  * is not needed.)
2989  */
2990  if (epqslot_candidate != NULL)
2991  {
2992  TupleTableSlot *epqslot_clean;
2993 
2994  epqslot_clean = ExecGetUpdateNewTuple(relinfo, epqslot_candidate,
2995  oldslot);
2996 
2997  if (newslot != epqslot_clean)
2998  ExecCopySlot(newslot, epqslot_clean);
2999  }
3000 
3001  trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
3002  }
3003  else
3004  {
3005  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
3006  trigtuple = fdw_trigtuple;
3007  }
3008 
3009  LocTriggerData.type = T_TriggerData;
3010  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
3013  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3014  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
3015  LocTriggerData.tg_updatedcols = updatedCols;
3016  for (i = 0; i < trigdesc->numtriggers; i++)
3017  {
3018  Trigger *trigger = &trigdesc->triggers[i];
3019  HeapTuple oldtuple;
3020 
3021  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3022  TRIGGER_TYPE_ROW,
3023  TRIGGER_TYPE_BEFORE,
3024  TRIGGER_TYPE_UPDATE))
3025  continue;
3026  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3027  updatedCols, oldslot, newslot))
3028  continue;
3029 
3030  if (!newtuple)
3031  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
3032 
3033  LocTriggerData.tg_trigslot = oldslot;
3034  LocTriggerData.tg_trigtuple = trigtuple;
3035  LocTriggerData.tg_newtuple = oldtuple = newtuple;
3036  LocTriggerData.tg_newslot = newslot;
3037  LocTriggerData.tg_trigger = trigger;
3038  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3039  i,
3040  relinfo->ri_TrigFunctions,
3041  relinfo->ri_TrigInstrument,
3042  GetPerTupleMemoryContext(estate));
3043 
3044  if (newtuple == NULL)
3045  {
3046  if (should_free_trig)
3047  heap_freetuple(trigtuple);
3048  if (should_free_new)
3049  heap_freetuple(oldtuple);
3050  return false; /* "do nothing" */
3051  }
3052  else if (newtuple != oldtuple)
3053  {
3054  ExecForceStoreHeapTuple(newtuple, newslot, false);
3055 
3056  /*
3057  * If the tuple returned by the trigger / being stored, is the old
3058  * row version, and the heap tuple passed to the trigger was
3059  * allocated locally, materialize the slot. Otherwise we might
3060  * free it while still referenced by the slot.
3061  */
3062  if (should_free_trig && newtuple == trigtuple)
3063  ExecMaterializeSlot(newslot);
3064 
3065  if (should_free_new)
3066  heap_freetuple(oldtuple);
3067 
3068  /* signal tuple should be re-fetched if used */
3069  newtuple = NULL;
3070  }
3071  }
3072  if (should_free_trig)
3073  heap_freetuple(trigtuple);
3074 
3075  return true;
3076 }
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2338
LockTupleMode
Definition: lockoptions.h:50
TupleTableSlot * ExecGetUpdateNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot)
const Bitmapset * tg_updatedcols
Definition: trigger.h:43
HeapTuple tg_newtuple
Definition: trigger.h:37
TupleTableSlot * tg_newslot
Definition: trigger.h:40
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443

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

Referenced by ExecSimpleRelationUpdate(), and ExecUpdatePrologue().

◆ ExecBSDeleteTriggers()

void ExecBSDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2626 of file trigger.c.

2627 {
2628  TriggerDesc *trigdesc;
2629  int i;
2630  TriggerData LocTriggerData = {0};
2631 
2632  trigdesc = relinfo->ri_TrigDesc;
2633 
2634  if (trigdesc == NULL)
2635  return;
2636  if (!trigdesc->trig_delete_before_statement)
2637  return;
2638 
2639  /* no-op if we already fired BS triggers in this context */
2641  CMD_DELETE))
2642  return;
2643 
2644  LocTriggerData.type = T_TriggerData;
2645  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2647  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2648  for (i = 0; i < trigdesc->numtriggers; i++)
2649  {
2650  Trigger *trigger = &trigdesc->triggers[i];
2651  HeapTuple newtuple;
2652 
2653  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2654  TRIGGER_TYPE_STATEMENT,
2655  TRIGGER_TYPE_BEFORE,
2656  TRIGGER_TYPE_DELETE))
2657  continue;
2658  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2659  NULL, NULL, NULL))
2660  continue;
2661 
2662  LocTriggerData.tg_trigger = trigger;
2663  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2664  i,
2665  relinfo->ri_TrigFunctions,
2666  relinfo->ri_TrigInstrument,
2667  GetPerTupleMemoryContext(estate));
2668 
2669  if (newtuple)
2670  ereport(ERROR,
2671  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2672  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2673  }
2674 }
@ CMD_DELETE
Definition: nodes.h:724
bool trig_delete_before_statement
Definition: reltrigger.h:69
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:6396

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().

◆ ExecBSInsertTriggers()

void ExecBSInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2408 of file trigger.c.

2409 {
2410  TriggerDesc *trigdesc;
2411  int i;
2412  TriggerData LocTriggerData = {0};
2413 
2414  trigdesc = relinfo->ri_TrigDesc;
2415 
2416  if (trigdesc == NULL)
2417  return;
2418  if (!trigdesc->trig_insert_before_statement)
2419  return;
2420 
2421  /* no-op if we already fired BS triggers in this context */
2423  CMD_INSERT))
2424  return;
2425 
2426  LocTriggerData.type = T_TriggerData;
2427  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2429  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2430  for (i = 0; i < trigdesc->numtriggers; i++)
2431  {
2432  Trigger *trigger = &trigdesc->triggers[i];
2433  HeapTuple newtuple;
2434 
2435  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2436  TRIGGER_TYPE_STATEMENT,
2437  TRIGGER_TYPE_BEFORE,
2438  TRIGGER_TYPE_INSERT))
2439  continue;
2440  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2441  NULL, NULL, NULL))
2442  continue;
2443 
2444  LocTriggerData.tg_trigger = trigger;
2445  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2446  i,
2447  relinfo->ri_TrigFunctions,
2448  relinfo->ri_TrigInstrument,
2449  GetPerTupleMemoryContext(estate));
2450 
2451  if (newtuple)
2452  ereport(ERROR,
2453  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2454  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2455  }
2456 }
@ CMD_INSERT
Definition: nodes.h:723
bool trig_insert_before_statement
Definition: reltrigger.h:59

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().

◆ ExecBSTruncateTriggers()

void ExecBSTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 3213 of file trigger.c.

3214 {
3215  TriggerDesc *trigdesc;
3216  int i;
3217  TriggerData LocTriggerData = {0};
3218 
3219  trigdesc = relinfo->ri_TrigDesc;
3220 
3221  if (trigdesc == NULL)
3222  return;
3223  if (!trigdesc->trig_truncate_before_statement)
3224  return;
3225 
3226  LocTriggerData.type = T_TriggerData;
3227  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
3229  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3230 
3231  for (i = 0; i < trigdesc->numtriggers; i++)
3232  {
3233  Trigger *trigger = &trigdesc->triggers[i];
3234  HeapTuple newtuple;
3235 
3236  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3237  TRIGGER_TYPE_STATEMENT,
3238  TRIGGER_TYPE_BEFORE,
3239  TRIGGER_TYPE_TRUNCATE))
3240  continue;
3241  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3242  NULL, NULL, NULL))
3243  continue;
3244 
3245  LocTriggerData.tg_trigger = trigger;
3246  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3247  i,
3248  relinfo->ri_TrigFunctions,
3249  relinfo->ri_TrigInstrument,
3250  GetPerTupleMemoryContext(estate));
3251 
3252  if (newtuple)
3253  ereport(ERROR,
3254  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
3255  errmsg("BEFORE STATEMENT trigger cannot return a value")));
3256  }
3257 }
bool trig_truncate_before_statement
Definition: reltrigger.h:72

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().

◆ ExecBSUpdateTriggers()

void ExecBSUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2869 of file trigger.c.

2870 {
2871  TriggerDesc *trigdesc;
2872  int i;
2873  TriggerData LocTriggerData = {0};
2874  Bitmapset *updatedCols;
2875 
2876  trigdesc = relinfo->ri_TrigDesc;
2877 
2878  if (trigdesc == NULL)
2879  return;
2880  if (!trigdesc->trig_update_before_statement)
2881  return;
2882 
2883  /* no-op if we already fired BS triggers in this context */
2885  CMD_UPDATE))
2886  return;
2887 
2888  /* statement-level triggers operate on the parent table */
2889  Assert(relinfo->ri_RootResultRelInfo == NULL);
2890 
2891  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2892 
2893  LocTriggerData.type = T_TriggerData;
2894  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2896  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2897  LocTriggerData.tg_updatedcols = updatedCols;
2898  for (i = 0; i < trigdesc->numtriggers; i++)
2899  {
2900  Trigger *trigger = &trigdesc->triggers[i];
2901  HeapTuple newtuple;
2902 
2903  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2904  TRIGGER_TYPE_STATEMENT,
2905  TRIGGER_TYPE_BEFORE,
2906  TRIGGER_TYPE_UPDATE))
2907  continue;
2908  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2909  updatedCols, NULL, NULL))
2910  continue;
2911 
2912  LocTriggerData.tg_trigger = trigger;
2913  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2914  i,
2915  relinfo->ri_TrigFunctions,
2916  relinfo->ri_TrigInstrument,
2917  GetPerTupleMemoryContext(estate));
2918 
2919  if (newtuple)
2920  ereport(ERROR,
2921  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2922  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2923  }
2924 }
@ CMD_UPDATE
Definition: nodes.h:722
bool trig_update_before_statement
Definition: reltrigger.h:64

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

Referenced by fireBSTriggers().

◆ ExecIRDeleteTriggers()

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

Definition at line 2822 of file trigger.c.

2824 {
2825  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2826  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2827  TriggerData LocTriggerData = {0};
2828  int i;
2829 
2830  LocTriggerData.type = T_TriggerData;
2831  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2834  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2835 
2836  ExecForceStoreHeapTuple(trigtuple, slot, false);
2837 
2838  for (i = 0; i < trigdesc->numtriggers; i++)
2839  {
2840  HeapTuple rettuple;
2841  Trigger *trigger = &trigdesc->triggers[i];
2842 
2843  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2844  TRIGGER_TYPE_ROW,
2845  TRIGGER_TYPE_INSTEAD,
2846  TRIGGER_TYPE_DELETE))
2847  continue;
2848  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2849  NULL, slot, NULL))
2850  continue;
2851 
2852  LocTriggerData.tg_trigslot = slot;
2853  LocTriggerData.tg_trigtuple = trigtuple;
2854  LocTriggerData.tg_trigger = trigger;
2855  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2856  i,
2857  relinfo->ri_TrigFunctions,
2858  relinfo->ri_TrigInstrument,
2859  GetPerTupleMemoryContext(estate));
2860  if (rettuple == NULL)
2861  return false; /* Delete was suppressed */
2862  if (rettuple != trigtuple)
2863  heap_freetuple(rettuple);
2864  }
2865  return true;
2866 }
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:102

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().

◆ ExecIRInsertTriggers()

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

Definition at line 2565 of file trigger.c.

2567 {
2568  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2569  HeapTuple newtuple = NULL;
2570  bool should_free;
2571  TriggerData LocTriggerData = {0};
2572  int i;
2573 
2574  LocTriggerData.type = T_TriggerData;
2575  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2578  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2579  for (i = 0; i < trigdesc->numtriggers; i++)
2580  {
2581  Trigger *trigger = &trigdesc->triggers[i];
2582  HeapTuple oldtuple;
2583 
2584  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2585  TRIGGER_TYPE_ROW,
2586  TRIGGER_TYPE_INSTEAD,
2587  TRIGGER_TYPE_INSERT))
2588  continue;
2589  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2590  NULL, NULL, slot))
2591  continue;
2592 
2593  if (!newtuple)
2594  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2595 
2596  LocTriggerData.tg_trigslot = slot;
2597  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2598  LocTriggerData.tg_trigger = trigger;
2599  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2600  i,
2601  relinfo->ri_TrigFunctions,
2602  relinfo->ri_TrigInstrument,
2603  GetPerTupleMemoryContext(estate));
2604  if (newtuple == NULL)
2605  {
2606  if (should_free)
2607  heap_freetuple(oldtuple);
2608  return false; /* "do nothing" */
2609  }
2610  else if (newtuple != oldtuple)
2611  {
2612  ExecForceStoreHeapTuple(newtuple, slot, false);
2613 
2614  if (should_free)
2615  heap_freetuple(oldtuple);
2616 
2617  /* signal tuple should be re-fetched if used */
2618  newtuple = NULL;
2619  }
2620  }
2621 
2622  return true;
2623 }

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().

◆ ExecIRUpdateTriggers()

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

Definition at line 3147 of file trigger.c.

3149 {
3150  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3151  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
3152  HeapTuple newtuple = NULL;
3153  bool should_free;
3154  TriggerData LocTriggerData = {0};
3155  int i;
3156 
3157  LocTriggerData.type = T_TriggerData;
3158  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
3161  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3162 
3163  ExecForceStoreHeapTuple(trigtuple, oldslot, false);
3164 
3165  for (i = 0; i < trigdesc->numtriggers; i++)
3166  {
3167  Trigger *trigger = &trigdesc->triggers[i];
3168  HeapTuple oldtuple;
3169 
3170  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3171  TRIGGER_TYPE_ROW,
3172  TRIGGER_TYPE_INSTEAD,
3173  TRIGGER_TYPE_UPDATE))
3174  continue;
3175  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3176  NULL, oldslot, newslot))
3177  continue;
3178 
3179  if (!newtuple)
3180  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
3181 
3182  LocTriggerData.tg_trigslot = oldslot;
3183  LocTriggerData.tg_trigtuple = trigtuple;
3184  LocTriggerData.tg_newslot = newslot;
3185  LocTriggerData.tg_newtuple = oldtuple = newtuple;
3186 
3187  LocTriggerData.tg_trigger = trigger;
3188  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3189  i,
3190  relinfo->ri_TrigFunctions,
3191  relinfo->ri_TrigInstrument,
3192  GetPerTupleMemoryContext(estate));
3193  if (newtuple == NULL)
3194  {
3195  return false; /* "do nothing" */
3196  }
3197  else if (newtuple != oldtuple)
3198  {
3199  ExecForceStoreHeapTuple(newtuple, newslot, false);
3200 
3201  if (should_free)
3202  heap_freetuple(oldtuple);
3203 
3204  /* signal tuple should be re-fetched if used */
3205  newtuple = NULL;
3206  }
3207  }
3208 
3209  return true;
3210 }

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().

◆ FindTriggerIncompatibleWithInheritance()

const char* FindTriggerIncompatibleWithInheritance ( TriggerDesc trigdesc)

Definition at line 2286 of file trigger.c.

2287 {
2288  if (trigdesc != NULL)
2289  {
2290  int i;
2291 
2292  for (i = 0; i < trigdesc->numtriggers; ++i)
2293  {
2294  Trigger *trigger = &trigdesc->triggers[i];
2295 
2296  if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
2297  return trigger->tgname;
2298  }
2299  }
2300 
2301  return NULL;
2302 }

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

Referenced by ATExecAddInherit(), and ATExecAttachPartition().

◆ FreeTriggerDesc()

void FreeTriggerDesc ( TriggerDesc trigdesc)

Definition at line 2154 of file trigger.c.

2155 {
2156  Trigger *trigger;
2157  int i;
2158 
2159  if (trigdesc == NULL)
2160  return;
2161 
2162  trigger = trigdesc->triggers;
2163  for (i = 0; i < trigdesc->numtriggers; i++)
2164  {
2165  pfree(trigger->tgname);
2166  if (trigger->tgnattr > 0)
2167  pfree(trigger->tgattr);
2168  if (trigger->tgnargs > 0)
2169  {
2170  while (--(trigger->tgnargs) >= 0)
2171  pfree(trigger->tgargs[trigger->tgnargs]);
2172  pfree(trigger->tgargs);
2173  }
2174  if (trigger->tgqual)
2175  pfree(trigger->tgqual);
2176  if (trigger->tgoldtable)
2177  pfree(trigger->tgoldtable);
2178  if (trigger->tgnewtable)
2179  pfree(trigger->tgnewtable);
2180  trigger++;
2181  }
2182  pfree(trigdesc->triggers);
2183  pfree(trigdesc);
2184 }

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

Referenced by RelationBuildTriggers(), and RelationDestroyRelation().

◆ get_trigger_oid()

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

Definition at line 1415 of file trigger.c.

1416 {
1417  Relation tgrel;
1418  ScanKeyData skey[2];
1419  SysScanDesc tgscan;
1420  HeapTuple tup;
1421  Oid oid;
1422 
1423  /*
1424  * Find the trigger, verify permissions, set up object address
1425  */
1426  tgrel = table_open(TriggerRelationId, AccessShareLock);
1427 
1428  ScanKeyInit(&skey[0],
1429  Anum_pg_trigger_tgrelid,
1430  BTEqualStrategyNumber, F_OIDEQ,
1431  ObjectIdGetDatum(relid));
1432  ScanKeyInit(&skey[1],
1433  Anum_pg_trigger_tgname,
1434  BTEqualStrategyNumber, F_NAMEEQ,
1435  CStringGetDatum(trigname));
1436 
1437  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1438  NULL, 2, skey);
1439 
1440  tup = systable_getnext(tgscan);
1441 
1442  if (!HeapTupleIsValid(tup))
1443  {
1444  if (!missing_ok)
1445  ereport(ERROR,
1446  (errcode(ERRCODE_UNDEFINED_OBJECT),
1447  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1448  trigname, get_rel_name(relid))));
1449  oid = InvalidOid;
1450  }
1451  else
1452  {
1453  oid = ((Form_pg_trigger) GETSTRUCT(tup))->oid;
1454  }
1455 
1456  systable_endscan(tgscan);
1457  table_close(tgrel, AccessShareLock);
1458  return oid;
1459 }

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

Referenced by get_object_address_relobject().

◆ MakeTransitionCaptureState()

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

Definition at line 4825 of file trigger.c.

4826 {
4828  bool need_old_upd,
4829  need_new_upd,
4830  need_old_del,
4831  need_new_ins;
4832  AfterTriggersTableData *table;
4833  MemoryContext oldcxt;
4834  ResourceOwner saveResourceOwner;
4835 
4836  if (trigdesc == NULL)
4837  return NULL;
4838 
4839  /* Detect which table(s) we need. */
4840  switch (cmdType)
4841  {
4842  case CMD_INSERT:
4843  need_old_upd = need_old_del = need_new_upd = false;
4844  need_new_ins = trigdesc->trig_insert_new_table;
4845  break;
4846  case CMD_UPDATE:
4847  need_old_upd = trigdesc->trig_update_old_table;
4848  need_new_upd = trigdesc->trig_update_new_table;
4849  need_old_del = need_new_ins = false;
4850  break;
4851  case CMD_DELETE:
4852  need_old_del = trigdesc->trig_delete_old_table;
4853  need_old_upd = need_new_upd = need_new_ins = false;
4854  break;
4855  case CMD_MERGE:
4856  need_old_upd = trigdesc->trig_update_old_table;
4857  need_new_upd = trigdesc->trig_update_new_table;
4858  need_old_del = trigdesc->trig_delete_old_table;
4859  need_new_ins = trigdesc->trig_insert_new_table;
4860  break;
4861  default:
4862  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4863  /* keep compiler quiet */
4864  need_old_upd = need_new_upd = need_old_del = need_new_ins = false;
4865  break;
4866  }
4867  if (!need_old_upd && !need_new_upd && !need_new_ins && !need_old_del)
4868  return NULL;
4869 
4870  /* Check state, like AfterTriggerSaveEvent. */
4871  if (afterTriggers.query_depth < 0)
4872  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4873 
4874  /* Be sure we have enough space to record events at this query depth. */
4877 
4878  /*
4879  * Find or create an AfterTriggersTableData struct to hold the
4880  * tuplestore(s). If there's a matching struct but it's marked closed,
4881  * ignore it; we need a newer one.
4882  *
4883  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4884  * allocated in the current (sub)transaction's CurTransactionContext, and
4885  * the tuplestores are managed by the (sub)transaction's resource owner.
4886  * This is sufficient lifespan because we do not allow triggers using
4887  * transition tables to be deferrable; they will be fired during
4888  * AfterTriggerEndQuery, after which it's okay to delete the data.
4889  */
4890  table = GetAfterTriggersTableData(relid, cmdType);
4891 
4892  /* Now create required tuplestore(s), if we don't have them already. */
4894  saveResourceOwner = CurrentResourceOwner;
4896 
4897  if (need_old_upd && table->old_upd_tuplestore == NULL)
4898  table->old_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4899  if (need_new_upd && table->new_upd_tuplestore == NULL)
4900  table->new_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4901  if (need_old_del && table->old_del_tuplestore == NULL)
4902  table->old_del_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4903  if (need_new_ins && table->new_ins_tuplestore == NULL)
4904  table->new_ins_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4905 
4906  CurrentResourceOwner = saveResourceOwner;
4907  MemoryContextSwitchTo(oldcxt);
4908 
4909  /* Now build the TransitionCaptureState struct, in caller's context */
4911  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4912  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4913  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4914  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4915  state->tcs_private = table;
4916 
4917  return state;
4918 }
int work_mem
Definition: globals.c:125
void * palloc0(Size size)
Definition: mcxt.c:1099
MemoryContext CurTransactionContext
Definition: mcxt.c:54
@ CMD_MERGE
Definition: nodes.h:725
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:147
Tuplestorestate * old_upd_tuplestore
Definition: trigger.c:3843
Tuplestorestate * new_upd_tuplestore
Definition: trigger.c:3845
Tuplestorestate * old_del_tuplestore
Definition: trigger.c:3847
Tuplestorestate * new_ins_tuplestore
Definition: trigger.c:3849
bool trig_update_new_table
Definition: reltrigger.h:77
bool trig_insert_new_table
Definition: reltrigger.h:75
bool trig_delete_old_table
Definition: reltrigger.h:78
bool trig_update_old_table
Definition: reltrigger.h:76
static AfterTriggersTableData * GetAfterTriggersTableData(Oid relid, CmdType cmdType)
Definition: trigger.c:4741
static void AfterTriggerEnlargeQueryState(void)
Definition: trigger.c:5475
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318

References AfterTriggerEnlargeQueryState(), afterTriggers, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, CurrentResourceOwner, CurTransactionContext, CurTransactionResourceOwner, elog, ERROR, GetAfterTriggersTableData(), AfterTriggersData::maxquerydepth, MemoryContextSwitchTo(), AfterTriggersTableData::new_ins_tuplestore, AfterTriggersTableData::new_upd_tuplestore, AfterTriggersTableData::old_del_tuplestore, AfterTriggersTableData::old_upd_tuplestore, palloc0(), AfterTriggersData::query_depth, 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().

◆ RelationBuildTriggers()

void RelationBuildTriggers ( Relation  relation)

Definition at line 1870 of file trigger.c.

1871 {
1872  TriggerDesc *trigdesc;
1873  int numtrigs;
1874  int maxtrigs;
1875  Trigger *triggers;
1876  Relation tgrel;
1877  ScanKeyData skey;
1878  SysScanDesc tgscan;
1879  HeapTuple htup;
1880  MemoryContext oldContext;
1881  int i;
1882 
1883  /*
1884  * Allocate a working array to hold the triggers (the array is extended if
1885  * necessary)
1886  */
1887  maxtrigs = 16;
1888  triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
1889  numtrigs = 0;
1890 
1891  /*
1892  * Note: since we scan the triggers using TriggerRelidNameIndexId, we will
1893  * be reading the triggers in name order, except possibly during
1894  * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
1895  * ensures that triggers will be fired in name order.
1896  */
1897  ScanKeyInit(&skey,
1898  Anum_pg_trigger_tgrelid,
1899  BTEqualStrategyNumber, F_OIDEQ,
1900  ObjectIdGetDatum(RelationGetRelid(relation)));
1901 
1902  tgrel = table_open(TriggerRelationId, AccessShareLock);
1903  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1904  NULL, 1, &skey);
1905 
1906  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
1907  {
1908  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
1909  Trigger *build;
1910  Datum datum;
1911  bool isnull;
1912 
1913  if (numtrigs >= maxtrigs)
1914  {
1915  maxtrigs *= 2;
1916  triggers = (Trigger *) repalloc(triggers, maxtrigs * sizeof(Trigger));
1917  }
1918  build = &(triggers[numtrigs]);
1919 
1920  build->tgoid = pg_trigger->oid;
1922  NameGetDatum(&pg_trigger->tgname)));
1923  build->tgfoid = pg_trigger->tgfoid;
1924  build->tgtype = pg_trigger->tgtype;
1925  build->tgenabled = pg_trigger->tgenabled;
1926  build->tgisinternal = pg_trigger->tgisinternal;
1927  build->tgisclone = OidIsValid(pg_trigger->tgparentid);
1928  build->tgconstrrelid = pg_trigger->tgconstrrelid;
1929  build->tgconstrindid = pg_trigger->tgconstrindid;
1930  build->tgconstraint = pg_trigger->tgconstraint;
1931  build->tgdeferrable = pg_trigger->tgdeferrable;
1932  build->tginitdeferred = pg_trigger->tginitdeferred;
1933  build->tgnargs = pg_trigger->tgnargs;
1934  /* tgattr is first var-width field, so OK to access directly */
1935  build->tgnattr = pg_trigger->tgattr.dim1;
1936  if (build->tgnattr > 0)
1937  {
1938  build->tgattr = (int16 *) palloc(build->tgnattr * sizeof(int16));
1939  memcpy(build->tgattr, &(pg_trigger->tgattr.values),
1940  build->tgnattr * sizeof(int16));
1941  }
1942  else
1943  build->tgattr = NULL;
1944  if (build->tgnargs > 0)
1945  {
1946  bytea *val;
1947  char *p;
1948 
1950  Anum_pg_trigger_tgargs,
1951  tgrel->rd_att, &isnull));
1952  if (isnull)
1953  elog(ERROR, "tgargs is null in trigger for relation \"%s\"",
1954  RelationGetRelationName(relation));
1955  p = (char *) VARDATA_ANY(val);
1956  build->tgargs = (char **) palloc(build->tgnargs * sizeof(char *));
1957  for (i = 0; i < build->tgnargs; i++)
1958  {
1959  build->tgargs[i] = pstrdup(p);
1960  p += strlen(p) + 1;
1961  }
1962  }
1963  else
1964  build->tgargs = NULL;
1965 
1966  datum = fastgetattr(htup, Anum_pg_trigger_tgoldtable,
1967  tgrel->rd_att, &isnull);
1968  if (!isnull)
1969  build->tgoldtable =
1971  else
1972  build->tgoldtable = NULL;
1973 
1974  datum = fastgetattr(htup, Anum_pg_trigger_tgnewtable,
1975  tgrel->rd_att, &isnull);
1976  if (!isnull)
1977  build->tgnewtable =
1979  else
1980  build->tgnewtable = NULL;
1981 
1982  datum = fastgetattr(htup, Anum_pg_trigger_tgqual,
1983  tgrel->rd_att, &isnull);
1984  if (!isnull)
1985  build->tgqual = TextDatumGetCString(datum);
1986  else
1987  build->tgqual = NULL;
1988 
1989  numtrigs++;
1990  }
1991 
1992  systable_endscan(tgscan);
1993  table_close(tgrel, AccessShareLock);
1994 
1995  /* There might not be any triggers */
1996  if (numtrigs == 0)
1997  {
1998  pfree(triggers);
1999  return;
2000  }
2001 
2002  /* Build trigdesc */
2003  trigdesc = (TriggerDesc *) palloc0(sizeof(TriggerDesc));
2004  trigdesc->triggers = triggers;
2005  trigdesc->numtriggers = numtrigs;
2006  for (i = 0; i < numtrigs; i++)
2007  SetTriggerFlags(trigdesc, &(triggers[i]));
2008 
2009  /* Copy completed trigdesc into cache storage */
2011  relation->trigdesc = CopyTriggerDesc(trigdesc);
2012  MemoryContextSwitchTo(oldContext);
2013 
2014  /* Release working memory */
2015  FreeTriggerDesc(trigdesc);
2016 }
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define DatumGetByteaPP(X)
Definition: fmgr.h:291
static Datum fastgetattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:745
long val
Definition: informix.c:664
MemoryContext CacheMemoryContext
Definition: mcxt.c:51
Datum nameout(PG_FUNCTION_ARGS)
Definition: name.c:71
#define VARDATA_ANY(PTR)
Definition: postgres.h:361
#define NameGetDatum(X)
Definition: postgres.h:639
#define DatumGetCString(X)
Definition: postgres.h:610
TriggerDesc * trigdesc
Definition: rel.h:115
char tgenabled
Definition: reltrigger.h:30
Oid tgoid
Definition: reltrigger.h:25
Oid tgconstrindid
Definition: reltrigger.h:34
Oid tgconstraint
Definition: reltrigger.h:35
Oid tgconstrrelid
Definition: reltrigger.h:33
Oid tgfoid
Definition: reltrigger.h:28
bool tgdeferrable
Definition: reltrigger.h:36
bool tginitdeferred
Definition: reltrigger.h:37
bool tgisinternal
Definition: reltrigger.h:31
Definition: c.h:633
void FreeTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:2154
TriggerDesc * CopyTriggerDesc(TriggerDesc *trigdesc)
Definition: trigger.c:2099
static void SetTriggerFlags(TriggerDesc *trigdesc, Trigger *trigger)
Definition: trigger.c:2022

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

Referenced by RelationBuildDesc(), and RelationCacheInitializePhase3().

◆ RemoveTriggerById()

void RemoveTriggerById ( Oid  trigOid)

Definition at line 1336 of file trigger.c.

1337 {
1338  Relation tgrel;
1339  SysScanDesc tgscan;
1340  ScanKeyData skey[1];
1341  HeapTuple tup;
1342  Oid relid;
1343  Relation rel;
1344 
1345  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1346 
1347  /*
1348  * Find the trigger to delete.
1349  */
1350  ScanKeyInit(&skey[0],
1351  Anum_pg_trigger_oid,
1352  BTEqualStrategyNumber, F_OIDEQ,
1353  ObjectIdGetDatum(trigOid));
1354 
1355  tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
1356  NULL, 1, skey);
1357 
1358  tup = systable_getnext(tgscan);
1359  if (!HeapTupleIsValid(tup))
1360  elog(ERROR, "could not find tuple for trigger %u", trigOid);
1361 
1362  /*
1363  * Open and exclusive-lock the relation the trigger belongs to.
1364  */
1365  relid = ((Form_pg_trigger) GETSTRUCT(tup))->tgrelid;
1366 
1367  rel = table_open(relid, AccessExclusiveLock);
1368 
1369  if (rel->rd_rel->relkind != RELKIND_RELATION &&
1370  rel->rd_rel->relkind != RELKIND_VIEW &&
1371  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
1372  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1373  ereport(ERROR,
1374  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1375  errmsg("relation \"%s\" cannot have triggers",
1377  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
1378 
1380  ereport(ERROR,
1381  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1382  errmsg("permission denied: \"%s\" is a system catalog",
1383  RelationGetRelationName(rel))));
1384 
1385  /*
1386  * Delete the pg_trigger tuple.
1387  */
1388  CatalogTupleDelete(tgrel, &tup->t_self);
1389 
1390  systable_endscan(tgscan);
1391  table_close(tgrel, RowExclusiveLock);
1392 
1393  /*
1394  * We do not bother to try to determine whether any other triggers remain,
1395  * which would be needed in order to decide whether it's safe to clear the
1396  * relation's relhastriggers. (In any case, there might be a concurrent
1397  * process adding new triggers.) Instead, just force a relcache inval to
1398  * make other backends (and this one too!) rebuild their relcache entries.
1399  * There's no great harm in leaving relhastriggers true even if there are
1400  * no triggers left.
1401  */
1403 
1404  /* Keep lock on trigger's rel until end of xact */
1405  table_close(rel, NoLock);
1406 }
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
#define AccessExclusiveLock
Definition: lockdefs.h:43

References AccessExclusiveLock, allowSystemTableMods, BTEqualStrategyNumber, CacheInvalidateRelcache(), CatalogTupleDelete(), elog, ereport, errcode(), errdetail_relkind_not_supported(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, IsSystemRelation(), NoLock, ObjectIdGetDatum, RelationData::rd_rel, RelationGetRelationName, RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by doDeletion().

◆ renametrig()

ObjectAddress renametrig ( RenameStmt stmt)

Definition at line 1512 of file trigger.c.

1513 {
1514  Oid tgoid;
1515  Relation targetrel;
1516  Relation tgrel;
1517  HeapTuple tuple;
1518  SysScanDesc tgscan;
1519  ScanKeyData key[2];
1520  Oid relid;
1521  ObjectAddress address;
1522 
1523  /*
1524  * Look up name, check permissions, and acquire lock (which we will NOT
1525  * release until end of transaction).
1526  */
1528  0,
1530  NULL);
1531 
1532  /* Have lock already, so just need to build relcache entry. */
1533  targetrel = relation_open(relid, NoLock);
1534 
1535  /*
1536  * On partitioned tables, this operation recurses to partitions. Lock all
1537  * tables upfront.
1538  */
1539  if (targetrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1540  (void) find_all_inheritors(relid, AccessExclusiveLock, NULL);
1541 
1542  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1543 
1544  /*
1545  * Search for the trigger to modify.
1546  */
1547  ScanKeyInit(&key[0],
1548  Anum_pg_trigger_tgrelid,
1549  BTEqualStrategyNumber, F_OIDEQ,
1550  ObjectIdGetDatum(relid));
1551  ScanKeyInit(&key[1],
1552  Anum_pg_trigger_tgname,
1553  BTEqualStrategyNumber, F_NAMEEQ,
1554  PointerGetDatum(stmt->subname));
1555  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1556  NULL, 2, key);
1557  if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1558  {
1559  Form_pg_trigger trigform;
1560 
1561  trigform = (Form_pg_trigger) GETSTRUCT(tuple);
1562  tgoid = trigform->oid;
1563 
1564  /*
1565  * If the trigger descends from a trigger on a parent partitioned
1566  * table, reject the rename. We don't allow a trigger in a partition
1567  * to differ in name from that of its parent: that would lead to an
1568  * inconsistency that pg_dump would not reproduce.
1569  */
1570  if (OidIsValid(trigform->tgparentid))
1571  ereport(ERROR,
1572  errmsg("cannot rename trigger \"%s\" on table \"%s\"",
1573  stmt->subname, RelationGetRelationName(targetrel)),
1574  errhint("Rename trigger on partitioned table \"%s\" instead.",
1575  get_rel_name(get_partition_parent(relid, false))));
1576 
1577 
1578  /* Rename the trigger on this relation ... */
1579  renametrig_internal(tgrel, targetrel, tuple, stmt->newname,
1580  stmt->subname);
1581 
1582  /* ... and if it is partitioned, recurse to its partitions */
1583  if (targetrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1584  {
1585  PartitionDesc partdesc = RelationGetPartitionDesc(targetrel, true);
1586 
1587  for (int i = 0; i < partdesc->nparts; i++)
1588  {
1589  Oid partitionId = partdesc->oids[i];
1590 
1591  renametrig_partition(tgrel, partitionId, trigform->oid,
1592  stmt->newname, stmt->subname);
1593  }
1594  }
1595  }
1596  else
1597  {
1598  ereport(ERROR,
1599  (errcode(ERRCODE_UNDEFINED_OBJECT),
1600  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1601  stmt->subname, RelationGetRelationName(targetrel))));
1602  }
1603 
1604  ObjectAddressSet(address, TriggerRelationId, tgoid);
1605 
1606  systable_endscan(tgscan);
1607 
1608  table_close(tgrel, RowExclusiveLock);
1609 
1610  /*
1611  * Close rel, but keep exclusive lock!
1612  */
1613  relation_close(targetrel, NoLock);
1614 
1615  return address;
1616 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:238
Oid get_partition_parent(Oid relid, bool even_if_detached)
Definition: partition.c:54
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
RangeVar * relation
Definition: parsenodes.h:3407
char * newname
Definition: parsenodes.h:3411
char * subname
Definition: parsenodes.h:3409
static void renametrig_internal(Relation tgrel, Relation targetrel, HeapTuple trigtup, const char *newname, const char *expected_name)
Definition: trigger.c:1626
static void RangeVarCallbackForRenameTrigger(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: trigger.c:1465
static void renametrig_partition(Relation tgrel, Oid partitionId, Oid parentTriggerOid, const char *newname, const char *expected_name)
Definition: trigger.c:1697

References AccessExclusiveLock, BTEqualStrategyNumber, ereport, errcode(), errhint(), errmsg(), ERROR, find_all_inheritors(), get_partition_parent(), get_rel_name(), GETSTRUCT, HeapTupleIsValid, i, sort-test::key, RenameStmt::newname, NoLock, PartitionDescData::nparts, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, PartitionDescData::oids, PointerGetDatum, RangeVarCallbackForRenameTrigger(), RangeVarGetRelidExtended(), RelationData::rd_rel, RenameStmt::relation, relation_close(), relation_open(), RelationGetPartitionDesc(), RelationGetRelationName, renametrig_internal(), renametrig_partition(), RowExclusiveLock, ScanKeyInit(), RenameStmt::subname, systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), and table_open().

Referenced by ExecRenameStmt().

◆ RI_FKey_fk_upd_check_required()

bool RI_FKey_fk_upd_check_required ( Trigger trigger,
Relation  fk_rel,
TupleTableSlot old_slot,
TupleTableSlot new_slot 
)

Definition at line 1262 of file ri_triggers.c.

1264 {
1265  const RI_ConstraintInfo *riinfo;
1266  int ri_nullcheck;
1267  Datum xminDatum;
1268  TransactionId xmin;
1269  bool isnull;
1270 
1271  /*
1272  * AfterTriggerSaveEvent() handles things such that this function is never
1273  * called for partitioned tables.
1274  */
1275  Assert(fk_rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE);
1276 
1277  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1278 
1279  ri_nullcheck = ri_NullCheck(RelationGetDescr(fk_rel), newslot, riinfo, false);
1280 
1281  /*
1282  * If all new key values are NULL, the row satisfies the constraint, so no
1283  * check is needed.
1284  */
1285  if (ri_nullcheck == RI_KEYS_ALL_NULL)
1286  return false;
1287 
1288  /*
1289  * If some new key values are NULL, the behavior depends on the match
1290  * type.
1291  */
1292  else if (ri_nullcheck == RI_KEYS_SOME_NULL)
1293  {
1294  switch (riinfo->confmatchtype)
1295  {
1296  case FKCONSTR_MATCH_SIMPLE:
1297 
1298  /*
1299  * If any new key value is NULL, the row must satisfy the
1300  * constraint, so no check is needed.
1301  */
1302  return false;
1303 
1305 
1306  /*
1307  * Don't know, must run full check.
1308  */
1309  break;
1310 
1311  case FKCONSTR_MATCH_FULL:
1312 
1313  /*
1314  * If some new key values are NULL, the row fails the
1315  * constraint. We must not throw error here, because the row
1316  * might get invalidated before the constraint is to be
1317  * checked, but we should queue the event to apply the check
1318  * later.
1319  */
1320  return true;
1321  }
1322  }
1323 
1324  /*
1325  * Continues here for no new key values are NULL, or we couldn't decide
1326  * yet.
1327  */
1328 
1329  /*
1330  * If the original row was inserted by our own transaction, we must fire
1331  * the trigger whether or not the keys are equal. This is because our
1332  * UPDATE will invalidate the INSERT so that the INSERT RI trigger will
1333  * not do anything; so we had better do the UPDATE check. (We could skip
1334  * this if we knew the INSERT trigger already fired, but there is no easy
1335  * way to know that.)
1336  */
1337  xminDatum = slot_getsysattr(oldslot, MinTransactionIdAttributeNumber, &isnull);
1338  Assert(!isnull);
1339  xmin = DatumGetTransactionId(xminDatum);
1341  return true;
1342 
1343  /* If all old and new key values are equal, no check is needed */
1344  if (ri_KeysEqual(fk_rel, oldslot, newslot, riinfo, false))
1345  return false;
1346 
1347  /* Else we need to fire the trigger. */
1348  return true;
1349 }
uint32 TransactionId
Definition: c.h:598
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2605
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2604
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2603
#define DatumGetTransactionId(X)
Definition: postgres.h:558
#define RI_KEYS_SOME_NULL
Definition: ri_triggers.c:67
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2792
static int ri_NullCheck(TupleDesc tupdesc, TupleTableSlot *slot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2633
#define RI_KEYS_ALL_NULL
Definition: ri_triggers.c:66
static const RI_ConstraintInfo * ri_FetchConstraintInfo(Trigger *trigger, Relation trig_rel, bool rel_is_pk)
Definition: ri_triggers.c:2053
#define MinTransactionIdAttributeNumber
Definition: sysattr.h:22
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:402
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:922

References Assert(), RI_ConstraintInfo::confmatchtype, DatumGetTransactionId, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_PARTIAL, FKCONSTR_MATCH_SIMPLE, MinTransactionIdAttributeNumber, RelationData::rd_rel, RelationGetDescr, ri_FetchConstraintInfo(), RI_KEYS_ALL_NULL, RI_KEYS_SOME_NULL, ri_KeysEqual(), ri_NullCheck(), slot_getsysattr(), and TransactionIdIsCurrentTransactionId().

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_pk_upd_check_required()

bool RI_FKey_pk_upd_check_required ( Trigger trigger,
Relation  pk_rel,
TupleTableSlot old_slot,
TupleTableSlot new_slot 
)

Definition at line 1230 of file ri_triggers.c.

1232 {
1233  const RI_ConstraintInfo *riinfo;
1234 
1235  riinfo = ri_FetchConstraintInfo(trigger, pk_rel, true);
1236 
1237  /*
1238  * If any old key value is NULL, the row could not have been referenced by
1239  * an FK row, so no check is needed.
1240  */
1241  if (ri_NullCheck(RelationGetDescr(pk_rel), oldslot, riinfo, true) != RI_KEYS_NONE_NULL)
1242  return false;
1243 
1244  /* If all old and new key values are equal, no check is needed */
1245  if (newslot && ri_KeysEqual(pk_rel, oldslot, newslot, riinfo, true))
1246  return false;
1247 
1248  /* Else we need to fire the trigger. */
1249  return true;
1250 }
#define RI_KEYS_NONE_NULL
Definition: ri_triggers.c:68

References RelationGetDescr, ri_FetchConstraintInfo(), RI_KEYS_NONE_NULL, ri_KeysEqual(), and ri_NullCheck().

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_trigger_type()

int RI_FKey_trigger_type ( Oid  tgfoid)

Definition at line 2998 of file ri_triggers.c.

2999 {
3000  switch (tgfoid)
3001  {
3002  case F_RI_FKEY_CASCADE_DEL:
3003  case F_RI_FKEY_CASCADE_UPD:
3004  case F_RI_FKEY_RESTRICT_DEL:
3005  case F_RI_FKEY_RESTRICT_UPD:
3006  case F_RI_FKEY_SETNULL_DEL:
3007  case F_RI_FKEY_SETNULL_UPD:
3008  case F_RI_FKEY_SETDEFAULT_DEL:
3009  case F_RI_FKEY_SETDEFAULT_UPD:
3010  case F_RI_FKEY_NOACTION_DEL:
3011  case F_RI_FKEY_NOACTION_UPD:
3012  return RI_TRIGGER_PK;
3013 
3014  case F_RI_FKEY_CHECK_INS:
3015  case F_RI_FKEY_CHECK_UPD:
3016  return RI_TRIGGER_FK;
3017  }
3018 
3019  return RI_TRIGGER_NONE;
3020 }
#define RI_TRIGGER_FK
Definition: trigger.h:279
#define RI_TRIGGER_NONE
Definition: trigger.h:280
#define RI_TRIGGER_PK
Definition: trigger.h:278

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), and ExecCrossPartitionUpdateForeignKey().

◆ RI_Initial_Check()

bool RI_Initial_Check ( Trigger trigger,
Relation  fk_rel,
Relation  pk_rel 
)

Definition at line 1369 of file ri_triggers.c.

1370 {
1371  const RI_ConstraintInfo *riinfo;
1372  StringInfoData querybuf;
1373  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1374  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1375  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1376  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1377  RangeTblEntry *pkrte;
1378  RangeTblEntry *fkrte;
1379  const char *sep;
1380  const char *fk_only;
1381  const char *pk_only;
1382  int save_nestlevel;
1383  char workmembuf[32];
1384  int spi_result;
1385  SPIPlanPtr qplan;
1386 
1387  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1388 
1389  /*
1390  * Check to make sure current user has enough permissions to do the test
1391  * query. (If not, caller can fall back to the trigger method, which
1392  * works because it changes user IDs on the fly.)
1393  *
1394  * XXX are there any other show-stopper conditions to check?
1395  */
1396  pkrte = makeNode(RangeTblEntry);
1397  pkrte->rtekind = RTE_RELATION;
1398  pkrte->relid = RelationGetRelid(pk_rel);
1399  pkrte->relkind = pk_rel->rd_rel->relkind;
1400  pkrte->rellockmode = AccessShareLock;
1401  pkrte->requiredPerms = ACL_SELECT;
1402 
1403  fkrte = makeNode(RangeTblEntry);
1404  fkrte->rtekind = RTE_RELATION;
1405  fkrte->relid = RelationGetRelid(fk_rel);
1406  fkrte->relkind = fk_rel->rd_rel->relkind;
1407  fkrte->rellockmode = AccessShareLock;
1408  fkrte->requiredPerms = ACL_SELECT;
1409 
1410  for (int i = 0; i < riinfo->nkeys; i++)
1411  {
1412  int attno;
1413 
1414  attno = riinfo->pk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1415  pkrte->selectedCols = bms_add_member(pkrte->selectedCols, attno);
1416 
1417  attno = riinfo->fk_attnums[i] - FirstLowInvalidHeapAttributeNumber;
1418  fkrte->selectedCols = bms_add_member(fkrte->selectedCols, attno);
1419  }
1420 
1421  if (!ExecCheckRTPerms(list_make2(fkrte, pkrte), false))
1422  return false;
1423 
1424  /*
1425  * Also punt if RLS is enabled on either table unless this role has the
1426  * bypassrls right or is the table owner of the table(s) involved which
1427  * have RLS enabled.
1428  */
1430  ((pk_rel->rd_rel->relrowsecurity &&
1431  !pg_class_ownercheck(pkrte->relid, GetUserId())) ||
1432  (fk_rel->rd_rel->relrowsecurity &&
1433  !pg_class_ownercheck(fkrte->relid, GetUserId()))))
1434  return false;
1435 
1436  /*----------
1437  * The query string built is:
1438  * SELECT fk.keycols FROM [ONLY] relname fk
1439  * LEFT OUTER JOIN [ONLY] pkrelname pk
1440  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1441  * WHERE pk.pkkeycol1 IS NULL AND
1442  * For MATCH SIMPLE:
1443  * (fk.keycol1 IS NOT NULL [AND ...])
1444  * For MATCH FULL:
1445  * (fk.keycol1 IS NOT NULL [OR ...])
1446  *
1447  * We attach COLLATE clauses to the operators when comparing columns
1448  * that have different collations.
1449  *----------
1450  */
1451  initStringInfo(&querybuf);
1452  appendStringInfoString(&querybuf, "SELECT ");
1453  sep = "";
1454  for (int i = 0; i < riinfo->nkeys; i++)
1455  {
1456  quoteOneName(fkattname,
1457  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1458  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1459  sep = ", ";
1460  }
1461 
1462  quoteRelationName(pkrelname, pk_rel);
1463  quoteRelationName(fkrelname, fk_rel);
1464  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1465  "" : "ONLY ";
1466  pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1467  "" : "ONLY ";
1468  appendStringInfo(&querybuf,
1469  " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
1470  fk_only, fkrelname, pk_only, pkrelname);
1471 
1472  strcpy(pkattname, "pk.");
1473  strcpy(fkattname, "fk.");
1474  sep = "(";
1475  for (int i = 0; i < riinfo->nkeys; i++)
1476  {
1477  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1478  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1479  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1480  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1481 
1482  quoteOneName(pkattname + 3,
1483  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1484  quoteOneName(fkattname + 3,
1485  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1486  ri_GenerateQual(&querybuf, sep,
1487  pkattname, pk_type,
1488  riinfo->pf_eq_oprs[i],
1489  fkattname, fk_type);
1490  if (pk_coll != fk_coll)
1491  ri_GenerateQualCollation(&querybuf, pk_coll);
1492  sep = "AND";
1493  }
1494 
1495  /*
1496  * It's sufficient to test any one pk attribute for null to detect a join
1497  * failure.
1498  */
1499  quoteOneName(pkattname, RIAttName(pk_rel, riinfo->pk_attnums[0]));
1500  appendStringInfo(&querybuf, ") WHERE pk.%s IS NULL AND (", pkattname);
1501 
1502  sep = "";
1503  for (int i = 0; i < riinfo->nkeys; i++)
1504  {
1505  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1506  appendStringInfo(&querybuf,
1507  "%sfk.%s IS NOT NULL",
1508  sep, fkattname);
1509  switch (riinfo->confmatchtype)
1510  {
1511  case FKCONSTR_MATCH_SIMPLE:
1512  sep = " AND ";
1513  break;
1514  case FKCONSTR_MATCH_FULL:
1515  sep = " OR ";
1516  break;
1517  }
1518  }
1519  appendStringInfoChar(&querybuf, ')');
1520 
1521  /*
1522  * Temporarily increase work_mem so that the check query can be executed
1523  * more efficiently. It seems okay to do this because the query is simple
1524  * enough to not use a multiple of work_mem, and one typically would not
1525  * have many large foreign-key validations happening concurrently. So
1526  * this seems to meet the criteria for being considered a "maintenance"
1527  * operation, and accordingly we use maintenance_work_mem. However, we
1528  * must also set hash_mem_multiplier to 1, since it is surely not okay to
1529  * let that get applied to the maintenance_work_mem value.
1530  *
1531  * We use the equivalent of a function SET option to allow the setting to
1532  * persist for exactly the duration of the check query. guc.c also takes
1533  * care of undoing the setting on error.
1534  */
1535  save_nestlevel = NewGUCNestLevel();
1536 
1537  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1538  (void) set_config_option("work_mem", workmembuf,
1540  GUC_ACTION_SAVE, true, 0, false);
1541  (void) set_config_option("hash_mem_multiplier", "1",
1543  GUC_ACTION_SAVE, true, 0, false);
1544 
1545  if (SPI_connect() != SPI_OK_CONNECT)
1546  elog(ERROR, "SPI_connect failed");
1547 
1548  /*
1549  * Generate the plan. We don't need to cache it, and there are no
1550  * arguments to the plan.
1551  */
1552  qplan = SPI_prepare(querybuf.data, 0, NULL);
1553 
1554  if (qplan == NULL)
1555  elog(ERROR, "SPI_prepare returned %s for %s",
1557 
1558  /*
1559  * Run the plan. For safety we force a current snapshot to be used. (In
1560  * transaction-snapshot mode, this arguably violates transaction isolation
1561  * rules, but we really haven't got much choice.) We don't need to
1562  * register the snapshot, because SPI_execute_snapshot will see to it. We
1563  * need at most one tuple returned, so pass limit = 1.
1564  */
1565  spi_result = SPI_execute_snapshot(qplan,
1566  NULL, NULL,
1569  true, false, 1);
1570 
1571  /* Check result */
1572  if (spi_result != SPI_OK_SELECT)
1573  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1574 
1575  /* Did we find a tuple violating the constraint? */
1576  if (SPI_processed > 0)
1577  {
1578  TupleTableSlot *slot;
1579  HeapTuple tuple = SPI_tuptable->vals[0];
1580  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1581  RI_ConstraintInfo fake_riinfo;
1582 
1583  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1584 
1585  heap_deform_tuple(tuple, tupdesc,
1586  slot->tts_values, slot->tts_isnull);
1587  ExecStoreVirtualTuple(slot);
1588 
1589  /*
1590  * The columns to look at in the result tuple are 1..N, not whatever
1591  * they are in the fk_rel. Hack up riinfo so that the subroutines
1592  * called here will behave properly.
1593  *
1594  * In addition to this, we have to pass the correct tupdesc to
1595  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1596  * or fk_rel's tupdesc.
1597  */
1598  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1599  for (int i = 0; i < fake_riinfo.nkeys; i++)
1600  fake_riinfo.fk_attnums[i] = i + 1;
1601 
1602  /*
1603  * If it's MATCH FULL, and there are any nulls in the FK keys,
1604  * complain about that rather than the lack of a match. MATCH FULL
1605  * disallows partially-null FK rows.
1606  */
1607  if (fake_riinfo.confmatchtype == FKCONSTR_MATCH_FULL &&
1608  ri_NullCheck(tupdesc, slot, &fake_riinfo, false) != RI_KEYS_NONE_NULL)
1609  ereport(ERROR,
1610  (errcode(ERRCODE_FOREIGN_KEY_VIOLATION),
1611  errmsg("insert or update on table \"%s\" violates foreign key constraint \"%s\"",
1612  RelationGetRelationName(fk_rel),
1613  NameStr(fake_riinfo.conname)),
1614  errdetail("MATCH FULL does not allow mixing of null and nonnull key values."),
1615  errtableconstraint(fk_rel,
1616  NameStr(fake_riinfo.conname))));
1617 
1618  /*
1619  * We tell ri_ReportViolation we were doing the RI_PLAN_CHECK_LOOKUPPK
1620  * query, which isn't true, but will cause it to use
1621  * fake_riinfo.fk_attnums as we need.
1622  */
1623  ri_ReportViolation(&fake_riinfo,
1624  pk_rel, fk_rel,
1625  slot, tupdesc,
1626  RI_PLAN_CHECK_LOOKUPPK, false);
1627 
1629  }
1630 
1631  if (SPI_finish() != SPI_OK_FINISH)
1632  elog(ERROR, "SPI_finish failed");
1633 
1634  /*
1635  * Restore work_mem and hash_mem_multiplier.
1636  */
1637  AtEOXact_GUC(true, save_nestlevel);
1638 
1639  return true;
1640 }
bool has_bypassrls_privilege(Oid roleid)
Definition: aclchk.c:5815
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:5171
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:570
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:83
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1552
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
int maintenance_work_mem
Definition: globals.c:127
int NewGUCNestLevel(void)
Definition: guc.c:6476
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:6490
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:7564
@ GUC_ACTION_SAVE
Definition: guc.h:200
@ PGC_S_SESSION
Definition: guc.h:123
@ PGC_USERSET
Definition: guc.h:76
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
#define makeNode(_type_)
Definition: nodes.h:621
@ RTE_RELATION
Definition: parsenodes.h:998
#define ACL_SELECT
Definition: parsenodes.h:83
#define list_make2(x1, x2)
Definition: pg_list.h:208
int errtableconstraint(Relation rel, const char *conname)
Definition: relcache.c:5867
static void quoteOneName(char *buffer, const char *name)
Definition: ri_triggers.c:1868
#define RIAttType(rel, attnum)
Definition: ri_triggers.c:89
static void ri_GenerateQualCollation(StringInfo buf, Oid collation)
Definition: ri_triggers.c:1934
#define MAX_QUOTED_REL_NAME_LEN
Definition: ri_triggers.c:86
static void ri_ReportViolation(const RI_ConstraintInfo *riinfo, Relation pk_rel, Relation fk_rel, TupleTableSlot *violatorslot, TupleDesc tupdesc, int queryno, bool partgone) pg_attribute_noreturn()
Definition: ri_triggers.c:2475
static void quoteRelationName(char *buffer, Relation rel)
Definition: ri_triggers.c:1888
static void ri_GenerateQual(StringInfo buf, const char *sep, const char *leftop, Oid leftoptype, Oid opoid, const char *rightop, Oid rightoptype)
Definition: ri_triggers.c:1905
#define RIAttCollation(rel, attnum)
Definition: ri_triggers.c:90
#define RI_PLAN_CHECK_LOOKUPPK
Definition: ri_triggers.c:72
#define MAX_QUOTED_NAME_LEN
Definition: ri_triggers.c:85
#define RIAttName(rel, attnum)
Definition: ri_triggers.c:88
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:325
#define InvalidSnapshot