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

Go to the source code of this file.

Data Structures

struct  TriggerData
 
struct  TransitionCaptureState
 

Macros

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

Typedefs

typedef uint32 TriggerEvent
 
typedef struct TriggerData TriggerData
 
typedef struct TransitionCaptureState TransitionCaptureState
 

Functions

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

Variables

PGDLLIMPORT int SessionReplicationRole
 

Macro Definition Documentation

◆ AFTER_TRIGGER_DEFERRABLE

#define AFTER_TRIGGER_DEFERRABLE   0x00000020

Definition at line 106 of file trigger.h.

◆ AFTER_TRIGGER_INITDEFERRED

#define AFTER_TRIGGER_INITDEFERRED   0x00000040

Definition at line 107 of file trigger.h.

◆ CALLED_AS_TRIGGER

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

Definition at line 25 of file trigger.h.

◆ RI_TRIGGER_FK

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

Definition at line 273 of file trigger.h.

◆ RI_TRIGGER_NONE

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

Definition at line 274 of file trigger.h.

◆ RI_TRIGGER_PK

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

Definition at line 272 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_LOCAL

#define SESSION_REPLICATION_ROLE_LOCAL   2

Definition at line 141 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_ORIGIN

#define SESSION_REPLICATION_ROLE_ORIGIN   0

Definition at line 139 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_REPLICA

#define SESSION_REPLICATION_ROLE_REPLICA   1

Definition at line 140 of file trigger.h.

◆ TRIGGER_DISABLED

#define TRIGGER_DISABLED   'D'

Definition at line 151 of file trigger.h.

◆ TRIGGER_EVENT_AFTER

#define TRIGGER_EVENT_AFTER   0x00000000

Definition at line 100 of file trigger.h.

◆ TRIGGER_EVENT_BEFORE

#define TRIGGER_EVENT_BEFORE   0x00000008

Definition at line 99 of file trigger.h.

◆ TRIGGER_EVENT_DELETE

#define TRIGGER_EVENT_DELETE   0x00000001

Definition at line 92 of file trigger.h.

◆ TRIGGER_EVENT_INSERT

#define TRIGGER_EVENT_INSERT   0x00000000

Definition at line 91 of file trigger.h.

◆ TRIGGER_EVENT_INSTEAD

#define TRIGGER_EVENT_INSTEAD   0x00000010

Definition at line 101 of file trigger.h.

◆ TRIGGER_EVENT_OPMASK

#define TRIGGER_EVENT_OPMASK   0x00000003

Definition at line 95 of file trigger.h.

◆ TRIGGER_EVENT_ROW

#define TRIGGER_EVENT_ROW   0x00000004

Definition at line 97 of file trigger.h.

◆ TRIGGER_EVENT_TIMINGMASK

#define TRIGGER_EVENT_TIMINGMASK   0x00000018

Definition at line 102 of file trigger.h.

◆ TRIGGER_EVENT_TRUNCATE

#define TRIGGER_EVENT_TRUNCATE   0x00000003

Definition at line 94 of file trigger.h.

◆ TRIGGER_EVENT_UPDATE

#define TRIGGER_EVENT_UPDATE   0x00000002

Definition at line 93 of file trigger.h.

◆ TRIGGER_FIRED_AFTER

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

Definition at line 130 of file trigger.h.

◆ TRIGGER_FIRED_BEFORE

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

Definition at line 127 of file trigger.h.

◆ TRIGGER_FIRED_BY_DELETE

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

Definition at line 112 of file trigger.h.

◆ TRIGGER_FIRED_BY_INSERT

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

Definition at line 109 of file trigger.h.

◆ TRIGGER_FIRED_BY_TRUNCATE

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

Definition at line 118 of file trigger.h.

◆ TRIGGER_FIRED_BY_UPDATE

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

Definition at line 115 of file trigger.h.

◆ TRIGGER_FIRED_FOR_ROW

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

Definition at line 121 of file trigger.h.

◆ TRIGGER_FIRED_FOR_STATEMENT

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

Definition at line 124 of file trigger.h.

◆ TRIGGER_FIRED_INSTEAD

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

Definition at line 133 of file trigger.h.

◆ TRIGGER_FIRES_ALWAYS

#define TRIGGER_FIRES_ALWAYS   'A'

Definition at line 149 of file trigger.h.

◆ TRIGGER_FIRES_ON_ORIGIN

#define TRIGGER_FIRES_ON_ORIGIN   'O'

Definition at line 148 of file trigger.h.

◆ TRIGGER_FIRES_ON_REPLICA

#define TRIGGER_FIRES_ON_REPLICA   'R'

Definition at line 150 of file trigger.h.

Typedef Documentation

◆ TransitionCaptureState

◆ TriggerData

typedef struct TriggerData TriggerData

◆ TriggerEvent

Definition at line 28 of file trigger.h.

Function Documentation

◆ AfterTriggerBeginQuery()

void AfterTriggerBeginQuery ( void  )

Definition at line 4751 of file trigger.c.

4752 {
4753  /* Increase the query stack depth */
4755 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3760

References afterTriggers, and AfterTriggersData::query_depth.

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

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 5021 of file trigger.c.

5022 {
5023  int my_level = GetCurrentTransactionNestLevel();
5024 
5025  /*
5026  * Allocate more space in the trans_stack if needed. (Note: because the
5027  * minimum nest level of a subtransaction is 2, we waste the first couple
5028  * entries of the array; not worth the notational effort to avoid it.)
5029  */
5030  while (my_level >= afterTriggers.maxtransdepth)
5031  {
5032  if (afterTriggers.maxtransdepth == 0)
5033  {
5034  /* Arbitrarily initialize for max of 8 subtransaction levels */
5037  8 * sizeof(AfterTriggersTransData));
5039  }
5040  else
5041  {
5042  /* repalloc will keep the stack in the same context */
5043  int new_alloc = afterTriggers.maxtransdepth * 2;
5044 
5047  new_alloc * sizeof(AfterTriggersTransData));
5048  afterTriggers.maxtransdepth = new_alloc;
5049  }
5050  }
5051 
5052  /*
5053  * Push the current information into the stack. The SET CONSTRAINTS state
5054  * is not saved until/unless changed. Likewise, we don't make a
5055  * per-subtransaction event context until needed.
5056  */
5057  afterTriggers.trans_stack[my_level].state = NULL;
5061 }
MemoryContext TopTransactionContext
Definition: mcxt.c:53
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
CommandId firing_counter
Definition: trigger.c:3715
AfterTriggersTransData * trans_stack
Definition: trigger.c:3726
AfterTriggerEventList events
Definition: trigger.c:3717
AfterTriggerEventList events
Definition: trigger.c:3741
SetConstraintState state
Definition: trigger.c:3740
CommandId firing_counter
Definition: trigger.c:3743
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:909

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

4720 {
4721  /*
4722  * Initialize after-trigger state structure to empty
4723  */
4724  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4726 
4727  /*
4728  * Verify that there is no leftover state remaining. If these assertions
4729  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4730  * up properly.
4731  */
4732  Assert(afterTriggers.state == NULL);
4733  Assert(afterTriggers.query_stack == NULL);
4735  Assert(afterTriggers.event_cxt == NULL);
4736  Assert(afterTriggers.events.head == NULL);
4737  Assert(afterTriggers.trans_stack == NULL);
4739 }
uint32 CommandId
Definition: c.h:601
Assert(fmt[strlen(fmt) - 1] !='\n')
AfterTriggerEventChunk * head
Definition: trigger.c:3609
SetConstraintState state
Definition: trigger.c:3716
AfterTriggersQueryData * query_stack
Definition: trigger.c:3721
MemoryContext event_cxt
Definition: trigger.c:3718

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

4772 {
4774 
4775  /* Must be inside a query, too */
4777 
4778  /*
4779  * If we never even got as far as initializing the event stack, there
4780  * certainly won't be any events, so exit quickly.
4781  */
4783  {
4785  return;
4786  }
4787 
4788  /*
4789  * Process all immediate-mode triggers queued by the query, and move the
4790  * deferred ones to the main list of deferred events.
4791  *
4792  * Notice that we decide which ones will be fired, and put the deferred
4793  * ones on the main list, before anything is actually fired. This ensures
4794  * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
4795  * IMMEDIATE: all events we have decided to defer will be available for it
4796  * to fire.
4797  *
4798  * We loop in case a trigger queues more events at the same query level.
4799  * Ordinary trigger functions, including all PL/pgSQL trigger functions,
4800  * will instead fire any triggers in a dedicated query level. Foreign key
4801  * enforcement triggers do add to the current query level, thanks to their
4802  * passing fire_triggers = false to SPI_execute_snapshot(). Other
4803  * C-language triggers might do likewise.
4804  *
4805  * If we find no firable events, we don't have to increment
4806  * firing_counter.
4807  */
4809 
4810  for (;;)
4811  {
4813  {
4814  CommandId firing_id = afterTriggers.firing_counter++;
4815  AfterTriggerEventChunk *oldtail = qs->events.tail;
4816 
4817  if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
4818  break; /* all fired */
4819 
4820  /*
4821  * Firing a trigger could result in query_stack being repalloc'd,
4822  * so we must recalculate qs after each afterTriggerInvokeEvents
4823  * call. Furthermore, it's unsafe to pass delete_ok = true here,
4824  * because that could cause afterTriggerInvokeEvents to try to
4825  * access qs->events after the stack has been repalloc'd.
4826  */
4828 
4829  /*
4830  * We'll need to scan the events list again. To reduce the cost
4831  * of doing so, get rid of completely-fired chunks. We know that
4832  * all events were marked IN_PROGRESS or DONE at the conclusion of
4833  * afterTriggerMarkEvents, so any still-interesting events must
4834  * have been added after that, and so must be in the chunk that
4835  * was then the tail chunk, or in later chunks. So, zap all
4836  * chunks before oldtail. This is approximately the same set of
4837  * events we would have gotten rid of by passing delete_ok = true.
4838  */
4839  Assert(oldtail != NULL);
4840  while (qs->events.head != oldtail)
4842  }
4843  else
4844  break;
4845  }
4846 
4847  /* Release query-level-local storage, including tuplestores if any */
4849 
4851 }
AfterTriggerEventChunk * tail
Definition: trigger.c:3610
AfterTriggerEventList events
Definition: trigger.c:3732
static void afterTriggerDeleteHeadEventChunk(AfterTriggersQueryData *qs)
Definition: trigger.c:4047
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:4862
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4315
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4399

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

5070 {
5071  int my_level = GetCurrentTransactionNestLevel();
5073  AfterTriggerEvent event;
5074  AfterTriggerEventChunk *chunk;
5075  CommandId subxact_firing_id;
5076 
5077  /*
5078  * Pop the prior state if needed.
5079  */
5080  if (isCommit)
5081  {
5082  Assert(my_level < afterTriggers.maxtransdepth);
5083  /* If we saved a prior state, we don't need it anymore */
5084  state = afterTriggers.trans_stack[my_level].state;
5085  if (state != NULL)
5086  pfree(state);
5087  /* this avoids double pfree if error later: */
5088  afterTriggers.trans_stack[my_level].state = NULL;
5091  }
5092  else
5093  {
5094  /*
5095  * Aborting. It is possible subxact start failed before calling
5096  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
5097  * trans_stack levels that aren't there.
5098  */
5099  if (my_level >= afterTriggers.maxtransdepth)
5100  return;
5101 
5102  /*
5103  * Release query-level storage for queries being aborted, and restore
5104  * query_depth to its pre-subxact value. This assumes that a
5105  * subtransaction will not add events to query levels started in a
5106  * earlier transaction state.
5107  */
5109  {
5113  }
5116 
5117  /*
5118  * Restore the global deferred-event list to its former length,
5119  * discarding any events queued by the subxact.
5120  */
5122  &afterTriggers.trans_stack[my_level].events);
5123 
5124  /*
5125  * Restore the trigger state. If the saved state is NULL, then this
5126  * subxact didn't save it, so it doesn't need restoring.
5127  */
5128  state = afterTriggers.trans_stack[my_level].state;
5129  if (state != NULL)
5130  {
5133  }
5134  /* this avoids double pfree if error later: */
5135  afterTriggers.trans_stack[my_level].state = NULL;
5136 
5137  /*
5138  * Scan for any remaining deferred events that were marked DONE or IN
5139  * PROGRESS by this subxact or a child, and un-mark them. We can
5140  * recognize such events because they have a firing ID greater than or
5141  * equal to the firing_counter value we saved at subtransaction start.
5142  * (This essentially assumes that the current subxact includes all
5143  * subxacts started after it.)
5144  */
5145  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
5147  {
5148  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5149 
5150  if (event->ate_flags &
5152  {
5153  if (evtshared->ats_firing_id >= subxact_firing_id)
5154  event->ate_flags &=
5156  }
5157  }
5158  }
5159 }
void pfree(void *pointer)
Definition: mcxt.c:1169
TriggerFlags ate_flags
Definition: trigger.c:3560
CommandId ats_firing_id
Definition: trigger.c:3551
Definition: regguts.h:318
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3536
#define GetTriggerSharedData(evt)
Definition: trigger.c:3585
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:4007
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3535
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3622

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

4974 {
4975  /*
4976  * Forget the pending-events list.
4977  *
4978  * Since all the info is in TopTransactionContext or children thereof, we
4979  * don't really need to do anything to reclaim memory. However, the
4980  * pending-events list could be large, and so it's useful to discard it as
4981  * soon as possible --- especially if we are aborting because we ran out
4982  * of memory for the list!
4983  */
4985  {
4987  afterTriggers.event_cxt = NULL;
4988  afterTriggers.events.head = NULL;
4989  afterTriggers.events.tail = NULL;
4990  afterTriggers.events.tailfree = NULL;
4991  }
4992 
4993  /*
4994  * Forget any subtransaction state as well. Since this can't be very
4995  * large, we let the eventual reset of TopTransactionContext free the
4996  * memory instead of doing it here.
4997  */
4998  afterTriggers.trans_stack = NULL;
5000 
5001 
5002  /*
5003  * Forget the query stack and constraint-related state information. As
5004  * with the subtransaction state information, we don't bother freeing the
5005  * memory here.
5006  */
5007  afterTriggers.query_stack = NULL;
5009  afterTriggers.state = NULL;
5010 
5011  /* No more afterTriggers manipulation until next transaction starts. */
5013 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218

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

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

◆ AfterTriggerFireDeferred()

void AfterTriggerFireDeferred ( void  )

Definition at line 4917 of file trigger.c.

4918 {
4919  AfterTriggerEventList *events;
4920  bool snap_pushed = false;
4921 
4922  /* Must not be inside a query */
4924 
4925  /*
4926  * If there are any triggers to fire, make sure we have set a snapshot for
4927  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
4928  * can't assume ActiveSnapshot is valid on entry.)
4929  */
4930  events = &afterTriggers.events;
4931  if (events->head != NULL)
4932  {
4934  snap_pushed = true;
4935  }
4936 
4937  /*
4938  * Run all the remaining triggers. Loop until they are all gone, in case
4939  * some trigger queues more for us to do.
4940  */
4941  while (afterTriggerMarkEvents(events, NULL, false))
4942  {
4943  CommandId firing_id = afterTriggers.firing_counter++;
4944 
4945  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
4946  break; /* all fired */
4947  }
4948 
4949  /*
4950  * We don't bother freeing the event list, since it will go away anyway
4951  * (and more efficiently than via pfree) in AfterTriggerEndXact.
4952  */
4953 
4954  if (snap_pushed)
4956 }
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void PopActiveSnapshot(void)
Definition: snapmgr.c:774
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680

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

5609 {
5610  AfterTriggerEvent event;
5611  AfterTriggerEventChunk *chunk;
5612  int depth;
5613 
5614  /* Scan queued events */
5616  {
5617  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5618 
5619  /*
5620  * We can ignore completed events. (Even if a DONE flag is rolled
5621  * back by subxact abort, it's OK because the effects of the TRUNCATE
5622  * or whatever must get rolled back too.)
5623  */
5624  if (event->ate_flags & AFTER_TRIGGER_DONE)
5625  continue;
5626 
5627  if (evtshared->ats_relid == relid)
5628  return true;
5629  }
5630 
5631  /*
5632  * Also scan events queued by incomplete queries. This could only matter
5633  * if TRUNCATE/etc is executed by a function or trigger within an updating
5634  * query on the same relation, which is pretty perverse, but let's check.
5635  */
5636  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
5637  {
5639  {
5640  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5641 
5642  if (event->ate_flags & AFTER_TRIGGER_DONE)
5643  continue;
5644 
5645  if (evtshared->ats_relid == relid)
5646  return true;
5647  }
5648  }
5649 
5650  return false;
5651 }

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

5294 {
5295  int my_level = GetCurrentTransactionNestLevel();
5296 
5297  /* If we haven't already done so, initialize our state. */
5298  if (afterTriggers.state == NULL)
5300 
5301  /*
5302  * If in a subtransaction, and we didn't save the current state already,
5303  * save it so it can be restored if the subtransaction aborts.
5304  */
5305  if (my_level > 1 &&
5306  afterTriggers.trans_stack[my_level].state == NULL)
5307  {
5308  afterTriggers.trans_stack[my_level].state =
5310  }
5311 
5312  /*
5313  * Handle SET CONSTRAINTS ALL ...
5314  */
5315  if (stmt->constraints == NIL)
5316  {
5317  /*
5318  * Forget any previous SET CONSTRAINTS commands in this transaction.
5319  */
5321 
5322  /*
5323  * Set the per-transaction ALL state to known.
5324  */
5325  afterTriggers.state->all_isset = true;
5327  }
5328  else
5329  {
5330  Relation conrel;
5331  Relation tgrel;
5332  List *conoidlist = NIL;
5333  List *tgoidlist = NIL;
5334  ListCell *lc;
5335 
5336  /*
5337  * Handle SET CONSTRAINTS constraint-name [, ...]
5338  *
5339  * First, identify all the named constraints and make a list of their
5340  * OIDs. Since, unlike the SQL spec, we allow multiple constraints of
5341  * the same name within a schema, the specifications are not
5342  * necessarily unique. Our strategy is to target all matching
5343  * constraints within the first search-path schema that has any
5344  * matches, but disregard matches in schemas beyond the first match.
5345  * (This is a bit odd but it's the historical behavior.)
5346  *
5347  * A constraint in a partitioned table may have corresponding
5348  * constraints in the partitions. Grab those too.
5349  */
5350  conrel = table_open(ConstraintRelationId, AccessShareLock);
5351 
5352  foreach(lc, stmt->constraints)
5353  {
5354  RangeVar *constraint = lfirst(lc);
5355  bool found;
5356  List *namespacelist;
5357  ListCell *nslc;
5358 
5359  if (constraint->catalogname)
5360  {
5361  if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
5362  ereport(ERROR,
5363  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5364  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
5365  constraint->catalogname, constraint->schemaname,
5366  constraint->relname)));
5367  }
5368 
5369  /*
5370  * If we're given the schema name with the constraint, look only
5371  * in that schema. If given a bare constraint name, use the
5372  * search path to find the first matching constraint.
5373  */
5374  if (constraint->schemaname)
5375  {
5376  Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
5377  false);
5378 
5379  namespacelist = list_make1_oid(namespaceId);
5380  }
5381  else
5382  {
5383  namespacelist = fetch_search_path(true);
5384  }
5385 
5386  found = false;
5387  foreach(nslc, namespacelist)
5388  {
5389  Oid namespaceId = lfirst_oid(nslc);
5390  SysScanDesc conscan;
5391  ScanKeyData skey[2];
5392  HeapTuple tup;
5393 
5394  ScanKeyInit(&skey[0],
5395  Anum_pg_constraint_conname,
5396  BTEqualStrategyNumber, F_NAMEEQ,
5397  CStringGetDatum(constraint->relname));
5398  ScanKeyInit(&skey[1],
5399  Anum_pg_constraint_connamespace,
5400  BTEqualStrategyNumber, F_OIDEQ,
5401  ObjectIdGetDatum(namespaceId));
5402 
5403  conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
5404  true, NULL, 2, skey);
5405 
5406  while (HeapTupleIsValid(tup = systable_getnext(conscan)))
5407  {
5409 
5410  if (con->condeferrable)
5411  conoidlist = lappend_oid(conoidlist, con->oid);
5412  else if (stmt->deferred)
5413  ereport(ERROR,
5414  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5415  errmsg("constraint \"%s\" is not deferrable",
5416  constraint->relname)));
5417  found = true;
5418  }
5419 
5420  systable_endscan(conscan);
5421 
5422  /*
5423  * Once we've found a matching constraint we do not search
5424  * later parts of the search path.
5425  */
5426  if (found)
5427  break;
5428  }
5429 
5430  list_free(namespacelist);
5431 
5432  /*
5433  * Not found ?
5434  */
5435  if (!found)
5436  ereport(ERROR,
5437  (errcode(ERRCODE_UNDEFINED_OBJECT),
5438  errmsg("constraint \"%s\" does not exist",
5439  constraint->relname)));
5440  }
5441 
5442  /*
5443  * Scan for any possible descendants of the constraints. We append
5444  * whatever we find to the same list that we're scanning; this has the
5445  * effect that we create new scans for those, too, so if there are
5446  * further descendents, we'll also catch them.
5447  */
5448  foreach(lc, conoidlist)
5449  {
5450  Oid parent = lfirst_oid(lc);
5451  ScanKeyData key;
5452  SysScanDesc scan;
5453  HeapTuple tuple;
5454 
5455  ScanKeyInit(&key,
5456  Anum_pg_constraint_conparentid,
5457  BTEqualStrategyNumber, F_OIDEQ,
5458  ObjectIdGetDatum(parent));
5459 
5460  scan = systable_beginscan(conrel, ConstraintParentIndexId, true, NULL, 1, &key);
5461 
5462  while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5463  {
5465 
5466  conoidlist = lappend_oid(conoidlist, con->oid);
5467  }
5468 
5469  systable_endscan(scan);
5470  }
5471 
5472  table_close(conrel, AccessShareLock);
5473 
5474  /*
5475  * Now, locate the trigger(s) implementing each of these constraints,
5476  * and make a list of their OIDs.
5477  */
5478  tgrel = table_open(TriggerRelationId, AccessShareLock);
5479 
5480  foreach(lc, conoidlist)
5481  {
5482  Oid conoid = lfirst_oid(lc);
5483  ScanKeyData skey;
5484  SysScanDesc tgscan;
5485  HeapTuple htup;
5486 
5487  ScanKeyInit(&skey,
5488  Anum_pg_trigger_tgconstraint,
5489  BTEqualStrategyNumber, F_OIDEQ,
5490  ObjectIdGetDatum(conoid));
5491 
5492  tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
5493  NULL, 1, &skey);
5494 
5495  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
5496  {
5497  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
5498 
5499  /*
5500  * Silently skip triggers that are marked as non-deferrable in
5501  * pg_trigger. This is not an error condition, since a
5502  * deferrable RI constraint may have some non-deferrable
5503  * actions.
5504  */
5505  if (pg_trigger->tgdeferrable)
5506  tgoidlist = lappend_oid(tgoidlist, pg_trigger->oid);
5507  }
5508 
5509  systable_endscan(tgscan);
5510  }
5511 
5512  table_close(tgrel, AccessShareLock);
5513 
5514  /*
5515  * Now we can set the trigger states of individual triggers for this
5516  * xact.
5517  */
5518  foreach(lc, tgoidlist)
5519  {
5520  Oid tgoid = lfirst_oid(lc);
5522  bool found = false;
5523  int i;
5524 
5525  for (i = 0; i < state->numstates; i++)
5526  {
5527  if (state->trigstates[i].sct_tgoid == tgoid)
5528  {
5529  state->trigstates[i].sct_tgisdeferred = stmt->deferred;
5530  found = true;
5531  break;
5532  }
5533  }
5534  if (!found)
5535  {
5537  SetConstraintStateAddItem(state, tgoid, stmt->deferred);
5538  }
5539  }
5540  }
5541 
5542  /*
5543  * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
5544  * checks against that constraint must be made when the SET CONSTRAINTS
5545  * command is executed -- i.e. the effects of the SET CONSTRAINTS command
5546  * apply retroactively. We've updated the constraints state, so scan the
5547  * list of previously deferred events to fire any that have now become
5548  * immediate.
5549  *
5550  * Obviously, if this was SET ... DEFERRED then it can't have converted
5551  * any unfired events to immediate, so we need do nothing in that case.
5552  */
5553  if (!stmt->deferred)
5554  {
5556  bool snapshot_set = false;
5557 
5558  while (afterTriggerMarkEvents(events, NULL, true))
5559  {
5560  CommandId firing_id = afterTriggers.firing_counter++;
5561 
5562  /*
5563  * Make sure a snapshot has been established in case trigger
5564  * functions need one. Note that we avoid setting a snapshot if
5565  * we don't find at least one trigger that has to be fired now.
5566  * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
5567  * ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
5568  * at the start of a transaction it's not possible for any trigger
5569  * events to be queued yet.)
5570  */
5571  if (!snapshot_set)
5572  {
5574  snapshot_set = true;
5575  }
5576 
5577  /*
5578  * We can delete fired events if we are at top transaction level,
5579  * but we'd better not if inside a subtransaction, since the
5580  * subtransaction could later get rolled back.
5581  */
5582  if (afterTriggerInvokeEvents(events, firing_id, NULL,
5583  !IsSubTransaction()))
5584  break; /* all fired */
5585  }
5586 
5587  if (snapshot_set)
5589  }
5590 }
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2113
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:598
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:505
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:386
Oid MyDatabaseId
Definition: globals.c:88
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
int i
Definition: isn.c:73
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
void list_free(List *list)
Definition: list.c:1505
#define AccessShareLock
Definition: lockdefs.h:36
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2938
List * fetch_search_path(bool includeImplicit)
Definition: namespace.c:4428
FormData_pg_constraint * Form_pg_constraint
#define lfirst(lc)
Definition: pg_list.h:169
#define NIL
Definition: pg_list.h:65
#define list_make1_oid(x1)
Definition: pg_list.h:236
#define lfirst_oid(lc)
Definition: pg_list.h:171
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:80
#define CStringGetDatum(X)
Definition: postgres.h:622
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
unsigned int Oid
Definition: postgres_ext.h:31
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Definition: pg_list.h:51
char * relname
Definition: primnodes.h:68
char * catalogname
Definition: primnodes.h:66
char * schemaname
Definition: primnodes.h:67
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static SetConstraintState SetConstraintStateAddItem(SetConstraintState state, Oid tgoid, bool tgisdeferred)
Definition: trigger.c:5263
static SetConstraintState SetConstraintStateCopy(SetConstraintState state)
Definition: trigger.c:5243
static SetConstraintState SetConstraintStateCreate(int numalloc)
Definition: trigger.c:5218
bool IsSubTransaction(void)
Definition: xact.c:4827

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

Referenced by standard_ProcessUtility().

◆ CopyTriggerDesc()

TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 2095 of file trigger.c.

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

162 {
163  return
164  CreateTriggerFiringOn(stmt, queryString, relOid, refRelOid,
165  constraintOid, indexOid, funcoid,
166  parentTriggerOid, whenClause, isInternal,
167  in_partition, TRIGGER_FIRES_ON_ORIGIN);
168 }
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:175
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:148

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

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

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

Referenced by CloneRowTriggersToPartition(), and CreateTrigger().

◆ EnableDisableTrigger()

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

Definition at line 1764 of file trigger.c.

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

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

Referenced by ATExecEnableDisableTrigger().

◆ ExecARDeleteTriggers()

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

Definition at line 2772 of file trigger.c.

2776 {
2777  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2778 
2779  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2780  (transition_capture && transition_capture->tcs_delete_old_table))
2781  {
2782  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2783 
2784  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2785  if (fdw_trigtuple == NULL)
2786  GetTupleForTrigger(estate,
2787  NULL,
2788  relinfo,
2789  tupleid,
2791  slot,
2792  NULL);
2793  else
2794  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2795 
2797  true, slot, NULL, NIL, NULL,
2798  transition_capture);
2799  }
2800 }
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1469
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1166
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
@ LockTupleExclusive
Definition: lockoptions.h:58
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:443
bool trig_delete_after_row
Definition: reltrigger.h:67
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5678
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:3226
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92

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

Referenced by ExecDelete(), and ExecSimpleRelationDelete().

◆ ExecARInsertTriggers()

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

Definition at line 2542 of file trigger.c.

2545 {
2546  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2547 
2548  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2549  (transition_capture && transition_capture->tcs_insert_new_table))
2551  true, NULL, slot,
2552  recheckIndexes, NULL,
2553  transition_capture);
2554 }
bool trig_insert_after_row
Definition: reltrigger.h:57
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91

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,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple,
TupleTableSlot slot,
List recheckIndexes,
TransitionCaptureState transition_capture 
)

Definition at line 3056 of file trigger.c.

3062 {
3063  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3064 
3065  if ((trigdesc && trigdesc->trig_update_after_row) ||
3066  (transition_capture &&
3067  (transition_capture->tcs_update_old_table ||
3068  transition_capture->tcs_update_new_table)))
3069  {
3070  /*
3071  * Note: if the UPDATE is converted into a DELETE+INSERT as part of
3072  * update-partition-key operation, then this function is also called
3073  * separately for DELETE and INSERT to capture transition table rows.
3074  * In such case, either old tuple or new tuple can be NULL.
3075  */
3076  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
3077 
3078  if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
3079  GetTupleForTrigger(estate,
3080  NULL,
3081  relinfo,
3082  tupleid,
3084  oldslot,
3085  NULL);
3086  else if (fdw_trigtuple != NULL)
3087  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
3088  else
3089  ExecClearTuple(oldslot);
3090 
3092  true, oldslot, newslot, recheckIndexes,
3093  ExecGetAllUpdatedCols(relinfo, estate),
3094  transition_capture);
3095  }
3096 }
Bitmapset * ExecGetAllUpdatedCols(ResultRelInfo *relinfo, EState *estate)
Definition: execUtils.c:1347
bool trig_update_after_row
Definition: reltrigger.h:62
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425

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

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

◆ ExecASDeleteTriggers()

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

Definition at line 2669 of file trigger.c.

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

2457 {
2458  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2459 
2460  if (trigdesc && trigdesc->trig_insert_after_statement)
2462  false, NULL, NULL, NIL, NULL, transition_capture);
2463 }
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 3212 of file trigger.c.

3213 {
3214  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3215 
3216  if (trigdesc && trigdesc->trig_truncate_after_statement)
3218  false, NULL, NULL, NIL, NULL, NULL);
3219 }
bool trig_truncate_after_statement
Definition: reltrigger.h:73
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:94

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

2910 {
2911  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2912 
2913  /* statement-level triggers operate on the parent table */
2914  Assert(relinfo->ri_RootResultRelInfo == NULL);
2915 
2916  if (trigdesc && trigdesc->trig_update_after_statement)
2918  false, NULL, NULL, NIL,
2919  ExecGetAllUpdatedCols(relinfo, estate),
2920  transition_capture);
2921 }
struct ResultRelInfo * ri_RootResultRelInfo
Definition: execnodes.h:517
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 2687 of file trigger.c.

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

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

Referenced by ExecDelete(), and ExecSimpleRelationDelete().

◆ ExecBRInsertTriggers()

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

Definition at line 2466 of file trigger.c.

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

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

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

◆ ExecBRUpdateTriggers()

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

Definition at line 2924 of file trigger.c.

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

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

Referenced by ExecSimpleRelationUpdate(), and ExecUpdate().

◆ ExecBSDeleteTriggers()

void ExecBSDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2618 of file trigger.c.

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

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

Referenced by fireBSTriggers().

◆ ExecBSInsertTriggers()

void ExecBSInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2404 of file trigger.c.

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

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

Referenced by CopyFrom(), and fireBSTriggers().

◆ ExecBSTruncateTriggers()

void ExecBSTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 3165 of file trigger.c.

3166 {
3167  TriggerDesc *trigdesc;
3168  int i;
3169  TriggerData LocTriggerData = {0};
3170 
3171  trigdesc = relinfo->ri_TrigDesc;
3172 
3173  if (trigdesc == NULL)
3174  return;
3175  if (!trigdesc->trig_truncate_before_statement)
3176  return;
3177 
3178  LocTriggerData.type = T_TriggerData;
3179  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
3181  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3182 
3183  for (i = 0; i < trigdesc->numtriggers; i++)
3184  {
3185  Trigger *trigger = &trigdesc->triggers[i];
3186  HeapTuple newtuple;
3187 
3188  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3189  TRIGGER_TYPE_STATEMENT,
3190  TRIGGER_TYPE_BEFORE,
3191  TRIGGER_TYPE_TRUNCATE))
3192  continue;
3193  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3194  NULL, NULL, NULL))
3195  continue;
3196 
3197  LocTriggerData.tg_trigger = trigger;
3198  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3199  i,
3200  relinfo->ri_TrigFunctions,
3201  relinfo->ri_TrigInstrument,
3202  GetPerTupleMemoryContext(estate));
3203 
3204  if (newtuple)
3205  ereport(ERROR,
3206  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
3207  errmsg("BEFORE STATEMENT trigger cannot return a value")));
3208  }
3209 }
bool trig_truncate_before_statement
Definition: reltrigger.h:72

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

Referenced by ExecuteTruncateGuts().

◆ ExecBSUpdateTriggers()

void ExecBSUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2850 of file trigger.c.

2851 {
2852  TriggerDesc *trigdesc;
2853  int i;
2854  TriggerData LocTriggerData = {0};
2855  Bitmapset *updatedCols;
2856 
2857  trigdesc = relinfo->ri_TrigDesc;
2858 
2859  if (trigdesc == NULL)
2860  return;
2861  if (!trigdesc->trig_update_before_statement)
2862  return;
2863 
2864  /* no-op if we already fired BS triggers in this context */
2866  CMD_UPDATE))
2867  return;
2868 
2869  /* statement-level triggers operate on the parent table */
2870  Assert(relinfo->ri_RootResultRelInfo == NULL);
2871 
2872  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2873 
2874  LocTriggerData.type = T_TriggerData;
2875  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2877  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2878  LocTriggerData.tg_updatedcols = updatedCols;
2879  for (i = 0; i < trigdesc->numtriggers; i++)
2880  {
2881  Trigger *trigger = &trigdesc->triggers[i];
2882  HeapTuple newtuple;
2883 
2884  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2885  TRIGGER_TYPE_STATEMENT,
2886  TRIGGER_TYPE_BEFORE,
2887  TRIGGER_TYPE_UPDATE))
2888  continue;
2889  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2890  updatedCols, NULL, NULL))
2891  continue;
2892 
2893  LocTriggerData.tg_trigger = trigger;
2894  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2895  i,
2896  relinfo->ri_TrigFunctions,
2897  relinfo->ri_TrigInstrument,
2898  GetPerTupleMemoryContext(estate));
2899 
2900  if (newtuple)
2901  ereport(ERROR,
2902  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2903  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2904  }
2905 }
@ CMD_UPDATE
Definition: nodes.h:687
bool trig_update_before_statement
Definition: reltrigger.h:64

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

Referenced by fireBSTriggers().

◆ ExecIRDeleteTriggers()

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

Definition at line 2803 of file trigger.c.

2805 {
2806  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2807  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2808  TriggerData LocTriggerData = {0};
2809  int i;
2810 
2811  LocTriggerData.type = T_TriggerData;
2812  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2815  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2816 
2817  ExecForceStoreHeapTuple(trigtuple, slot, false);
2818 
2819  for (i = 0; i < trigdesc->numtriggers; i++)
2820  {
2821  HeapTuple rettuple;
2822  Trigger *trigger = &trigdesc->triggers[i];
2823 
2824  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2825  TRIGGER_TYPE_ROW,
2826  TRIGGER_TYPE_INSTEAD,
2827  TRIGGER_TYPE_DELETE))
2828  continue;
2829  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2830  NULL, slot, NULL))
2831  continue;
2832 
2833  LocTriggerData.tg_trigslot = slot;
2834  LocTriggerData.tg_trigtuple = trigtuple;
2835  LocTriggerData.tg_trigger = trigger;
2836  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2837  i,
2838  relinfo->ri_TrigFunctions,
2839  relinfo->ri_TrigInstrument,
2840  GetPerTupleMemoryContext(estate));
2841  if (rettuple == NULL)
2842  return false; /* Delete was suppressed */
2843  if (rettuple != trigtuple)
2844  heap_freetuple(rettuple);
2845  }
2846  return true;
2847 }
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:101

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

Referenced by ExecDelete().

◆ ExecIRInsertTriggers()

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

Definition at line 2557 of file trigger.c.

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

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

Referenced by CopyFrom(), and ExecInsert().

◆ ExecIRUpdateTriggers()

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

Definition at line 3099 of file trigger.c.

3101 {
3102  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3103  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
3104  HeapTuple newtuple = NULL;
3105  bool should_free;
3106  TriggerData LocTriggerData = {0};
3107  int i;
3108 
3109  LocTriggerData.type = T_TriggerData;
3110  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
3113  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3114 
3115  ExecForceStoreHeapTuple(trigtuple, oldslot, false);
3116 
3117  for (i = 0; i < trigdesc->numtriggers; i++)
3118  {
3119  Trigger *trigger = &trigdesc->triggers[i];
3120  HeapTuple oldtuple;
3121 
3122  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3123  TRIGGER_TYPE_ROW,
3124  TRIGGER_TYPE_INSTEAD,
3125  TRIGGER_TYPE_UPDATE))
3126  continue;
3127  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3128  NULL, oldslot, newslot))
3129  continue;
3130 
3131  if (!newtuple)
3132  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
3133 
3134  LocTriggerData.tg_trigslot = oldslot;
3135  LocTriggerData.tg_trigtuple = trigtuple;
3136  LocTriggerData.tg_newslot = newslot;
3137  LocTriggerData.tg_newtuple = oldtuple = newtuple;
3138 
3139  LocTriggerData.tg_trigger = trigger;
3140  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3141  i,
3142  relinfo->ri_TrigFunctions,
3143  relinfo->ri_TrigInstrument,
3144  GetPerTupleMemoryContext(estate));
3145  if (newtuple == NULL)
3146  {
3147  return false; /* "do nothing" */
3148  }
3149  else if (newtuple != oldtuple)
3150  {
3151  ExecForceStoreHeapTuple(newtuple, newslot, false);
3152 
3153  if (should_free)
3154  heap_freetuple(oldtuple);
3155 
3156  /* signal tuple should be re-fetched if used */
3157  newtuple = NULL;
3158  }
3159  }
3160 
3161  return true;
3162 }

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

Referenced by ExecUpdate().

◆ FindTriggerIncompatibleWithInheritance()

const char* FindTriggerIncompatibleWithInheritance ( TriggerDesc trigdesc)

Definition at line 2282 of file trigger.c.

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

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

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

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

Referenced by RelationBuildTriggers(), and RelationDestroyRelation().

◆ get_trigger_oid()

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

Definition at line 1411 of file trigger.c.

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

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

4630 {
4632  bool need_old,
4633  need_new;
4634  AfterTriggersTableData *table;
4635  MemoryContext oldcxt;
4636  ResourceOwner saveResourceOwner;
4637 
4638  if (trigdesc == NULL)
4639  return NULL;
4640 
4641  /* Detect which table(s) we need. */
4642  switch (cmdType)
4643  {
4644  case CMD_INSERT:
4645  need_old = false;
4646  need_new = trigdesc->trig_insert_new_table;
4647  break;
4648  case CMD_UPDATE:
4649  need_old = trigdesc->trig_update_old_table;
4650  need_new = trigdesc->trig_update_new_table;
4651  break;
4652  case CMD_DELETE:
4653  need_old = trigdesc->trig_delete_old_table;
4654  need_new = false;
4655  break;
4656  default:
4657  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4658  need_old = need_new = false; /* keep compiler quiet */
4659  break;
4660  }
4661  if (!need_old && !need_new)
4662  return NULL;
4663 
4664  /* Check state, like AfterTriggerSaveEvent. */
4665  if (afterTriggers.query_depth < 0)
4666  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4667 
4668  /* Be sure we have enough space to record events at this query depth. */
4671 
4672  /*
4673  * Find or create an AfterTriggersTableData struct to hold the
4674  * tuplestore(s). If there's a matching struct but it's marked closed,
4675  * ignore it; we need a newer one.
4676  *
4677  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4678  * allocated in the current (sub)transaction's CurTransactionContext, and
4679  * the tuplestores are managed by the (sub)transaction's resource owner.
4680  * This is sufficient lifespan because we do not allow triggers using
4681  * transition tables to be deferrable; they will be fired during
4682  * AfterTriggerEndQuery, after which it's okay to delete the data.
4683  */
4684  table = GetAfterTriggersTableData(relid, cmdType);
4685 
4686  /* Now create required tuplestore(s), if we don't have them already. */
4688  saveResourceOwner = CurrentResourceOwner;
4690 
4691  if (need_old && table->old_tuplestore == NULL)
4692  table->old_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4693  if (need_new && table->new_tuplestore == NULL)
4694  table->new_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4695 
4696  CurrentResourceOwner = saveResourceOwner;
4697  MemoryContextSwitchTo(oldcxt);
4698 
4699  /* Now build the TransitionCaptureState struct, in caller's context */
4701  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4702  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4703  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4704  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4705  state->tcs_private = table;
4706 
4707  return state;
4708 }
int work_mem
Definition: globals.c:124
void * palloc0(Size size)
Definition: mcxt.c:1093
MemoryContext CurTransactionContext
Definition: mcxt.c:54
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:147
Tuplestorestate * new_tuplestore
Definition: trigger.c:3756
Tuplestorestate * old_tuplestore
Definition: trigger.c:3755
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:4545
static void AfterTriggerEnlargeQueryState(void)
Definition: trigger.c:5171
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318

References AfterTriggerEnlargeQueryState(), afterTriggers, CMD_DELETE, CMD_INSERT, CMD_UPDATE, CurrentResourceOwner, CurTransactionContext, CurTransactionResourceOwner, elog, ERROR, GetAfterTriggersTableData(), AfterTriggersData::maxquerydepth, MemoryContextSwitchTo(), AfterTriggersTableData::new_tuplestore, AfterTriggersTableData::old_tuplestore, palloc0(), AfterTriggersData::query_depth, 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 1866 of file trigger.c.

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

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

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

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

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

Referenced by ExecRenameStmt().

◆ RI_FKey_fk_upd_check_required()

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

Definition at line 1255 of file ri_triggers.c.

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

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

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_pk_upd_check_required()

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

Definition at line 1223 of file ri_triggers.c.

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

2986 {
2987  switch (tgfoid)
2988  {
2989  case F_RI_FKEY_CASCADE_DEL:
2990  case F_RI_FKEY_CASCADE_UPD:
2991  case F_RI_FKEY_RESTRICT_DEL:
2992  case F_RI_FKEY_RESTRICT_UPD:
2993  case F_RI_FKEY_SETNULL_DEL:
2994  case F_RI_FKEY_SETNULL_UPD:
2995  case F_RI_FKEY_SETDEFAULT_DEL:
2996  case F_RI_FKEY_SETDEFAULT_UPD:
2997  case F_RI_FKEY_NOACTION_DEL:
2998  case F_RI_FKEY_NOACTION_UPD:
2999  return RI_TRIGGER_PK;
3000 
3001  case F_RI_FKEY_CHECK_INS:
3002  case F_RI_FKEY_CHECK_UPD:
3003  return RI_TRIGGER_FK;
3004  }
3005 
3006  return RI_TRIGGER_NONE;
3007 }
#define RI_TRIGGER_FK
Definition: trigger.h:273
#define RI_TRIGGER_NONE
Definition: trigger.h:274
#define RI_TRIGGER_PK
Definition: trigger.h:272

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

Referenced by AfterTriggerSaveEvent().

◆ RI_Initial_Check()

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

Definition at line 1356 of file ri_triggers.c.

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

References AccessShareLock, ACL_SELECT, appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), bms_add_member(), RI_ConstraintInfo::confmatchtype, RI_ConstraintInfo::conname, StringInfoData::data, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, errtableconstraint(), ExecCheckR