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, 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)
 
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_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 280 of file trigger.h.

◆ RI_TRIGGER_NONE

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

Definition at line 281 of file trigger.h.

◆ RI_TRIGGER_PK

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

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

4955 {
4956  /* Increase the query stack depth */
4958 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3845

References afterTriggers, and AfterTriggersData::query_depth.

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

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 5237 of file trigger.c.

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

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

4923 {
4924  /*
4925  * Initialize after-trigger state structure to empty
4926  */
4927  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4929 
4930  /*
4931  * Verify that there is no leftover state remaining. If these assertions
4932  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4933  * up properly.
4934  */
4935  Assert(afterTriggers.state == NULL);
4936  Assert(afterTriggers.query_stack == NULL);
4938  Assert(afterTriggers.event_cxt == NULL);
4939  Assert(afterTriggers.events.head == NULL);
4940  Assert(afterTriggers.trans_stack == NULL);
4942 }
uint32 CommandId
Definition: c.h:602
Assert(fmt[strlen(fmt) - 1] !='\n')
AfterTriggerEventChunk * head
Definition: trigger.c:3679
SetConstraintState state
Definition: trigger.c:3786
AfterTriggersQueryData * query_stack
Definition: trigger.c:3791
MemoryContext event_cxt
Definition: trigger.c:3788

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

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

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

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

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

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

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

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

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

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

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

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

Referenced by standard_ProcessUtility().

◆ CopyTriggerDesc()

TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 2090 of file trigger.c.

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

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

References CreateTriggerFiringOn(), and TRIGGER_FIRES_ON_ORIGIN.

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

◆ CreateTriggerFiringOn()

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

Definition at line 181 of file trigger.c.

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

References AccessShareLock, ACL_EXECUTE, ACL_TRIGGER, aclcheck_error(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate, allowSystemTableMods, generate_unaccent_rules::args, CreateTrigStmt::args, Assert(), assign_expr_collations(), attnameAttNum(), attnum, BoolGetDatum(), BTEqualStrategyNumber, buildint2vector(), byteain(), CacheInvalidateRelcacheByTuple(), CatalogTupleInsert(), CatalogTupleUpdate(), ObjectAddress::classId, CreateTrigStmt::columns, CommandCounterIncrement(), CreateTrigStmt::constrrel, copyObject, CreateConstraintEntry(), CStringGetDatum(), CStringGetTextDatum, CurrentMemoryContext, DatumGetPointer(), CreateTrigStmt::deferrable, deleteDependencyRecordsFor(), DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, DEPENDENCY_NORMAL, DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, DirectFunctionCall1, elog(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errdetail_relkind_not_supported(), errhint(), errmsg(), ERROR, CreateTrigStmt::events, EXPR_KIND_TRIGGER_WHEN, find_all_inheritors(), 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, CreateTrigStmt::initdeferred, Int16GetDatum(), InvalidAttrNumber, InvalidOid, InvokeObjectPostCreateHookArg, CreateTrigStmt::isconstraint, 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(), CreateTrigStmt::relation, RelationGetDescr, RelationGetNamespace, RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, RELOID, CreateTrigStmt::replace, CreateTrigStmt::row, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, ShareRowExclusiveLock, snprintf, strVal, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), table_open(), table_openrv(), CreateTrigStmt::timing, transformWhereClause(), CreateTrigStmt::transitionRels, CreateTrigStmt::trigname, TupleDescAttr, values, Var::varattno, Var::varno, and CreateTrigStmt::whenClause.

Referenced by CloneRowTriggersToPartition(), and CreateTrigger().

◆ EnableDisableTrigger()

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

Definition at line 1730 of file trigger.c.

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

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

2783 {
2784  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2785 
2786  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2787  (transition_capture && transition_capture->tcs_delete_old_table))
2788  {
2789  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2790 
2791  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2792  if (fdw_trigtuple == NULL)
2793  GetTupleForTrigger(estate,
2794  NULL,
2795  relinfo,
2796  tupleid,
2798  slot,
2799  NULL,
2800  NULL);
2801  else
2802  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2803 
2804  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2806  true, slot, NULL, NIL, NULL,
2807  transition_capture,
2808  is_crosspart_update);
2809  }
2810 }
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1168
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
@ LockTupleExclusive
Definition: lockoptions.h:58
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:475
bool trig_delete_after_row
Definition: reltrigger.h:67
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **epqslot, TM_FailureData *tmfdp)
Definition: trigger.c:3268
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:5997
#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 2539 of file trigger.c.

2542 {
2543  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2544 
2545  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2546  (transition_capture && transition_capture->tcs_insert_new_table))
2547  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2549  true, NULL, slot,
2550  recheckIndexes, NULL,
2551  transition_capture,
2552  false);
2553 }
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 3080 of file trigger.c.

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

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

2670 {
2671  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2672 
2673  if (trigdesc && trigdesc->trig_delete_after_statement)
2674  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2676  false, NULL, NULL, NIL, NULL, transition_capture,
2677  false);
2678 }
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 2450 of file trigger.c.

2452 {
2453  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2454 
2455  if (trigdesc && trigdesc->trig_insert_after_statement)
2456  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2458  false, NULL, NULL, NIL, NULL, transition_capture,
2459  false);
2460 }
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 3251 of file trigger.c.

3252 {
3253  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3254 
3255  if (trigdesc && trigdesc->trig_truncate_after_statement)
3256  AfterTriggerSaveEvent(estate, relinfo,
3257  NULL, NULL,
3259  false, NULL, NULL, NIL, NULL, NULL,
3260  false);
3261 }
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 2918 of file trigger.c.

2920 {
2921  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2922 
2923  /* statement-level triggers operate on the parent table */
2924  Assert(relinfo->ri_RootResultRelInfo == NULL);
2925 
2926  if (trigdesc && trigdesc->trig_update_after_statement)
2927  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2929  false, NULL, NULL, NIL,
2930  ExecGetAllUpdatedCols(relinfo, estate),
2931  transition_capture,
2932  false);
2933 }
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:567
bool trig_update_after_statement
Definition: reltrigger.h:65

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

Referenced by fireASTriggers().

◆ ExecBRDeleteTriggers()

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

Definition at line 2688 of file trigger.c.

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

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

Definition at line 2936 of file trigger.c.

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

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

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

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

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

3205 {
3206  TriggerDesc *trigdesc;
3207  int i;
3208  TriggerData LocTriggerData = {0};
3209 
3210  trigdesc = relinfo->ri_TrigDesc;
3211 
3212  if (trigdesc == NULL)
3213  return;
3214  if (!trigdesc->trig_truncate_before_statement)
3215  return;
3216 
3217  LocTriggerData.type = T_TriggerData;
3218  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
3220  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3221 
3222  for (i = 0; i < trigdesc->numtriggers; i++)
3223  {
3224  Trigger *trigger = &trigdesc->triggers[i];
3225  HeapTuple newtuple;
3226 
3227  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3228  TRIGGER_TYPE_STATEMENT,
3229  TRIGGER_TYPE_BEFORE,
3230  TRIGGER_TYPE_TRUNCATE))
3231  continue;
3232  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3233  NULL, NULL, NULL))
3234  continue;
3235 
3236  LocTriggerData.tg_trigger = trigger;
3237  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3238  i,
3239  relinfo->ri_TrigFunctions,
3240  relinfo->ri_TrigInstrument,
3241  GetPerTupleMemoryContext(estate));
3242 
3243  if (newtuple)
3244  ereport(ERROR,
3245  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
3246  errmsg("BEFORE STATEMENT trigger cannot return a value")));
3247  }
3248 }
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 2860 of file trigger.c.

2861 {
2862  TriggerDesc *trigdesc;
2863  int i;
2864  TriggerData LocTriggerData = {0};
2865  Bitmapset *updatedCols;
2866 
2867  trigdesc = relinfo->ri_TrigDesc;
2868 
2869  if (trigdesc == NULL)
2870  return;
2871  if (!trigdesc->trig_update_before_statement)
2872  return;
2873 
2874  /* no-op if we already fired BS triggers in this context */
2876  CMD_UPDATE))
2877  return;
2878 
2879  /* statement-level triggers operate on the parent table */
2880  Assert(relinfo->ri_RootResultRelInfo == NULL);
2881 
2882  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2883 
2884  LocTriggerData.type = T_TriggerData;
2885  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2887  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2888  LocTriggerData.tg_updatedcols = updatedCols;
2889  for (i = 0; i < trigdesc->numtriggers; i++)
2890  {
2891  Trigger *trigger = &trigdesc->triggers[i];
2892  HeapTuple newtuple;
2893 
2894  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2895  TRIGGER_TYPE_STATEMENT,
2896  TRIGGER_TYPE_BEFORE,
2897  TRIGGER_TYPE_UPDATE))
2898  continue;
2899  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2900  updatedCols, NULL, NULL))
2901  continue;
2902 
2903  LocTriggerData.tg_trigger = trigger;
2904  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2905  i,
2906  relinfo->ri_TrigFunctions,
2907  relinfo->ri_TrigInstrument,
2908  GetPerTupleMemoryContext(estate));
2909 
2910  if (newtuple)
2911  ereport(ERROR,
2912  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2913  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2914  }
2915 }
@ CMD_UPDATE
Definition: nodes.h:266
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 2813 of file trigger.c.

2815 {
2816  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2817  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2818  TriggerData LocTriggerData = {0};
2819  int i;
2820 
2821  LocTriggerData.type = T_TriggerData;
2822  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2825  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2826 
2827  ExecForceStoreHeapTuple(trigtuple, slot, false);
2828 
2829  for (i = 0; i < trigdesc->numtriggers; i++)
2830  {
2831  HeapTuple rettuple;
2832  Trigger *trigger = &trigdesc->triggers[i];
2833 
2834  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2835  TRIGGER_TYPE_ROW,
2836  TRIGGER_TYPE_INSTEAD,
2837  TRIGGER_TYPE_DELETE))
2838  continue;
2839  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2840  NULL, slot, NULL))
2841  continue;
2842 
2843  LocTriggerData.tg_trigslot = slot;
2844  LocTriggerData.tg_trigtuple = trigtuple;
2845  LocTriggerData.tg_trigger = trigger;
2846  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2847  i,
2848  relinfo->ri_TrigFunctions,
2849  relinfo->ri_TrigInstrument,
2850  GetPerTupleMemoryContext(estate));
2851  if (rettuple == NULL)
2852  return false; /* Delete was suppressed */
2853  if (rettuple != trigtuple)
2854  heap_freetuple(rettuple);
2855  }
2856  return true;
2857 }
#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 2556 of file trigger.c.

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

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

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

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

2278 {
2279  if (trigdesc != NULL)
2280  {
2281  int i;
2282 
2283  for (i = 0; i < trigdesc->numtriggers; ++i)
2284  {
2285  Trigger *trigger = &trigdesc->triggers[i];
2286 
2287  if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
2288  return trigger->tgname;
2289  }
2290  }
2291 
2292  return NULL;
2293 }

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

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

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

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

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

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

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

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

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

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

Referenced by doDeletion().

◆ renametrig()

ObjectAddress renametrig ( RenameStmt stmt)

Definition at line 1473 of file trigger.c.

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

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

Referenced by ExecRenameStmt().

◆ RI_FKey_fk_upd_check_required()

bool RI_FKey_fk_upd_check_required ( Trigger trigger,
Relation  fk_rel,
TupleTableSlot 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:588
#define FKCONSTR_MATCH_SIMPLE
Definition: parsenodes.h:2334
#define FKCONSTR_MATCH_PARTIAL
Definition: parsenodes.h:2333
#define FKCONSTR_MATCH_FULL
Definition: parsenodes.h:2332
static TransactionId DatumGetTransactionId(Datum X)
Definition: postgres.h:610
#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:2630
static bool ri_KeysEqual(Relation rel, TupleTableSlot *oldslot, TupleTableSlot *newslot, const RI_ConstraintInfo *riinfo, bool rel_is_pk)
Definition: ri_triggers.c:2789
#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:2052
#define MinTransactionIdAttributeNumber
Definition: sysattr.h:22
static Datum slot_getsysattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:410
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:925

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 2995 of file ri_triggers.c.

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

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