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 *trigname, bool missing_ok)
 
ObjectAddress renametrig (RenameStmt *stmt)
 
void EnableDisableTrigger (Relation rel, const char *tgname, Oid tgparent, char fires_when, bool skip_system, bool recurse, 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, TM_Result *tmresult, TM_FailureData *tmfd)
 
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 *newslot, TM_Result *tmresult, TM_FailureData *tmfd)
 
void ExecARUpdateTriggers (EState *estate, ResultRelInfo *relinfo, ResultRelInfo *src_partinfo, ResultRelInfo *dst_partinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *newslot, List *recheckIndexes, TransitionCaptureState *transition_capture, bool is_crosspart_update)
 
bool ExecIRUpdateTriggers (EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *newslot)
 
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 *oldslot, TupleTableSlot *newslot)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, TupleTableSlot *oldslot, TupleTableSlot *newslot)
 
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 283 of file trigger.h.

◆ RI_TRIGGER_NONE

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

Definition at line 284 of file trigger.h.

◆ RI_TRIGGER_PK

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

Definition at line 282 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 4980 of file trigger.c.

4981 {
4982  /* Increase the query stack depth */
4984 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3871

References afterTriggers, and AfterTriggersData::query_depth.

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

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 5263 of file trigger.c.

5264 {
5265  int my_level = GetCurrentTransactionNestLevel();
5266 
5267  /*
5268  * Allocate more space in the trans_stack if needed. (Note: because the
5269  * minimum nest level of a subtransaction is 2, we waste the first couple
5270  * entries of the array; not worth the notational effort to avoid it.)
5271  */
5272  while (my_level >= afterTriggers.maxtransdepth)
5273  {
5274  if (afterTriggers.maxtransdepth == 0)
5275  {
5276  /* Arbitrarily initialize for max of 8 subtransaction levels */
5279  8 * sizeof(AfterTriggersTransData));
5281  }
5282  else
5283  {
5284  /* repalloc will keep the stack in the same context */
5285  int new_alloc = afterTriggers.maxtransdepth * 2;
5286 
5289  new_alloc * sizeof(AfterTriggersTransData));
5290  afterTriggers.maxtransdepth = new_alloc;
5291  }
5292  }
5293 
5294  /*
5295  * Push the current information into the stack. The SET CONSTRAINTS state
5296  * is not saved until/unless changed. Likewise, we don't make a
5297  * per-subtransaction event context until needed.
5298  */
5299  afterTriggers.trans_stack[my_level].state = NULL;
5303 }
MemoryContext TopTransactionContext
Definition: mcxt.c:146
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1456
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1005
CommandId firing_counter
Definition: trigger.c:3811
AfterTriggersTransData * trans_stack
Definition: trigger.c:3822
AfterTriggerEventList events
Definition: trigger.c:3813
AfterTriggerEventList events
Definition: trigger.c:3837
SetConstraintState state
Definition: trigger.c:3836
CommandId firing_counter
Definition: trigger.c:3839
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:914

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

4949 {
4950  /*
4951  * Initialize after-trigger state structure to empty
4952  */
4953  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4955 
4956  /*
4957  * Verify that there is no leftover state remaining. If these assertions
4958  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4959  * up properly.
4960  */
4961  Assert(afterTriggers.state == NULL);
4962  Assert(afterTriggers.query_stack == NULL);
4964  Assert(afterTriggers.event_cxt == NULL);
4965  Assert(afterTriggers.events.head == NULL);
4966  Assert(afterTriggers.trans_stack == NULL);
4968 }
uint32 CommandId
Definition: c.h:650
Assert(fmt[strlen(fmt) - 1] !='\n')
AfterTriggerEventChunk * head
Definition: trigger.c:3705
SetConstraintState state
Definition: trigger.c:3812
AfterTriggersQueryData * query_stack
Definition: trigger.c:3817
MemoryContext event_cxt
Definition: trigger.c:3814

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

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

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

5312 {
5313  int my_level = GetCurrentTransactionNestLevel();
5315  AfterTriggerEvent event;
5316  AfterTriggerEventChunk *chunk;
5317  CommandId subxact_firing_id;
5318 
5319  /*
5320  * Pop the prior state if needed.
5321  */
5322  if (isCommit)
5323  {
5324  Assert(my_level < afterTriggers.maxtransdepth);
5325  /* If we saved a prior state, we don't need it anymore */
5326  state = afterTriggers.trans_stack[my_level].state;
5327  if (state != NULL)
5328  pfree(state);
5329  /* this avoids double pfree if error later: */
5330  afterTriggers.trans_stack[my_level].state = NULL;
5333  }
5334  else
5335  {
5336  /*
5337  * Aborting. It is possible subxact start failed before calling
5338  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
5339  * trans_stack levels that aren't there.
5340  */
5341  if (my_level >= afterTriggers.maxtransdepth)
5342  return;
5343 
5344  /*
5345  * Release query-level storage for queries being aborted, and restore
5346  * query_depth to its pre-subxact value. This assumes that a
5347  * subtransaction will not add events to query levels started in a
5348  * earlier transaction state.
5349  */
5351  {
5355  }
5358 
5359  /*
5360  * Restore the global deferred-event list to its former length,
5361  * discarding any events queued by the subxact.
5362  */
5364  &afterTriggers.trans_stack[my_level].events);
5365 
5366  /*
5367  * Restore the trigger state. If the saved state is NULL, then this
5368  * subxact didn't save it, so it doesn't need restoring.
5369  */
5370  state = afterTriggers.trans_stack[my_level].state;
5371  if (state != NULL)
5372  {
5375  }
5376  /* this avoids double pfree if error later: */
5377  afterTriggers.trans_stack[my_level].state = NULL;
5378 
5379  /*
5380  * Scan for any remaining deferred events that were marked DONE or IN
5381  * PROGRESS by this subxact or a child, and un-mark them. We can
5382  * recognize such events because they have a firing ID greater than or
5383  * equal to the firing_counter value we saved at subtransaction start.
5384  * (This essentially assumes that the current subxact includes all
5385  * subxacts started after it.)
5386  */
5387  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
5389  {
5390  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5391 
5392  if (event->ate_flags &
5394  {
5395  if (evtshared->ats_firing_id >= subxact_firing_id)
5396  event->ate_flags &=
5398  }
5399  }
5400  }
5401 }
void pfree(void *pointer)
Definition: mcxt.c:1436
TriggerFlags ate_flags
Definition: trigger.c:3638
CommandId ats_firing_id
Definition: trigger.c:3629
Definition: regguts.h:318
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3614
#define GetTriggerSharedData(evt)
Definition: trigger.c:3681
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:4130
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3613
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3718

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

5216 {
5217  /*
5218  * Forget the pending-events list.
5219  *
5220  * Since all the info is in TopTransactionContext or children thereof, we
5221  * don't really need to do anything to reclaim memory. However, the
5222  * pending-events list could be large, and so it's useful to discard it as
5223  * soon as possible --- especially if we are aborting because we ran out
5224  * of memory for the list!
5225  */
5227  {
5229  afterTriggers.event_cxt = NULL;
5230  afterTriggers.events.head = NULL;
5231  afterTriggers.events.tail = NULL;
5232  afterTriggers.events.tailfree = NULL;
5233  }
5234 
5235  /*
5236  * Forget any subtransaction state as well. Since this can't be very
5237  * large, we let the eventual reset of TopTransactionContext free the
5238  * memory instead of doing it here.
5239  */
5240  afterTriggers.trans_stack = NULL;
5242 
5243 
5244  /*
5245  * Forget the query stack and constraint-related state information. As
5246  * with the subtransaction state information, we don't bother freeing the
5247  * memory here.
5248  */
5249  afterTriggers.query_stack = NULL;
5251  afterTriggers.state = NULL;
5252 
5253  /* No more afterTriggers manipulation until next transaction starts. */
5255 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:387

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

5160 {
5161  AfterTriggerEventList *events;
5162  bool snap_pushed = false;
5163 
5164  /* Must not be inside a query */
5166 
5167  /*
5168  * If there are any triggers to fire, make sure we have set a snapshot for
5169  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
5170  * can't assume ActiveSnapshot is valid on entry.)
5171  */
5172  events = &afterTriggers.events;
5173  if (events->head != NULL)
5174  {
5176  snap_pushed = true;
5177  }
5178 
5179  /*
5180  * Run all the remaining triggers. Loop until they are all gone, in case
5181  * some trigger queues more for us to do.
5182  */
5183  while (afterTriggerMarkEvents(events, NULL, false))
5184  {
5185  CommandId firing_id = afterTriggers.firing_counter++;
5186 
5187  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
5188  break; /* all fired */
5189  }
5190 
5191  /*
5192  * We don't bother freeing the event list, since it will go away anyway
5193  * (and more efficiently than via pfree) in AfterTriggerEndXact.
5194  */
5195 
5196  if (snap_pushed)
5198 }
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:251
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:683
void PopActiveSnapshot(void)
Definition: snapmgr.c:778

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

5937 {
5938  AfterTriggerEvent event;
5939  AfterTriggerEventChunk *chunk;
5940  int depth;
5941 
5942  /* Scan queued events */
5944  {
5945  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5946 
5947  /*
5948  * We can ignore completed events. (Even if a DONE flag is rolled
5949  * back by subxact abort, it's OK because the effects of the TRUNCATE
5950  * or whatever must get rolled back too.)
5951  */
5952  if (event->ate_flags & AFTER_TRIGGER_DONE)
5953  continue;
5954 
5955  if (evtshared->ats_relid == relid)
5956  return true;
5957  }
5958 
5959  /*
5960  * Also scan events queued by incomplete queries. This could only matter
5961  * if TRUNCATE/etc is executed by a function or trigger within an updating
5962  * query on the same relation, which is pretty perverse, but let's check.
5963  */
5964  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
5965  {
5967  {
5968  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5969 
5970  if (event->ate_flags & AFTER_TRIGGER_DONE)
5971  continue;
5972 
5973  if (evtshared->ats_relid == relid)
5974  return true;
5975  }
5976  }
5977 
5978  return false;
5979 }

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

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

References AccessShareLock, afterTriggerInvokeEvents(), afterTriggerMarkEvents(), afterTriggers, SetConstraintStateData::all_isdeferred, SetConstraintStateData::all_isset, BTEqualStrategyNumber, RangeVar::catalogname, CStringGetDatum(), 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, stmt, 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 2096 of file trigger.c.

2097 {
2098  TriggerDesc *newdesc;
2099  Trigger *trigger;
2100  int i;
2101 
2102  if (trigdesc == NULL || trigdesc->numtriggers <= 0)
2103  return NULL;
2104 
2105  newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
2106  memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
2107 
2108  trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
2109  memcpy(trigger, trigdesc->triggers,
2110  trigdesc->numtriggers * sizeof(Trigger));
2111  newdesc->triggers = trigger;
2112 
2113  for (i = 0; i < trigdesc->numtriggers; i++)
2114  {
2115  trigger->tgname = pstrdup(trigger->tgname);
2116  if (trigger->tgnattr > 0)
2117  {
2118  int16 *newattr;
2119 
2120  newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
2121  memcpy(newattr, trigger->tgattr,
2122  trigger->tgnattr * sizeof(int16));
2123  trigger->tgattr = newattr;
2124  }
2125  if (trigger->tgnargs > 0)
2126  {
2127  char **newargs;
2128  int16 j;
2129 
2130  newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
2131  for (j = 0; j < trigger->tgnargs; j++)
2132  newargs[j] = pstrdup(trigger->tgargs[j]);
2133  trigger->tgargs = newargs;
2134  }
2135  if (trigger->tgqual)
2136  trigger->tgqual = pstrdup(trigger->tgqual);
2137  if (trigger->tgoldtable)
2138  trigger->tgoldtable = pstrdup(trigger->tgoldtable);
2139  if (trigger->tgnewtable)
2140  trigger->tgnewtable = pstrdup(trigger->tgnewtable);
2141  trigger++;
2142  }
2143 
2144  return newdesc;
2145 }
signed short int16
Definition: c.h:477
int j
Definition: isn.c:74
char * pstrdup(const char *in)
Definition: mcxt.c:1624
void * palloc(Size size)
Definition: mcxt.c:1210
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 165 of file trigger.c.

169 {
170  return
171  CreateTriggerFiringOn(stmt, queryString, relOid, refRelOid,
172  constraintOid, indexOid, funcoid,
173  parentTriggerOid, whenClause, isInternal,
174  in_partition, TRIGGER_FIRES_ON_ORIGIN);
175 }
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:182
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:149

References CreateTriggerFiringOn(), stmt, 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 182 of file trigger.c.

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

References AccessShareLock, ACL_EXECUTE, ACL_TRIGGER, aclcheck_error(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate, allowSystemTableMods, generate_unaccent_rules::args, Assert(), assign_expr_collations(), attnameAttNum(), attnum, BoolGetDatum(), BTEqualStrategyNumber, buildint2vector(), byteain(), CacheInvalidateRelcacheByTuple(), CatalogTupleInsert(), CatalogTupleUpdate(), ObjectAddress::classId, CommandCounterIncrement(), copyObject, CreateConstraintEntry(), CStringGetDatum(), CStringGetTextDatum, CurrentMemoryContext, DatumGetPointer(), 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, EXPR_KIND_TRIGGER_WHEN, find_all_inheritors(), 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, Int16GetDatum(), InvalidAttrNumber, InvalidOid, InvokeObjectPostCreateHookArg, TriggerTransition::isNew, IsSystemRelation(), TriggerTransition::isTable, j, len, lfirst, lfirst_node, 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_aclcheck(), OBJECT_FUNCTION, ObjectAddressSet, ObjectAddress::objectId, ObjectIdGetDatum(), ObjectAddress::objectSubId, OidIsValid, PartitionDescData::oids, ParseState::p_rtable, ParseState::p_sourcetext, palloc(), parser_errposition(), pfree(), pg_class_aclcheck(), PointerGetDatum(), PRS2_NEW_VARNO, PRS2_OLD_VARNO, pull_var_clause(), RangeVarGetRelid, RelationData::rd_att, RelationData::rd_id, RelationData::rd_rel, recordDependencyOn(), recordDependencyOnExpr(), RelationGetDescr, RelationGetNamespace, RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, RELOID, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, ShareRowExclusiveLock, snprintf, stmt, strVal, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), table_openrv(), transformWhereClause(), TupleDescAttr, values, Var::varattno, Var::varno, and CreateTrigStmt::whenClause.

Referenced by CloneRowTriggersToPartition(), and CreateTrigger().

◆ EnableDisableTrigger()

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

Definition at line 1732 of file trigger.c.

1735 {
1736  Relation tgrel;
1737  int nkeys;
1738  ScanKeyData keys[2];
1739  SysScanDesc tgscan;
1740  HeapTuple tuple;
1741  bool found;
1742  bool changed;
1743 
1744  /* Scan the relevant entries in pg_triggers */
1745  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1746 
1747  ScanKeyInit(&keys[0],
1748  Anum_pg_trigger_tgrelid,
1749  BTEqualStrategyNumber, F_OIDEQ,
1751  if (tgname)
1752  {
1753  ScanKeyInit(&keys[1],
1754  Anum_pg_trigger_tgname,
1755  BTEqualStrategyNumber, F_NAMEEQ,
1756  CStringGetDatum(tgname));
1757  nkeys = 2;
1758  }
1759  else
1760  nkeys = 1;
1761 
1762  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1763  NULL, nkeys, keys);
1764 
1765  found = changed = false;
1766 
1767  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1768  {
1769  Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1770 
1771  if (OidIsValid(tgparent) && tgparent != oldtrig->tgparentid)
1772  continue;
1773 
1774  if (oldtrig->tgisinternal)
1775  {
1776  /* system trigger ... ok to process? */
1777  if (skip_system)
1778  continue;
1779  if (!superuser())
1780  ereport(ERROR,
1781  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1782  errmsg("permission denied: \"%s\" is a system trigger",
1783  NameStr(oldtrig->tgname))));
1784  }
1785 
1786  found = true;
1787 
1788  if (oldtrig->tgenabled != fires_when)
1789  {
1790  /* need to change this one ... make a copy to scribble on */
1791  HeapTuple newtup = heap_copytuple(tuple);
1792  Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1793 
1794  newtrig->tgenabled = fires_when;
1795 
1796  CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1797 
1798  heap_freetuple(newtup);
1799 
1800  changed = true;
1801  }
1802 
1803  /*
1804  * When altering FOR EACH ROW triggers on a partitioned table, do the
1805  * same on the partitions as well, unless ONLY is specified.
1806  *
1807  * Note that we recurse even if we didn't change the trigger above,
1808  * because the partitions' copy of the trigger may have a different
1809  * value of tgenabled than the parent's trigger and thus might need to
1810  * be changed.
1811  */
1812  if (recurse &&
1813  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
1814  (TRIGGER_FOR_ROW(oldtrig->tgtype)))
1815  {
1816  PartitionDesc partdesc = RelationGetPartitionDesc(rel, true);
1817  int i;
1818 
1819  for (i = 0; i < partdesc->nparts; i++)
1820  {
1821  Relation part;
1822 
1823  part = relation_open(partdesc->oids[i], lockmode);
1824  /* Match on child triggers' tgparentid, not their name */
1825  EnableDisableTrigger(part, NULL, oldtrig->oid,
1826  fires_when, skip_system, recurse,
1827  lockmode);
1828  table_close(part, NoLock); /* keep lock till commit */
1829  }
1830  }
1831 
1832  InvokeObjectPostAlterHook(TriggerRelationId,
1833  oldtrig->oid, 0);
1834  }
1835 
1836  systable_endscan(tgscan);
1837 
1838  table_close(tgrel, RowExclusiveLock);
1839 
1840  if (tgname && !found)
1841  ereport(ERROR,
1842  (errcode(ERRCODE_UNDEFINED_OBJECT),
1843  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1844  tgname, RelationGetRelationName(rel))));
1845 
1846  /*
1847  * If we changed anything, broadcast a SI inval message to force each
1848  * backend (including our own!) to rebuild relation's relcache entry.
1849  * Otherwise they will fail to apply the change promptly.
1850  */
1851  if (changed)
1853 }
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1363
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
bool superuser(void)
Definition: superuser.c:46
void EnableDisableTrigger(Relation rel, const char *tgname, Oid tgparent, char fires_when, bool skip_system, bool recurse, LOCKMODE lockmode)
Definition: trigger.c:1732

References BTEqualStrategyNumber, CacheInvalidateRelcache(), CatalogTupleUpdate(), CStringGetDatum(), ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_copytuple(), heap_freetuple(), HeapTupleIsValid, i, InvokeObjectPostAlterHook, NameStr, NoLock, PartitionDescData::nparts, ObjectIdGetDatum(), OidIsValid, PartitionDescData::oids, RelationData::rd_rel, relation_open(), RelationGetPartitionDesc(), 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 2785 of file trigger.c.

2791 {
2792  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2793 
2794  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2795  (transition_capture && transition_capture->tcs_delete_old_table))
2796  {
2797  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2798 
2799  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2800  if (fdw_trigtuple == NULL)
2801  GetTupleForTrigger(estate,
2802  NULL,
2803  relinfo,
2804  tupleid,
2806  slot,
2807  NULL,
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:1169
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
@ LockTupleExclusive
Definition: lockoptions.h:58
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:480
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 *oldslot, TupleTableSlot *newslot, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture, bool is_crosspart_update)
Definition: trigger.c:6023
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **epqslot, TM_Result *tmresultp, TM_FailureData *tmfdp)
Definition: trigger.c:3279
#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 2545 of file trigger.c.

2548 {
2549  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2550 
2551  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2552  (transition_capture && transition_capture->tcs_insert_new_table))
2553  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2555  true, NULL, slot,
2556  recheckIndexes, NULL,
2557  transition_capture,
2558  false);
2559 }
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 newslot,
List recheckIndexes,
TransitionCaptureState transition_capture,
bool  is_crosspart_update 
)

Definition at line 3090 of file trigger.c.

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

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

2676 {
2677  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2678 
2679  if (trigdesc && trigdesc->trig_delete_after_statement)
2680  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2682  false, NULL, NULL, NIL, NULL, transition_capture,
2683  false);
2684 }
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 2456 of file trigger.c.

2458 {
2459  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2460 
2461  if (trigdesc && trigdesc->trig_insert_after_statement)
2462  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2464  false, NULL, NULL, NIL, NULL, transition_capture,
2465  false);
2466 }
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 3262 of file trigger.c.

3263 {
3264  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3265 
3266  if (trigdesc && trigdesc->trig_truncate_after_statement)
3267  AfterTriggerSaveEvent(estate, relinfo,
3268  NULL, NULL,
3270  false, NULL, NULL, NIL, NULL, NULL,
3271  false);
3272 }
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:574
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,
TM_Result tmresult,
TM_FailureData tmfd 
)

Definition at line 2694 of file trigger.c.

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

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

Definition at line 2945 of file trigger.c.

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

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, 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 2623 of file trigger.c.

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

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, 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 2405 of file trigger.c.

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

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

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

References ExecCallTriggerFunc(), ExecFetchSlotHeapTuple(), ExecForceStoreHeapTuple(), GetPerTupleMemoryContext, heap_freetuple(), i, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, 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 newslot 
)

Definition at line 3149 of file trigger.c.

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

References ExecCallTriggerFunc(), ExecFetchSlotHeapTuple(), ExecForceStoreHeapTuple(), ExecGetTriggerOldSlot(), GetPerTupleMemoryContext, heap_freetuple(), i, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, 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 2283 of file trigger.c.

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

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

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

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 *  trigname,
bool  missing_ok 
)

Definition at line 1377 of file trigger.c.

1378 {
1379  Relation tgrel;
1380  ScanKeyData skey[2];
1381  SysScanDesc tgscan;
1382  HeapTuple tup;
1383  Oid oid;
1384 
1385  /*
1386  * Find the trigger, verify permissions, set up object address
1387  */
1388  tgrel = table_open(TriggerRelationId, AccessShareLock);
1389 
1390  ScanKeyInit(&skey[0],
1391  Anum_pg_trigger_tgrelid,
1392  BTEqualStrategyNumber, F_OIDEQ,
1393  ObjectIdGetDatum(relid));
1394  ScanKeyInit(&skey[1],
1395  Anum_pg_trigger_tgname,
1396  BTEqualStrategyNumber, F_NAMEEQ,
1397  CStringGetDatum(trigname));
1398 
1399  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1400  NULL, 2, skey);
1401 
1402  tup = systable_getnext(tgscan);
1403 
1404  if (!HeapTupleIsValid(tup))
1405  {
1406  if (!missing_ok)
1407  ereport(ERROR,
1408  (errcode(ERRCODE_UNDEFINED_OBJECT),
1409  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1410  trigname, get_rel_name(relid))));
1411  oid = InvalidOid;
1412  }
1413  else
1414  {
1415  oid = ((Form_pg_trigger) GETSTRUCT(tup))->oid;
1416  }
1417 
1418  systable_endscan(tgscan);
1419  table_close(tgrel, AccessShareLock);
1420  return oid;
1421 }

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

4845 {
4847  bool need_old_upd,
4848  need_new_upd,
4849  need_old_del,
4850  need_new_ins;
4851  AfterTriggersTableData *table;
4852  MemoryContext oldcxt;
4853  ResourceOwner saveResourceOwner;
4854 
4855  if (trigdesc == NULL)
4856  return NULL;
4857 
4858  /* Detect which table(s) we need. */
4859  switch (cmdType)
4860  {
4861  case CMD_INSERT:
4862  need_old_upd = need_old_del = need_new_upd = false;
4863  need_new_ins = trigdesc->trig_insert_new_table;
4864  break;
4865  case CMD_UPDATE:
4866  need_old_upd = trigdesc->trig_update_old_table;
4867  need_new_upd = trigdesc->trig_update_new_table;
4868  need_old_del = need_new_ins = false;
4869  break;
4870  case CMD_DELETE:
4871  need_old_del = trigdesc->trig_delete_old_table;
4872  need_old_upd = need_new_upd = need_new_ins = false;
4873  break;
4874  case CMD_MERGE:
4875  need_old_upd = trigdesc->trig_update_old_table;
4876  need_new_upd = trigdesc->trig_update_new_table;
4877  need_old_del = trigdesc->trig_delete_old_table;
4878  need_new_ins = trigdesc->trig_insert_new_table;
4879  break;
4880  default:
4881  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4882  /* keep compiler quiet */
4883  need_old_upd = need_new_upd = need_old_del = need_new_ins = false;
4884  break;
4885  }
4886  if (!need_old_upd && !need_new_upd && !need_new_ins && !need_old_del)
4887  return NULL;
4888 
4889  /* Check state, like AfterTriggerSaveEvent. */
4890  if (afterTriggers.query_depth < 0)
4891  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4892 
4893  /* Be sure we have enough space to record events at this query depth. */
4896 
4897  /*
4898  * Find or create an AfterTriggersTableData struct to hold the
4899  * tuplestore(s). If there's a matching struct but it's marked closed,
4900  * ignore it; we need a newer one.
4901  *
4902  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4903  * allocated in the current (sub)transaction's CurTransactionContext, and
4904  * the tuplestores are managed by the (sub)transaction's resource owner.
4905  * This is sufficient lifespan because we do not allow triggers using
4906  * transition tables to be deferrable; they will be fired during
4907  * AfterTriggerEndQuery, after which it's okay to delete the data.
4908  */
4909  table = GetAfterTriggersTableData(relid, cmdType);
4910 
4911  /* Now create required tuplestore(s), if we don't have them already. */
4913  saveResourceOwner = CurrentResourceOwner;
4915 
4916  if (need_old_upd && table->old_upd_tuplestore == NULL)
4917  table->old_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4918  if (need_new_upd && table->new_upd_tuplestore == NULL)
4919  table->new_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4920  if (need_old_del && table->old_del_tuplestore == NULL)
4921  table->old_del_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4922  if (need_new_ins && table->new_ins_tuplestore == NULL)
4923  table->new_ins_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4924 
4925  CurrentResourceOwner = saveResourceOwner;
4926  MemoryContextSwitchTo(oldcxt);
4927 
4928  /* Now build the TransitionCaptureState struct, in caller's context */
4930  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4931  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4932  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4933  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4934  state->tcs_private = table;
4935 
4936  return state;
4937 }
int work_mem
Definition: globals.c:125
void * palloc0(Size size)
Definition: mcxt.c:1241
MemoryContext CurTransactionContext
Definition: mcxt.c:147
@ CMD_MERGE
Definition: nodes.h:280
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:147
Tuplestorestate * old_upd_tuplestore
Definition: trigger.c:3860
Tuplestorestate * new_upd_tuplestore
Definition: trigger.c:3862
Tuplestorestate * old_del_tuplestore
Definition: trigger.c:3864
Tuplestorestate * new_ins_tuplestore
Definition: trigger.c:3866
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:4758
static void AfterTriggerEnlargeQueryState(void)
Definition: trigger.c:5499
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 1867 of file trigger.c.

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

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

1299 {
1300  Relation tgrel;
1301  SysScanDesc tgscan;
1302  ScanKeyData skey[1];
1303  HeapTuple tup;
1304  Oid relid;
1305  Relation rel;
1306 
1307  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1308 
1309  /*
1310  * Find the trigger to delete.
1311  */
1312  ScanKeyInit(&skey[0],
1313  Anum_pg_trigger_oid,
1314  BTEqualStrategyNumber, F_OIDEQ,
1315  ObjectIdGetDatum(trigOid));
1316 
1317  tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
1318  NULL, 1, skey);
1319 
1320  tup = systable_getnext(tgscan);
1321  if (!HeapTupleIsValid(tup))
1322  elog(ERROR, "could not find tuple for trigger %u", trigOid);
1323 
1324  /*
1325  * Open and exclusive-lock the relation the trigger belongs to.
1326  */
1327  relid = ((Form_pg_trigger) GETSTRUCT(tup))->tgrelid;
1328 
1329  rel = table_open(relid, AccessExclusiveLock);
1330 
1331  if (rel->rd_rel->relkind != RELKIND_RELATION &&
1332  rel->rd_rel->relkind != RELKIND_VIEW &&
1333  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
1334  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1335  ereport(ERROR,
1336  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1337  errmsg("relation \"%s\" cannot have triggers",
1339  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
1340 
1342  ereport(ERROR,
1343  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1344  errmsg("permission denied: \"%s\" is a system catalog",
1345  RelationGetRelationName(rel))));
1346 
1347  /*
1348  * Delete the pg_trigger tuple.
1349  */
1350  CatalogTupleDelete(tgrel, &tup->t_self);
1351 
1352  systable_endscan(tgscan);
1353  table_close(tgrel, RowExclusiveLock);
1354 
1355  /*
1356  * We do not bother to try to determine whether any other triggers remain,
1357  * which would be needed in order to decide whether it's safe to clear the
1358  * relation's relhastriggers. (In any case, there might be a concurrent
1359  * process adding new triggers.) Instead, just force a relcache inval to
1360  * make other backends (and this one too!) rebuild their relcache entries.
1361  * There's no great harm in leaving relhastriggers true even if there are
1362  * no triggers left.
1363  */
1365 
1366  /* Keep lock on trigger's rel until end of xact */
1367  table_close(rel, NoLock);
1368 }
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
#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 1474 of file trigger.c.

1475 {
1476  Oid tgoid;
1477  Relation targetrel;
1478  Relation tgrel;
1479  HeapTuple tuple;
1480  SysScanDesc tgscan;
1481  ScanKeyData key[2];
1482  Oid relid;
1483  ObjectAddress address;
1484 
1485  /*
1486  * Look up name, check permissions, and acquire lock (which we will NOT
1487  * release until end of transaction).
1488  */
1490  0,
1492  NULL);
1493 
1494  /* Have lock already, so just need to build relcache entry. */
1495  targetrel = relation_open(relid, NoLock);
1496 
1497  /*
1498  * On partitioned tables, this operation recurses to partitions. Lock all
1499  * tables upfront.
1500  */
1501  if (targetrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1502  (void) find_all_inheritors(relid, AccessExclusiveLock, NULL);
1503 
1504  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1505 
1506  /*
1507  * Search for the trigger to modify.
1508  */
1509  ScanKeyInit(&key[0],
1510  Anum_pg_trigger_tgrelid,
1511  BTEqualStrategyNumber, F_OIDEQ,
1512  ObjectIdGetDatum(relid));
1513  ScanKeyInit(&key[1],
1514  Anum_pg_trigger_tgname,
1515  BTEqualStrategyNumber, F_NAMEEQ,
1516  PointerGetDatum(stmt->subname));
1517  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1518  NULL, 2, key);
1519  if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1520  {
1521  Form_pg_trigger trigform;
1522 
1523  trigform = (Form_pg_trigger) GETSTRUCT(tuple);
1524  tgoid = trigform->oid;
1525 
1526  /*
1527  * If the trigger descends from a trigger on a parent partitioned
1528  * table, reject the rename. We don't allow a trigger in a partition
1529  * to differ in name from that of its parent: that would lead to an
1530  * inconsistency that pg_dump would not reproduce.
1531  */
1532  if (OidIsValid(trigform->tgparentid))
1533  ereport(ERROR,
1534  errmsg("cannot rename trigger \"%s\" on table \"%s\"",
1535  stmt->subname, RelationGetRelationName(targetrel)),
1536  errhint("Rename the trigger on the partitioned table \"%s\" instead.",
1537  get_rel_name(get_partition_parent(relid, false))));
1538 
1539 
1540  /* Rename the trigger on this relation ... */
1541  renametrig_internal(tgrel, targetrel, tuple, stmt->newname,
1542  stmt->subname);
1543 
1544  /* ... and if it is partitioned, recurse to its partitions */
1545  if (targetrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1546  {
1547  PartitionDesc partdesc = RelationGetPartitionDesc(targetrel, true);
1548 
1549  for (int i = 0; i < partdesc->nparts; i++)
1550  {
1551  Oid partitionId = partdesc->oids[i];
1552 
1553  renametrig_partition(tgrel, partitionId, trigform->oid,
1554  stmt->newname, stmt->subname);
1555  }
1556  }
1557  }
1558  else
1559  {
1560  ereport(ERROR,
1561  (errcode(ERRCODE_UNDEFINED_OBJECT),
1562  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1563  stmt->subname, RelationGetRelationName(targetrel))));
1564  }
1565 
1566  ObjectAddressSet(address, TriggerRelationId, tgoid);
1567 
1568  systable_endscan(tgscan);
1569 
1570  table_close(tgrel, RowExclusiveLock);
1571 
1572  /*
1573  * Close rel, but keep exclusive lock!
1574  */
1575  relation_close(targetrel, NoLock);
1576 
1577  return address;
1578 }
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:239
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
static void renametrig_internal(Relation tgrel, Relation targetrel, HeapTuple trigtup, const char *newname, const char *expected_name)
Definition: trigger.c:1588
static void RangeVarCallbackForRenameTrigger(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition: trigger.c:1427
static void renametrig_partition(Relation tgrel, Oid partitionId, Oid parentTriggerOid, const char *newname, const char *expected_name)
Definition: trigger.c:1659

References AccessExclusiveLock, BTEqualStrategyNumber, ereport, errcode(), errhint(), errmsg(), ERROR, find_all_inheritors(), get_partition_parent(), get_rel_name(), GETSTRUCT, HeapTupleIsValid, i, sort-test::key, NoLock, PartitionDescData::nparts, ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, PartitionDescData::oids, PointerGetDatum(), RangeVarCallbackForRenameTrigger(), RangeVarGetRelidExtended(), RelationData::rd_rel, relation_close(), relation_open(), RelationGetPartitionDesc(), RelationGetRelationName, renametrig_internal(), renametrig_partition(), RowExclusiveLock, ScanKeyInit(), stmt, 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 oldslot,
TupleTableSlot newslot 
)

Definition at line 1261 of file ri_triggers.c.

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

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 oldslot,
TupleTableSlot newslot 
)

Definition at line 1229 of file ri_triggers.c.

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

3005 {
3006  switch (tgfoid)
3007  {
3008  case F_RI_FKEY_CASCADE_DEL:
3009  case F_RI_FKEY_CASCADE_UPD:
3010  case F_RI_FKEY_RESTRICT_DEL:
3011  case F_RI_FKEY_RESTRICT_UPD:
3012  case F_RI_FKEY_SETNULL_DEL:
3013  case F_RI_FKEY_SETNULL_UPD:
3014  case F_RI_FKEY_SETDEFAULT_DEL:
3015  case F_RI_FKEY_SETDEFAULT_UPD:
3016  case F_RI_FKEY_NOACTION_DEL:
3017  case F_RI_FKEY_NOACTION_UPD:
3018  return RI_TRIGGER_PK;
3019 
3020  case F_RI_FKEY_CHECK_INS:
3021  case F_RI_FKEY_CHECK_UPD:
3022  return RI_TRIGGER_FK;
3023  }
3024 
3025  return RI_TRIGGER_NONE;
3026 }
#define RI_TRIGGER_FK
Definition: trigger.h:283
#define RI_TRIGGER_NONE
Definition: trigger.h:284
#define RI_TRIGGER_PK
Definition: trigger.h:282

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent(), ExecCrossPartitionUpdateForeignKey(), GetForeignKeyActionTriggers(), and GetForeignKeyCheckTriggers().

◆ RI_Initial_Check()

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

Definition at line 1368 of file ri_triggers.c.

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