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

Go to the source code of this file.

Data Structures

struct  TriggerData
 
struct  TransitionCaptureState
 

Macros

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

Typedefs

typedef uint32 TriggerEvent
 
typedef struct TriggerData TriggerData
 
typedef struct TransitionCaptureState TransitionCaptureState
 

Functions

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

Variables

PGDLLIMPORT int SessionReplicationRole
 

Macro Definition Documentation

◆ AFTER_TRIGGER_DEFERRABLE

#define AFTER_TRIGGER_DEFERRABLE   0x00000020

Definition at line 107 of file trigger.h.

◆ AFTER_TRIGGER_INITDEFERRED

#define AFTER_TRIGGER_INITDEFERRED   0x00000040

Definition at line 108 of file trigger.h.

◆ CALLED_AS_TRIGGER

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

Definition at line 26 of file trigger.h.

◆ RI_TRIGGER_FK

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

Definition at line 283 of file trigger.h.

◆ RI_TRIGGER_NONE

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

Definition at line 284 of file trigger.h.

◆ RI_TRIGGER_PK

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

Definition at line 282 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_LOCAL

#define SESSION_REPLICATION_ROLE_LOCAL   2

Definition at line 142 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_ORIGIN

#define SESSION_REPLICATION_ROLE_ORIGIN   0

Definition at line 140 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_REPLICA

#define SESSION_REPLICATION_ROLE_REPLICA   1

Definition at line 141 of file trigger.h.

◆ TRIGGER_DISABLED

#define TRIGGER_DISABLED   'D'

Definition at line 152 of file trigger.h.

◆ TRIGGER_EVENT_AFTER

#define TRIGGER_EVENT_AFTER   0x00000000

Definition at line 101 of file trigger.h.

◆ TRIGGER_EVENT_BEFORE

#define TRIGGER_EVENT_BEFORE   0x00000008

Definition at line 100 of file trigger.h.

◆ TRIGGER_EVENT_DELETE

#define TRIGGER_EVENT_DELETE   0x00000001

Definition at line 93 of file trigger.h.

◆ TRIGGER_EVENT_INSERT

#define TRIGGER_EVENT_INSERT   0x00000000

Definition at line 92 of file trigger.h.

◆ TRIGGER_EVENT_INSTEAD

#define TRIGGER_EVENT_INSTEAD   0x00000010

Definition at line 102 of file trigger.h.

◆ TRIGGER_EVENT_OPMASK

#define TRIGGER_EVENT_OPMASK   0x00000003

Definition at line 96 of file trigger.h.

◆ TRIGGER_EVENT_ROW

#define TRIGGER_EVENT_ROW   0x00000004

Definition at line 98 of file trigger.h.

◆ TRIGGER_EVENT_TIMINGMASK

#define TRIGGER_EVENT_TIMINGMASK   0x00000018

Definition at line 103 of file trigger.h.

◆ TRIGGER_EVENT_TRUNCATE

#define TRIGGER_EVENT_TRUNCATE   0x00000003

Definition at line 95 of file trigger.h.

◆ TRIGGER_EVENT_UPDATE

#define TRIGGER_EVENT_UPDATE   0x00000002

Definition at line 94 of file trigger.h.

◆ TRIGGER_FIRED_AFTER

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

Definition at line 131 of file trigger.h.

◆ TRIGGER_FIRED_BEFORE

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

Definition at line 128 of file trigger.h.

◆ TRIGGER_FIRED_BY_DELETE

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

Definition at line 113 of file trigger.h.

◆ TRIGGER_FIRED_BY_INSERT

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

Definition at line 110 of file trigger.h.

◆ TRIGGER_FIRED_BY_TRUNCATE

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

Definition at line 119 of file trigger.h.

◆ TRIGGER_FIRED_BY_UPDATE

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

Definition at line 116 of file trigger.h.

◆ TRIGGER_FIRED_FOR_ROW

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

Definition at line 122 of file trigger.h.

◆ TRIGGER_FIRED_FOR_STATEMENT

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

Definition at line 125 of file trigger.h.

◆ TRIGGER_FIRED_INSTEAD

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

Definition at line 134 of file trigger.h.

◆ TRIGGER_FIRES_ALWAYS

#define TRIGGER_FIRES_ALWAYS   'A'

Definition at line 150 of file trigger.h.

◆ TRIGGER_FIRES_ON_ORIGIN

#define TRIGGER_FIRES_ON_ORIGIN   'O'

Definition at line 149 of file trigger.h.

◆ TRIGGER_FIRES_ON_REPLICA

#define TRIGGER_FIRES_ON_REPLICA   'R'

Definition at line 151 of file trigger.h.

Typedef Documentation

◆ TransitionCaptureState

◆ TriggerData

typedef struct TriggerData TriggerData

◆ TriggerEvent

Definition at line 29 of file trigger.h.

Function Documentation

◆ AfterTriggerBeginQuery()

void AfterTriggerBeginQuery ( void  )

Definition at line 5018 of file trigger.c.

5019 {
5020  /* Increase the query stack depth */
5022 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3878

References afterTriggers, and AfterTriggersData::query_depth.

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

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 5301 of file trigger.c.

5302 {
5303  int my_level = GetCurrentTransactionNestLevel();
5304 
5305  /*
5306  * Allocate more space in the trans_stack if needed. (Note: because the
5307  * minimum nest level of a subtransaction is 2, we waste the first couple
5308  * entries of the array; not worth the notational effort to avoid it.)
5309  */
5310  while (my_level >= afterTriggers.maxtransdepth)
5311  {
5312  if (afterTriggers.maxtransdepth == 0)
5313  {
5314  /* Arbitrarily initialize for max of 8 subtransaction levels */
5317  8 * sizeof(AfterTriggersTransData));
5319  }
5320  else
5321  {
5322  /* repalloc will keep the stack in the same context */
5323  int new_alloc = afterTriggers.maxtransdepth * 2;
5324 
5327  new_alloc * sizeof(AfterTriggersTransData));
5328  afterTriggers.maxtransdepth = new_alloc;
5329  }
5330  }
5331 
5332  /*
5333  * Push the current information into the stack. The SET CONSTRAINTS state
5334  * is not saved until/unless changed. Likewise, we don't make a
5335  * per-subtransaction event context until needed.
5336  */
5337  afterTriggers.trans_stack[my_level].state = NULL;
5341 }
MemoryContext TopTransactionContext
Definition: mcxt.c:142
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1528
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1168
CommandId firing_counter
Definition: trigger.c:3818
AfterTriggersTransData * trans_stack
Definition: trigger.c:3829
AfterTriggerEventList events
Definition: trigger.c:3820
AfterTriggerEventList events
Definition: trigger.c:3844
SetConstraintState state
Definition: trigger.c:3843
CommandId firing_counter
Definition: trigger.c:3846
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:915

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

4987 {
4988  /*
4989  * Initialize after-trigger state structure to empty
4990  */
4991  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4993 
4994  /*
4995  * Verify that there is no leftover state remaining. If these assertions
4996  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4997  * up properly.
4998  */
4999  Assert(afterTriggers.state == NULL);
5000  Assert(afterTriggers.query_stack == NULL);
5002  Assert(afterTriggers.event_cxt == NULL);
5003  Assert(afterTriggers.events.head == NULL);
5004  Assert(afterTriggers.trans_stack == NULL);
5006 }
uint32 CommandId
Definition: c.h:653
Assert(fmt[strlen(fmt) - 1] !='\n')
AfterTriggerEventChunk * head
Definition: trigger.c:3712
SetConstraintState state
Definition: trigger.c:3819
AfterTriggersQueryData * query_stack
Definition: trigger.c:3824
MemoryContext event_cxt
Definition: trigger.c:3821

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

5039 {
5041 
5042  /* Must be inside a query, too */
5044 
5045  /*
5046  * If we never even got as far as initializing the event stack, there
5047  * certainly won't be any events, so exit quickly.
5048  */
5050  {
5052  return;
5053  }
5054 
5055  /*
5056  * Process all immediate-mode triggers queued by the query, and move the
5057  * deferred ones to the main list of deferred events.
5058  *
5059  * Notice that we decide which ones will be fired, and put the deferred
5060  * ones on the main list, before anything is actually fired. This ensures
5061  * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
5062  * IMMEDIATE: all events we have decided to defer will be available for it
5063  * to fire.
5064  *
5065  * We loop in case a trigger queues more events at the same query level.
5066  * Ordinary trigger functions, including all PL/pgSQL trigger functions,
5067  * will instead fire any triggers in a dedicated query level. Foreign key
5068  * enforcement triggers do add to the current query level, thanks to their
5069  * passing fire_triggers = false to SPI_execute_snapshot(). Other
5070  * C-language triggers might do likewise.
5071  *
5072  * If we find no firable events, we don't have to increment
5073  * firing_counter.
5074  */
5076 
5077  for (;;)
5078  {
5080  {
5081  CommandId firing_id = afterTriggers.firing_counter++;
5082  AfterTriggerEventChunk *oldtail = qs->events.tail;
5083 
5084  if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
5085  break; /* all fired */
5086 
5087  /*
5088  * Firing a trigger could result in query_stack being repalloc'd,
5089  * so we must recalculate qs after each afterTriggerInvokeEvents
5090  * call. Furthermore, it's unsafe to pass delete_ok = true here,
5091  * because that could cause afterTriggerInvokeEvents to try to
5092  * access qs->events after the stack has been repalloc'd.
5093  */
5095 
5096  /*
5097  * We'll need to scan the events list again. To reduce the cost
5098  * of doing so, get rid of completely-fired chunks. We know that
5099  * all events were marked IN_PROGRESS or DONE at the conclusion of
5100  * afterTriggerMarkEvents, so any still-interesting events must
5101  * have been added after that, and so must be in the chunk that
5102  * was then the tail chunk, or in later chunks. So, zap all
5103  * chunks before oldtail. This is approximately the same set of
5104  * events we would have gotten rid of by passing delete_ok = true.
5105  */
5106  Assert(oldtail != NULL);
5107  while (qs->events.head != oldtail)
5109  }
5110  else
5111  break;
5112  }
5113 
5114  /* Release query-level-local storage, including tuplestores if any */
5116 
5118 }
AfterTriggerEventChunk * tail
Definition: trigger.c:3713
AfterTriggerEventList events
Definition: trigger.c:3835
static void afterTriggerDeleteHeadEventChunk(AfterTriggersQueryData *qs)
Definition: trigger.c:4208
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:5129
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4541
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4625

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

5350 {
5351  int my_level = GetCurrentTransactionNestLevel();
5353  AfterTriggerEvent event;
5354  AfterTriggerEventChunk *chunk;
5355  CommandId subxact_firing_id;
5356 
5357  /*
5358  * Pop the prior state if needed.
5359  */
5360  if (isCommit)
5361  {
5362  Assert(my_level < afterTriggers.maxtransdepth);
5363  /* If we saved a prior state, we don't need it anymore */
5364  state = afterTriggers.trans_stack[my_level].state;
5365  if (state != NULL)
5366  pfree(state);
5367  /* this avoids double pfree if error later: */
5368  afterTriggers.trans_stack[my_level].state = NULL;
5371  }
5372  else
5373  {
5374  /*
5375  * Aborting. It is possible subxact start failed before calling
5376  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
5377  * trans_stack levels that aren't there.
5378  */
5379  if (my_level >= afterTriggers.maxtransdepth)
5380  return;
5381 
5382  /*
5383  * Release query-level storage for queries being aborted, and restore
5384  * query_depth to its pre-subxact value. This assumes that a
5385  * subtransaction will not add events to query levels started in a
5386  * earlier transaction state.
5387  */
5389  {
5393  }
5396 
5397  /*
5398  * Restore the global deferred-event list to its former length,
5399  * discarding any events queued by the subxact.
5400  */
5402  &afterTriggers.trans_stack[my_level].events);
5403 
5404  /*
5405  * Restore the trigger state. If the saved state is NULL, then this
5406  * subxact didn't save it, so it doesn't need restoring.
5407  */
5408  state = afterTriggers.trans_stack[my_level].state;
5409  if (state != NULL)
5410  {
5413  }
5414  /* this avoids double pfree if error later: */
5415  afterTriggers.trans_stack[my_level].state = NULL;
5416 
5417  /*
5418  * Scan for any remaining deferred events that were marked DONE or IN
5419  * PROGRESS by this subxact or a child, and un-mark them. We can
5420  * recognize such events because they have a firing ID greater than or
5421  * equal to the firing_counter value we saved at subtransaction start.
5422  * (This essentially assumes that the current subxact includes all
5423  * subxacts started after it.)
5424  */
5425  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
5427  {
5428  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5429 
5430  if (event->ate_flags &
5432  {
5433  if (evtshared->ats_firing_id >= subxact_firing_id)
5434  event->ate_flags &=
5436  }
5437  }
5438  }
5439 }
void pfree(void *pointer)
Definition: mcxt.c:1508
TriggerFlags ate_flags
Definition: trigger.c:3645
CommandId ats_firing_id
Definition: trigger.c:3636
Definition: regguts.h:323
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3621
#define GetTriggerSharedData(evt)
Definition: trigger.c:3688
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:4168
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3620
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3725

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

5254 {
5255  /*
5256  * Forget the pending-events list.
5257  *
5258  * Since all the info is in TopTransactionContext or children thereof, we
5259  * don't really need to do anything to reclaim memory. However, the
5260  * pending-events list could be large, and so it's useful to discard it as
5261  * soon as possible --- especially if we are aborting because we ran out
5262  * of memory for the list!
5263  */
5265  {
5267  afterTriggers.event_cxt = NULL;
5268  afterTriggers.events.head = NULL;
5269  afterTriggers.events.tail = NULL;
5270  afterTriggers.events.tailfree = NULL;
5271  }
5272 
5273  /*
5274  * Forget any subtransaction state as well. Since this can't be very
5275  * large, we let the eventual reset of TopTransactionContext free the
5276  * memory instead of doing it here.
5277  */
5278  afterTriggers.trans_stack = NULL;
5280 
5281 
5282  /*
5283  * Forget the query stack and constraint-related state information. As
5284  * with the subtransaction state information, we don't bother freeing the
5285  * memory here.
5286  */
5287  afterTriggers.query_stack = NULL;
5289  afterTriggers.state = NULL;
5290 
5291  /* No more afterTriggers manipulation until next transaction starts. */
5293 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:442

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

5198 {
5199  AfterTriggerEventList *events;
5200  bool snap_pushed = false;
5201 
5202  /* Must not be inside a query */
5204 
5205  /*
5206  * If there are any triggers to fire, make sure we have set a snapshot for
5207  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
5208  * can't assume ActiveSnapshot is valid on entry.)
5209  */
5210  events = &afterTriggers.events;
5211  if (events->head != NULL)
5212  {
5214  snap_pushed = true;
5215  }
5216 
5217  /*
5218  * Run all the remaining triggers. Loop until they are all gone, in case
5219  * some trigger queues more for us to do.
5220  */
5221  while (afterTriggerMarkEvents(events, NULL, false))
5222  {
5223  CommandId firing_id = afterTriggers.firing_counter++;
5224 
5225  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
5226  break; /* all fired */
5227  }
5228 
5229  /*
5230  * We don't bother freeing the event list, since it will go away anyway
5231  * (and more efficiently than via pfree) in AfterTriggerEndXact.
5232  */
5233 
5234  if (snap_pushed)
5236 }
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:648
void PopActiveSnapshot(void)
Definition: snapmgr.c:743

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

5975 {
5976  AfterTriggerEvent event;
5977  AfterTriggerEventChunk *chunk;
5978  int depth;
5979 
5980  /* Scan queued events */
5982  {
5983  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5984 
5985  /*
5986  * We can ignore completed events. (Even if a DONE flag is rolled
5987  * back by subxact abort, it's OK because the effects of the TRUNCATE
5988  * or whatever must get rolled back too.)
5989  */
5990  if (event->ate_flags & AFTER_TRIGGER_DONE)
5991  continue;
5992 
5993  if (evtshared->ats_relid == relid)
5994  return true;
5995  }
5996 
5997  /*
5998  * Also scan events queued by incomplete queries. This could only matter
5999  * if TRUNCATE/etc is executed by a function or trigger within an updating
6000  * query on the same relation, which is pretty perverse, but let's check.
6001  */
6002  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
6003  {
6005  {
6006  AfterTriggerShared evtshared = GetTriggerSharedData(event);
6007 
6008  if (event->ate_flags & AFTER_TRIGGER_DONE)
6009  continue;
6010 
6011  if (evtshared->ats_relid == relid)
6012  return true;
6013  }
6014  }
6015 
6016  return false;
6017 }

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

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

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

Referenced by standard_ProcessUtility().

◆ CopyTriggerDesc()

TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 2085 of file trigger.c.

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

References CreateTriggerFiringOn(), stmt, and TRIGGER_FIRES_ON_ORIGIN.

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

◆ CreateTriggerFiringOn()

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

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

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

Referenced by CloneRowTriggersToPartition(), and CreateTrigger().

◆ EnableDisableTrigger()

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

Definition at line 1721 of file trigger.c.

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

References BTEqualStrategyNumber, CacheInvalidateRelcache(), CatalogTupleUpdate(), CStringGetDatum(), ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_copytuple(), heap_freetuple(), HeapTupleIsValid, i, InvokeObjectPostAlterHook, NameStr, NoLock, PartitionDescData::nparts, ObjectIdGetDatum(), OidIsValid, PartitionDescData::oids, RelationData::rd_rel, relation_open(), RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, RowExclusiveLock, ScanKeyInit(), superuser(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, table_close(), and table_open().

Referenced by ATExecEnableDisableTrigger().

◆ ExecARDeleteTriggers()

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

Definition at line 2774 of file trigger.c.

2780 {
2781  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2782 
2783  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2784  (transition_capture && transition_capture->tcs_delete_old_table))
2785  {
2786  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2787 
2788  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2789  if (fdw_trigtuple == NULL)
2790  GetTupleForTrigger(estate,
2791  NULL,
2792  relinfo,
2793  tupleid,
2795  slot,
2796  NULL,
2797  NULL,
2798  NULL);
2799  else
2800  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2801 
2802  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2804  true, slot, NULL, NIL, NULL,
2805  transition_capture,
2806  is_crosspart_update);
2807  }
2808 }
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1468
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1138
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83
@ LockTupleExclusive
Definition: lockoptions.h:58
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:486
bool trig_delete_after_row
Definition: reltrigger.h:67
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, ResultRelInfo *src_partinfo, ResultRelInfo *dst_partinfo, int event, bool row_trigger, TupleTableSlot *oldslot, TupleTableSlot *newslot, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture, bool is_crosspart_update)
Definition: trigger.c:6061
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **epqslot, TM_Result *tmresultp, TM_FailureData *tmfdp)
Definition: trigger.c:3286
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:93

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

Referenced by ExecDeleteEpilogue(), and ExecSimpleRelationDelete().

◆ ExecARInsertTriggers()

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

Definition at line 2534 of file trigger.c.

2537 {
2538  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2539 
2540  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2541  (transition_capture && transition_capture->tcs_insert_new_table))
2542  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2544  true, NULL, slot,
2545  recheckIndexes, NULL,
2546  transition_capture,
2547  false);
2548 }
bool trig_insert_after_row
Definition: reltrigger.h:57
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:92

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

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

◆ ExecARUpdateTriggers()

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

Definition at line 3097 of file trigger.c.

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

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

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

◆ ExecASDeleteTriggers()

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

Definition at line 2663 of file trigger.c.

2665 {
2666  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2667 
2668  if (trigdesc && trigdesc->trig_delete_after_statement)
2669  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2671  false, NULL, NULL, NIL, NULL, transition_capture,
2672  false);
2673 }
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 2445 of file trigger.c.

2447 {
2448  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2449 
2450  if (trigdesc && trigdesc->trig_insert_after_statement)
2451  AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2453  false, NULL, NULL, NIL, NULL, transition_capture,
2454  false);
2455 }
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 3269 of file trigger.c.

3270 {
3271  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3272 
3273  if (trigdesc && trigdesc->trig_truncate_after_statement)
3274  AfterTriggerSaveEvent(estate, relinfo,
3275  NULL, NULL,
3277  false, NULL, NULL, NIL, NULL, NULL,
3278  false);
3279 }
bool trig_truncate_after_statement
Definition: reltrigger.h:73
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:95

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

Referenced by ExecuteTruncateGuts().

◆ ExecASUpdateTriggers()

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

Definition at line 2916 of file trigger.c.

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

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

Referenced by fireASTriggers().

◆ ExecBRDeleteTriggers()

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

Definition at line 2683 of file trigger.c.

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

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

Referenced by ExecDeletePrologue(), and ExecSimpleRelationDelete().

◆ ExecBRInsertTriggers()

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

Definition at line 2458 of file trigger.c.

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

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

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

◆ ExecBRUpdateTriggers()

bool ExecBRUpdateTriggers ( EState estate,
EPQState epqstate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple,
TupleTableSlot newslot,
TM_Result tmresult,
TM_FailureData tmfd 
)

Definition at line 2934 of file trigger.c.

2941 {
2942  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2943  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2944  HeapTuple newtuple = NULL;
2945  HeapTuple trigtuple;
2946  bool should_free_trig = false;
2947  bool should_free_new = false;
2948  TriggerData LocTriggerData = {0};
2949  int i;
2950  Bitmapset *updatedCols;
2951  LockTupleMode lockmode;
2952 
2953  /* Determine lock mode to use */
2954  lockmode = ExecUpdateLockMode(estate, relinfo);
2955 
2956  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2957  if (fdw_trigtuple == NULL)
2958  {
2959  TupleTableSlot *epqslot_candidate = NULL;
2960 
2961  /* get a copy of the on-disk tuple we are planning to update */
2962  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2963  lockmode, oldslot, &epqslot_candidate,
2964  tmresult, tmfd))
2965  return false; /* cancel the update action */
2966 
2967  /*
2968  * In READ COMMITTED isolation level it's possible that target tuple
2969  * was changed due to concurrent update. In that case we have a raw
2970  * subplan output tuple in epqslot_candidate, and need to form a new
2971  * insertable tuple using ExecGetUpdateNewTuple to replace the one we
2972  * received in newslot. Neither we nor our callers have any further
2973  * interest in the passed-in tuple, so it's okay to overwrite newslot
2974  * with the newer data.
2975  */
2976  if (epqslot_candidate != NULL)
2977  {
2978  TupleTableSlot *epqslot_clean;
2979 
2980  epqslot_clean = ExecGetUpdateNewTuple(relinfo, epqslot_candidate,
2981  oldslot);
2982 
2983  /*
2984  * Typically, the caller's newslot was also generated by
2985  * ExecGetUpdateNewTuple, so that epqslot_clean will be the same
2986  * slot and copying is not needed. But do the right thing if it
2987  * isn't.
2988  */
2989  if (unlikely(newslot != epqslot_clean))
2990  ExecCopySlot(newslot, epqslot_clean);
2991 
2992  /*
2993  * At this point newslot contains a virtual tuple that may
2994  * reference some fields of oldslot's tuple in some disk buffer.
2995  * If that tuple is in a different page than the original target
2996  * tuple, then our only pin on that buffer is oldslot's, and we're
2997  * about to release it. Hence we'd better materialize newslot to
2998  * ensure it doesn't contain references into an unpinned buffer.
2999  * (We'd materialize it below anyway, but too late for safety.)
3000  */
3001  ExecMaterializeSlot(newslot);
3002  }
3003 
3004  /*
3005  * Here we convert oldslot to a materialized slot holding trigtuple.
3006  * Neither slot passed to the triggers will hold any buffer pin.
3007  */
3008  trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
3009  }
3010  else
3011  {
3012  /* Put the FDW-supplied tuple into oldslot to unify the cases */
3013  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
3014  trigtuple = fdw_trigtuple;
3015  }
3016 
3017  LocTriggerData.type = T_TriggerData;
3018  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
3021  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3022  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
3023  LocTriggerData.tg_updatedcols = updatedCols;
3024  for (i = 0; i < trigdesc->numtriggers; i++)
3025  {
3026  Trigger *trigger = &trigdesc->triggers[i];
3027  HeapTuple oldtuple;
3028 
3029  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3030  TRIGGER_TYPE_ROW,
3031  TRIGGER_TYPE_BEFORE,
3032  TRIGGER_TYPE_UPDATE))
3033  continue;
3034  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3035  updatedCols, oldslot, newslot))
3036  continue;
3037 
3038  if (!newtuple)
3039  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
3040 
3041  LocTriggerData.tg_trigslot = oldslot;
3042  LocTriggerData.tg_trigtuple = trigtuple;
3043  LocTriggerData.tg_newtuple = oldtuple = newtuple;
3044  LocTriggerData.tg_newslot = newslot;
3045  LocTriggerData.tg_trigger = trigger;
3046  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3047  i,
3048  relinfo->ri_TrigFunctions,
3049  relinfo->ri_TrigInstrument,
3050  GetPerTupleMemoryContext(estate));
3051 
3052  if (newtuple == NULL)
3053  {
3054  if (should_free_trig)
3055  heap_freetuple(trigtuple);
3056  if (should_free_new)
3057  heap_freetuple(oldtuple);
3058  return false; /* "do nothing" */
3059  }
3060  else if (newtuple != oldtuple)
3061  {
3062  ExecForceStoreHeapTuple(newtuple, newslot, false);
3063 
3064  /*
3065  * If the tuple returned by the trigger / being stored, is the old
3066  * row version, and the heap tuple passed to the trigger was
3067  * allocated locally, materialize the slot. Otherwise we might
3068  * free it while still referenced by the slot.
3069  */
3070  if (should_free_trig && newtuple == trigtuple)
3071  ExecMaterializeSlot(newslot);
3072 
3073  if (should_free_new)
3074  heap_freetuple(oldtuple);
3075 
3076  /* signal tuple should be re-fetched if used */
3077  newtuple = NULL;
3078  }
3079  }
3080  if (should_free_trig)
3081  heap_freetuple(trigtuple);
3082 
3083  return true;
3084 }
#define unlikely(x)
Definition: c.h:298
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2349
LockTupleMode
Definition: lockoptions.h:50
TupleTableSlot * ExecGetUpdateNewTuple(ResultRelInfo *relinfo, TupleTableSlot *planSlot, TupleTableSlot *oldSlot)
const Bitmapset * tg_updatedcols
Definition: trigger.h:43
HeapTuple tg_newtuple
Definition: trigger.h:37
TupleTableSlot * tg_newslot
Definition: trigger.h:40
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:488
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:451

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

Referenced by ExecSimpleRelationUpdate(), and ExecUpdatePrologue().

◆ ExecBSDeleteTriggers()

void ExecBSDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2612 of file trigger.c.

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

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

Referenced by fireBSTriggers().

◆ ExecBSInsertTriggers()

void ExecBSInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2394 of file trigger.c.

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

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

Referenced by CopyFrom(), and fireBSTriggers().

◆ ExecBSTruncateTriggers()

void ExecBSTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 3222 of file trigger.c.

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

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

Referenced by ExecuteTruncateGuts().

◆ ExecBSUpdateTriggers()

void ExecBSUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2858 of file trigger.c.

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

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

Referenced by fireBSTriggers().

◆ ExecIRDeleteTriggers()

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

Definition at line 2811 of file trigger.c.

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

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

Referenced by ExecDelete(), and ExecMergeMatched().

◆ ExecIRInsertTriggers()

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

Definition at line 2551 of file trigger.c.

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

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

Referenced by CopyFrom(), and ExecInsert().

◆ ExecIRUpdateTriggers()

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

Definition at line 3156 of file trigger.c.

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

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

Referenced by ExecMergeMatched(), and ExecUpdate().

◆ FindTriggerIncompatibleWithInheritance()

const char* FindTriggerIncompatibleWithInheritance ( TriggerDesc trigdesc)

Definition at line 2272 of file trigger.c.

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

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

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

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

Referenced by RelationBuildTriggers(), and RelationDestroyRelation().

◆ get_trigger_oid()

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

Definition at line 1366 of file trigger.c.

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

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

4883 {
4885  bool need_old_upd,
4886  need_new_upd,
4887  need_old_del,
4888  need_new_ins;
4889  AfterTriggersTableData *table;
4890  MemoryContext oldcxt;
4891  ResourceOwner saveResourceOwner;
4892 
4893  if (trigdesc == NULL)
4894  return NULL;
4895 
4896  /* Detect which table(s) we need. */
4897  switch (cmdType)
4898  {
4899  case CMD_INSERT:
4900  need_old_upd = need_old_del = need_new_upd = false;
4901  need_new_ins = trigdesc->trig_insert_new_table;
4902  break;
4903  case CMD_UPDATE:
4904  need_old_upd = trigdesc->trig_update_old_table;
4905  need_new_upd = trigdesc->trig_update_new_table;
4906  need_old_del = need_new_ins = false;
4907  break;
4908  case CMD_DELETE:
4909  need_old_del = trigdesc->trig_delete_old_table;
4910  need_old_upd = need_new_upd = need_new_ins = false;
4911  break;
4912  case CMD_MERGE:
4913  need_old_upd = trigdesc->trig_update_old_table;
4914  need_new_upd = trigdesc->trig_update_new_table;
4915  need_old_del = trigdesc->trig_delete_old_table;
4916  need_new_ins = trigdesc->trig_insert_new_table;
4917  break;
4918  default:
4919  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4920  /* keep compiler quiet */
4921  need_old_upd = need_new_upd = need_old_del = need_new_ins = false;
4922  break;
4923  }
4924  if (!need_old_upd && !need_new_upd && !need_new_ins && !need_old_del)
4925  return NULL;
4926 
4927  /* Check state, like AfterTriggerSaveEvent. */
4928  if (afterTriggers.query_depth < 0)
4929  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4930 
4931  /* Be sure we have enough space to record events at this query depth. */
4934 
4935  /*
4936  * Find or create an AfterTriggersTableData struct to hold the
4937  * tuplestore(s). If there's a matching struct but it's marked closed,
4938  * ignore it; we need a newer one.
4939  *
4940  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4941  * allocated in the current (sub)transaction's CurTransactionContext, and
4942  * the tuplestores are managed by the (sub)transaction's resource owner.
4943  * This is sufficient lifespan because we do not allow triggers using
4944  * transition tables to be deferrable; they will be fired during
4945  * AfterTriggerEndQuery, after which it's okay to delete the data.
4946  */
4947  table = GetAfterTriggersTableData(relid, cmdType);
4948 
4949  /* Now create required tuplestore(s), if we don't have them already. */
4951  saveResourceOwner = CurrentResourceOwner;
4953 
4954  if (need_old_upd && table->old_upd_tuplestore == NULL)
4955  table->old_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4956  if (need_new_upd && table->new_upd_tuplestore == NULL)
4957  table->new_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4958  if (need_old_del && table->old_del_tuplestore == NULL)
4959  table->old_del_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4960  if (need_new_ins && table->new_ins_tuplestore == NULL)
4961  table->new_ins_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4962 
4963  CurrentResourceOwner = saveResourceOwner;
4964  MemoryContextSwitchTo(oldcxt);
4965 
4966  /* Now build the TransitionCaptureState struct, in caller's context */
4968  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4969  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4970  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4971  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4972  state->tcs_private = table;
4973 
4974  return state;
4975 }
int work_mem
Definition: globals.c:128
void * palloc0(Size size)
Definition: mcxt.c:1334
MemoryContext CurTransactionContext
Definition: mcxt.c:143
@ CMD_MERGE
Definition: nodes.h:259
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:166
Tuplestorestate * old_upd_tuplestore
Definition: trigger.c:3867
Tuplestorestate * new_upd_tuplestore
Definition: trigger.c:3869
Tuplestorestate * old_del_tuplestore
Definition: trigger.c:3871
Tuplestorestate * new_ins_tuplestore
Definition: trigger.c:3873
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:4796
static void AfterTriggerEnlargeQueryState(void)
Definition: trigger.c:5537
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318

References AfterTriggerEnlargeQueryState(), afterTriggers, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_UPDATE, CurrentResourceOwner, CurTransactionContext, CurTransactionResourceOwner, elog, ERROR, GetAfterTriggersTableData(), AfterTriggersData::maxquerydepth, MemoryContextSwitchTo(), AfterTriggersTableData::new_ins_tuplestore, AfterTriggersTableData::new_upd_tuplestore, AfterTriggersTableData::old_del_tuplestore, AfterTriggersTableData::old_upd_tuplestore, palloc0(), AfterTriggersData::query_depth, TriggerDesc::trig_delete_old_table, TriggerDesc::trig_insert_new_table, TriggerDesc::trig_update_new_table, TriggerDesc::trig_update_old_table, tuplestore_begin_heap(), and work_mem.

Referenced by CopyFrom(), and ExecSetupTransitionCaptureState().

◆ RelationBuildTriggers()

void RelationBuildTriggers ( Relation  relation)

Definition at line 1856 of file trigger.c.

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

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

Referenced by RelationBuildDesc(), and RelationCacheInitializePhase3().

◆ RemoveTriggerById()

void RemoveTriggerById ( Oid  trigOid)

Definition at line 1287 of file trigger.c.

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

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

Referenced by doDeletion().

◆ renametrig()

ObjectAddress renametrig ( RenameStmt stmt)

Definition at line 1463 of file trigger.c.

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

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

Referenced by ExecRenameStmt().

◆ RI_FKey_fk_upd_check_required()

bool RI_FKey_fk_upd_check_required ( Trigger trigger,
Relation  fk_rel,
TupleTableSlot oldslot,
TupleTableSlot newslot 
)

Definition at line 1258 of file ri_triggers.c.

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

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

Referenced by AfterTriggerSaveEvent().

◆ RI_FKey_pk_upd_check_required()

bool RI_FKey_pk_upd_check_required ( Trigger trigger,
Relation  pk_rel,
TupleTableSlot oldslot,
TupleTableSlot newslot 
)

Definition at line 1226 of file ri_triggers.c.

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

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

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

References RI_TRIGGER_FK, RI_TRIGGER_NONE, and RI_TRIGGER_PK.

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

◆ RI_Initial_Check()

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

Definition at line 1365 of file ri_triggers.c.

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

Referenced by validateForeignKeyConstraint().

◆ RI_PartitionRemove_Check()

void RI_PartitionRemove_Check ( Trigger trigger,
Relation  fk_rel,
Relation  pk_rel 
)

Definition at line 1660 of file ri_triggers.c.

1661 {
1662  const RI_ConstraintInfo *riinfo;
1663  StringInfoData querybuf;
1664  char *constraintDef;
1665  char pkrelname[MAX_QUOTED_REL_NAME_LEN];
1666  char fkrelname[MAX_QUOTED_REL_NAME_LEN];
1667  char pkattname[MAX_QUOTED_NAME_LEN + 3];
1668  char fkattname[MAX_QUOTED_NAME_LEN + 3];
1669  const char *sep;
1670  const char *fk_only;
1671  int save_nestlevel;
1672  char workmembuf[32];
1673  int spi_result;
1674  SPIPlanPtr qplan;
1675  int i;
1676 
1677  riinfo = ri_FetchConstraintInfo(trigger, fk_rel, false);
1678 
1679  /*
1680  * We don't check permissions before displaying the error message, on the
1681  * assumption that the user detaching the partition must have enough
1682  * privileges to examine the table contents anyhow.
1683  */
1684 
1685  /*----------
1686  * The query string built is:
1687  * SELECT fk.keycols FROM [ONLY] relname fk
1688  * JOIN pkrelname pk
1689  * ON (pk.pkkeycol1=fk.keycol1 [AND ...])
1690  * WHERE (<partition constraint>) AND
1691  * For MATCH SIMPLE:
1692  * (fk.keycol1 IS NOT NULL [AND ...])
1693  * For MATCH FULL:
1694  * (fk.keycol1 IS NOT NULL [OR ...])
1695  *
1696  * We attach COLLATE clauses to the operators when comparing columns
1697  * that have different collations.
1698  *----------
1699  */
1700  initStringInfo(&querybuf);
1701  appendStringInfoString(&querybuf, "SELECT ");
1702  sep = "";
1703  for (i = 0; i < riinfo->nkeys; i++)
1704  {
1705  quoteOneName(fkattname,
1706  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1707  appendStringInfo(&querybuf, "%sfk.%s", sep, fkattname);
1708  sep = ", ";
1709  }
1710 
1711  quoteRelationName(pkrelname, pk_rel);
1712  quoteRelationName(fkrelname, fk_rel);
1713  fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
1714  "" : "ONLY ";
1715  appendStringInfo(&querybuf,
1716  " FROM %s%s fk JOIN %s pk ON",
1717  fk_only, fkrelname, pkrelname);
1718  strcpy(pkattname, "pk.");
1719  strcpy(fkattname, "fk.");
1720  sep = "(";
1721  for (i = 0; i < riinfo->nkeys; i++)
1722  {
1723  Oid pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
1724  Oid fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
1725  Oid pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
1726  Oid fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
1727 
1728  quoteOneName(pkattname + 3,
1729  RIAttName(pk_rel, riinfo->pk_attnums[i]));
1730  quoteOneName(fkattname + 3,
1731  RIAttName(fk_rel, riinfo->fk_attnums[i]));
1732  ri_GenerateQual(&querybuf, sep,
1733  pkattname, pk_type,
1734  riinfo->pf_eq_oprs[i],
1735  fkattname, fk_type);
1736  if (pk_coll != fk_coll)
1737  ri_GenerateQualCollation(&querybuf, pk_coll);
1738  sep = "AND";
1739  }
1740 
1741  /*
1742  * Start the WHERE clause with the partition constraint (except if this is
1743  * the default partition and there's no other partition, because the
1744  * partition constraint is the empty string in that case.)
1745  */
1746  constraintDef = pg_get_partconstrdef_string(RelationGetRelid(pk_rel), "pk");
1747  if (constraintDef && constraintDef[0] != '\0')
1748  appendStringInfo(&querybuf, ") WHERE %s AND (",
1749  constraintDef);
1750  else
1751  appendStringInfoString(&querybuf, ") WHERE (");
1752 
1753  sep = "";
1754  for (i = 0; i < riinfo->nkeys; i++)
1755  {
1756  quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
1757  appendStringInfo(&querybuf,
1758  "%sfk.%s IS NOT NULL",
1759  sep, fkattname);
1760  switch (riinfo->confmatchtype)
1761  {
1762  case FKCONSTR_MATCH_SIMPLE:
1763  sep = " AND ";
1764  break;
1765  case FKCONSTR_MATCH_FULL:
1766  sep = " OR ";
1767  break;
1768  }
1769  }
1770  appendStringInfoChar(&querybuf, ')');
1771 
1772  /*
1773  * Temporarily increase work_mem so that the check query can be executed
1774  * more efficiently. It seems okay to do this because the query is simple
1775  * enough to not use a multiple of work_mem, and one typically would not
1776  * have many large foreign-key validations happening concurrently. So
1777  * this seems to meet the criteria for being considered a "maintenance"
1778  * operation, and accordingly we use maintenance_work_mem. However, we
1779  * must also set hash_mem_multiplier to 1, since it is surely not okay to
1780  * let that get applied to the maintenance_work_mem value.
1781  *
1782  * We use the equivalent of a function SET option to allow the setting to
1783  * persist for exactly the duration of the check query. guc.c also takes
1784  * care of undoing the setting on error.
1785  */
1786  save_nestlevel = NewGUCNestLevel();
1787 
1788  snprintf(workmembuf, sizeof(workmembuf), "%d", maintenance_work_mem);
1789  (void) set_config_option("work_mem", workmembuf,
1791  GUC_ACTION_SAVE, true, 0, false);
1792  (void) set_config_option("hash_mem_multiplier", "1",
1794  GUC_ACTION_SAVE, true, 0, false);
1795 
1796  if (SPI_connect() != SPI_OK_CONNECT)
1797  elog(ERROR, "SPI_connect failed");
1798 
1799  /*
1800  * Generate the plan. We don't need to cache it, and there are no
1801  * arguments to the plan.
1802  */
1803  qplan = SPI_prepare(querybuf.data, 0, NULL);
1804 
1805  if (qplan == NULL)
1806  elog(ERROR, "SPI_prepare returned %s for %s",
1808 
1809  /*
1810  * Run the plan. For safety we force a current snapshot to be used. (In
1811  * transaction-snapshot mode, this arguably violates transaction isolation
1812  * rules, but we really haven't got much choice.) We don't need to
1813  * register the snapshot, because SPI_execute_snapshot will see to it. We
1814  * need at most one tuple returned, so pass limit = 1.
1815  */
1816  spi_result = SPI_execute_snapshot(qplan,
1817  NULL, NULL,
1820  true, false, 1);
1821 
1822  /* Check result */
1823  if (spi_result != SPI_OK_SELECT)
1824  elog(ERROR, "SPI_execute_snapshot returned %s", SPI_result_code_string(spi_result));
1825 
1826  /* Did we find a tuple that would violate the constraint? */
1827  if (SPI_processed > 0)
1828  {
1829  TupleTableSlot *slot;
1830  HeapTuple tuple = SPI_tuptable->vals[0];
1831  TupleDesc tupdesc = SPI_tuptable->tupdesc;
1832  RI_ConstraintInfo fake_riinfo;
1833 
1834  slot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
1835 
1836  heap_deform_tuple(tuple, tupdesc,
1837  slot->tts_values, slot->tts_isnull);
1838  ExecStoreVirtualTuple(slot);
1839 
1840  /*
1841  * The columns to look at in the result tuple are 1..N, not whatever
1842  * they are in the fk_rel. Hack up riinfo so that ri_ReportViolation
1843  * will behave properly.
1844  *
1845  * In addition to this, we have to pass the correct tupdesc to
1846  * ri_ReportViolation, overriding its normal habit of using the pk_rel
1847  * or fk_rel's tupdesc.
1848  */
1849  memcpy(&fake_riinfo, riinfo, sizeof(RI_ConstraintInfo));
1850  for (i = 0; i < fake_riinfo.nkeys; i++)
1851  fake_riinfo.pk_attnums[i] = i + 1;
1852 
1853  ri_ReportViolation(&fake_riinfo, pk_rel, fk_rel,
1854  slot, tupdesc, 0, true);
1855  }
1856 
1857  if (SPI_finish() != SPI_OK_FINISH)
1858  elog(ERROR, "SPI_finish failed");
1859 
1860  /*
1861  * Restore work_mem and hash_mem_multiplier.
1862  */
1863  AtEOXact_GUC(true, save_nestlevel);
1864 }
char * pg_get_partconstrdef_string(Oid partitionId, char *aliasname)
Definition: ruleutils.c:2097

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AtEOXact_GUC(), RI_ConstraintInfo::confmatchtype, StringInfoData::data, elog, ERROR, ExecStoreVirtualTuple(), RI_ConstraintInfo::fk_attnums, FKCONSTR_MATCH_FULL, FKCONSTR_MATCH_SIMPLE, GetLatestSnapshot(), GUC_ACTION_SAVE, heap_deform_tuple(), i, initStringInfo(), InvalidSnapshot, maintenance_work_mem, MakeSingleTupleTableSlot(), MAX_QUOTED_NAME_LEN, MAX_QUOTED_REL_NAME_LEN, NewGUCNestLevel(), RI_ConstraintInfo::nkeys, RI_ConstraintInfo::pf_eq_oprs, pg_get_partconstrdef_string(), PGC_S_SESSION, PGC_USERSET, RI_ConstraintInfo::pk_attnums, quoteOneName(), quoteRelationName(), RelationData::rd_rel, RelationGetRelid, ri_FetchConstraintInfo(), ri_GenerateQual(), ri_GenerateQualCollation(), ri_ReportViolation(), RIAttCollation, RIAttName, RIAttType, set_config_option(), snprintf, SPI_connect(), SPI_execute_snapshot(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SPI_OK_SELECT, SPI_prepare(), SPI_processed, SPI_result, SPI_result_code_string(), SPI_tuptable, TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, TTSOpsVirtual, SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by ATDetachCheckNoForeignKeyRefs().

◆ TriggerSetParentTrigger()

void TriggerSetParentTrigger ( Relation  trigRel,
Oid  childTrigId,
Oid  parentTrigId,
Oid  childTableId 
)

Definition at line 1216 of file trigger.c.

1220 {
1221  SysScanDesc tgscan;
1222  ScanKeyData skey[1];
1223  Form_pg_trigger trigForm;
1224  HeapTuple tuple,
1225  newtup;
1226  ObjectAddress depender;
1227  ObjectAddress referenced;
1228 
1229  /*
1230  * Find the trigger to delete.
1231  */
1232  ScanKeyInit(&skey[0],
1233  Anum_pg_trigger_oid,
1234  BTEqualStrategyNumber, F_OIDEQ,
1235  ObjectIdGetDatum(childTrigId));
1236 
1237  tgscan = systable_beginscan(trigRel, TriggerOidIndexId, true,
1238  NULL, 1, skey);
1239 
1240  tuple = systable_getnext(tgscan);
1241  if (!HeapTupleIsValid(tuple))
1242  elog(ERROR, "could not find tuple for trigger %u", childTrigId);
1243  newtup = heap_copytuple(tuple);
1244  trigForm = (Form_pg_trigger) GETSTRUCT(newtup);
1245  if (OidIsValid(parentTrigId))
1246  {
1247  /* don't allow setting parent for a constraint that already has one */
1248  if (OidIsValid(trigForm->tgparentid))
1249  elog(ERROR, "trigger %u already has a parent trigger",
1250  childTrigId);
1251 
1252  trigForm->tgparentid = parentTrigId;
1253 
1254  CatalogTupleUpdate(trigRel, &tuple->t_self, newtup);
1255 
1256  ObjectAddressSet(depender, TriggerRelationId, childTrigId);
1257 
1258  ObjectAddressSet(referenced, TriggerRelationId, parentTrigId);
1259  recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_PRI);
1260 
1261  ObjectAddressSet(referenced, RelationRelationId, childTableId);
1262  recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_SEC);
1263  }
1264  else
1265  {
1266  trigForm->tgparentid = InvalidOid;
1267 
1268  CatalogTupleUpdate(trigRel, &tuple->t_self, newtup);
1269 
1270  deleteDependencyRecordsForClass(TriggerRelationId, childTrigId,
1271  TriggerRelationId,
1273  deleteDependencyRecordsForClass(TriggerRelationId, childTrigId,
1274  RelationRelationId,
1276  }
1277 
1278  heap_freetuple(newtup);
1279  systable_endscan(tgscan);
1280 }
long deleteDependencyRecordsForClass(Oid classId, Oid objectId, Oid refclassId, char deptype)
Definition: pg_depend.c:350

References BTEqualStrategyNumber, CatalogTupleUpdate(), deleteDependencyRecordsForClass(), DEPENDENCY_PARTITION_PRI, DEPENDENCY_PARTITION_SEC, elog, ERROR, GETSTRUCT, heap_copytuple(), heap_freetuple(), HeapTupleIsValid, InvalidOid, ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, recordDependencyOn(), ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), and HeapTupleData::t_self.

Referenced by DetachPartitionFinalize(), and tryAttachPartitionForeignKey().

Variable Documentation

◆ SessionReplicationRole

PGDLLIMPORT int SessionReplicationRole
extern