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)
 
void RemoveTriggerById (Oid trigOid)
 
Oid get_trigger_oid (Oid relid, const char *name, bool missing_ok)
 
ObjectAddress renametrig (RenameStmt *stmt)
 
void EnableDisableTrigger (Relation rel, const char *tgname, char fires_when, bool skip_system, LOCKMODE lockmode)
 
void RelationBuildTriggers (Relation relation)
 
TriggerDescCopyTriggerDesc (TriggerDesc *trigdesc)
 
const char * FindTriggerIncompatibleWithInheritance (TriggerDesc *trigdesc)
 
TransitionCaptureStateMakeTransitionCaptureState (TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
 
void FreeTriggerDesc (TriggerDesc *trigdesc)
 
void ExecBSInsertTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASInsertTriggers (EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
 
bool ExecBRInsertTriggers (EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
 
void ExecARInsertTriggers (EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
 
bool ExecIRInsertTriggers (EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
 
void ExecBSDeleteTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASDeleteTriggers (EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
 
bool ExecBRDeleteTriggers (EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot **epqslot)
 
void ExecARDeleteTriggers (EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TransitionCaptureState *transition_capture)
 
bool ExecIRDeleteTriggers (EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple)
 
void ExecBSUpdateTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASUpdateTriggers (EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
 
bool ExecBRUpdateTriggers (EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *slot)
 
void ExecARUpdateTriggers (EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
 
bool ExecIRUpdateTriggers (EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, TupleTableSlot *slot)
 
void ExecBSTruncateTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASTruncateTriggers (EState *estate, ResultRelInfo *relinfo)
 
void AfterTriggerBeginXact (void)
 
void AfterTriggerBeginQuery (void)
 
void AfterTriggerEndQuery (EState *estate)
 
void AfterTriggerFireDeferred (void)
 
void AfterTriggerEndXact (bool isCommit)
 
void AfterTriggerBeginSubXact (void)
 
void AfterTriggerEndSubXact (bool isCommit)
 
void AfterTriggerSetState (ConstraintsSetStmt *stmt)
 
bool AfterTriggerPendingOnRel (Oid relid)
 
bool RI_FKey_pk_upd_check_required (Trigger *trigger, Relation pk_rel, TupleTableSlot *old_slot, TupleTableSlot *new_slot)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, TupleTableSlot *old_slot, TupleTableSlot *new_slot)
 
bool RI_Initial_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
void RI_PartitionRemove_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
int RI_FKey_trigger_type (Oid tgfoid)
 

Variables

PGDLLIMPORT int SessionReplicationRole
 

Macro Definition Documentation

◆ AFTER_TRIGGER_DEFERRABLE

#define AFTER_TRIGGER_DEFERRABLE   0x00000020

Definition at line 114 of file trigger.h.

Referenced by afterTriggerCheckState(), AfterTriggerSaveEvent(), and ExecCallTriggerFunc().

◆ AFTER_TRIGGER_INITDEFERRED

#define AFTER_TRIGGER_INITDEFERRED   0x00000040

Definition at line 115 of file trigger.h.

Referenced by afterTriggerCheckState(), AfterTriggerSaveEvent(), and ExecCallTriggerFunc().

◆ CALLED_AS_TRIGGER

◆ RI_TRIGGER_FK

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

Definition at line 272 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), and RI_FKey_trigger_type().

◆ RI_TRIGGER_NONE

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

Definition at line 273 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), and RI_FKey_trigger_type().

◆ RI_TRIGGER_PK

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

Definition at line 271 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), and RI_FKey_trigger_type().

◆ SESSION_REPLICATION_ROLE_LOCAL

#define SESSION_REPLICATION_ROLE_LOCAL   2

Definition at line 149 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_ORIGIN

#define SESSION_REPLICATION_ROLE_ORIGIN   0

Definition at line 147 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_REPLICA

#define SESSION_REPLICATION_ROLE_REPLICA   1

Definition at line 148 of file trigger.h.

Referenced by filter_event_trigger(), matchLocks(), and TriggerEnabled().

◆ TRIGGER_DISABLED

#define TRIGGER_DISABLED   'D'

Definition at line 159 of file trigger.h.

Referenced by ATExecCmd(), BuildEventTriggerCache(), and TriggerEnabled().

◆ TRIGGER_EVENT_AFTER

#define TRIGGER_EVENT_AFTER   0x00000000

Definition at line 108 of file trigger.h.

◆ TRIGGER_EVENT_BEFORE

◆ TRIGGER_EVENT_DELETE

#define TRIGGER_EVENT_DELETE   0x00000001

◆ TRIGGER_EVENT_INSERT

◆ TRIGGER_EVENT_INSTEAD

#define TRIGGER_EVENT_INSTEAD   0x00000010

Definition at line 109 of file trigger.h.

Referenced by ExecIRDeleteTriggers(), ExecIRInsertTriggers(), and ExecIRUpdateTriggers().

◆ TRIGGER_EVENT_OPMASK

#define TRIGGER_EVENT_OPMASK   0x00000003

◆ TRIGGER_EVENT_ROW

◆ TRIGGER_EVENT_TIMINGMASK

#define TRIGGER_EVENT_TIMINGMASK   0x00000018

Definition at line 110 of file trigger.h.

◆ TRIGGER_EVENT_TRUNCATE

#define TRIGGER_EVENT_TRUNCATE   0x00000003

◆ TRIGGER_EVENT_UPDATE

◆ TRIGGER_FIRED_AFTER

◆ TRIGGER_FIRED_BEFORE

◆ TRIGGER_FIRED_BY_DELETE

◆ TRIGGER_FIRED_BY_INSERT

◆ TRIGGER_FIRED_BY_TRUNCATE

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

◆ TRIGGER_FIRED_BY_UPDATE

◆ TRIGGER_FIRED_FOR_ROW

◆ TRIGGER_FIRED_FOR_STATEMENT

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

◆ TRIGGER_FIRED_INSTEAD

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

◆ TRIGGER_FIRES_ALWAYS

#define TRIGGER_FIRES_ALWAYS   'A'

Definition at line 157 of file trigger.h.

Referenced by ATExecCmd().

◆ TRIGGER_FIRES_ON_ORIGIN

◆ TRIGGER_FIRES_ON_REPLICA

#define TRIGGER_FIRES_ON_REPLICA   'R'

Definition at line 158 of file trigger.h.

Referenced by ATExecCmd(), filter_event_trigger(), and TriggerEnabled().

Typedef Documentation

◆ TransitionCaptureState

◆ TriggerData

typedef struct TriggerData TriggerData

◆ TriggerEvent

Definition at line 28 of file trigger.h.

Function Documentation

◆ AfterTriggerBeginQuery()

void AfterTriggerBeginQuery ( void  )

Definition at line 4432 of file trigger.c.

References AfterTriggersData::query_depth.

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

4433 {
4434  /* Increase the query stack depth */
4436 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3483

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 4700 of file trigger.c.

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

4701 {
4702  int my_level = GetCurrentTransactionNestLevel();
4703 
4704  /*
4705  * Allocate more space in the trans_stack if needed. (Note: because the
4706  * minimum nest level of a subtransaction is 2, we waste the first couple
4707  * entries of the array; not worth the notational effort to avoid it.)
4708  */
4709  while (my_level >= afterTriggers.maxtransdepth)
4710  {
4711  if (afterTriggers.maxtransdepth == 0)
4712  {
4713  /* Arbitrarily initialize for max of 8 subtransaction levels */
4716  8 * sizeof(AfterTriggersTransData));
4718  }
4719  else
4720  {
4721  /* repalloc will keep the stack in the same context */
4722  int new_alloc = afterTriggers.maxtransdepth * 2;
4723 
4726  new_alloc * sizeof(AfterTriggersTransData));
4727  afterTriggers.maxtransdepth = new_alloc;
4728  }
4729  }
4730 
4731  /*
4732  * Push the current information into the stack. The SET CONSTRAINTS state
4733  * is not saved until/unless changed. Likewise, we don't make a
4734  * per-subtransaction event context until needed.
4735  */
4736  afterTriggers.trans_stack[my_level].state = NULL;
4740 }
AfterTriggersTransData * trans_stack
Definition: trigger.c:3449
MemoryContext TopTransactionContext
Definition: mcxt.c:49
AfterTriggerEventList events
Definition: trigger.c:3464
CommandId firing_counter
Definition: trigger.c:3466
CommandId firing_counter
Definition: trigger.c:3438
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
AfterTriggerEventList events
Definition: trigger.c:3440
static AfterTriggersData afterTriggers
Definition: trigger.c:3483
SetConstraintState state
Definition: trigger.c:3463

◆ AfterTriggerBeginXact()

void AfterTriggerBeginXact ( void  )

Definition at line 4400 of file trigger.c.

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

4401 {
4402  /*
4403  * Initialize after-trigger state structure to empty
4404  */
4405  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4407 
4408  /*
4409  * Verify that there is no leftover state remaining. If these assertions
4410  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4411  * up properly.
4412  */
4413  Assert(afterTriggers.state == NULL);
4414  Assert(afterTriggers.query_stack == NULL);
4416  Assert(afterTriggers.event_cxt == NULL);
4417  Assert(afterTriggers.events.head == NULL);
4418  Assert(afterTriggers.trans_stack == NULL);
4420 }
uint32 CommandId
Definition: c.h:534
AfterTriggersTransData * trans_stack
Definition: trigger.c:3449
AfterTriggersQueryData * query_stack
Definition: trigger.c:3444
SetConstraintState state
Definition: trigger.c:3439
CommandId firing_counter
Definition: trigger.c:3438
#define Assert(condition)
Definition: c.h:745
AfterTriggerEventChunk * head
Definition: trigger.c:3332
MemoryContext event_cxt
Definition: trigger.c:3441
AfterTriggerEventList events
Definition: trigger.c:3440
static AfterTriggersData afterTriggers
Definition: trigger.c:3483

◆ AfterTriggerEndQuery()

void AfterTriggerEndQuery ( EState estate)

Definition at line 4452 of file trigger.c.

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

Referenced by apply_handle_delete(), apply_handle_insert(), apply_handle_update(), CopyFrom(), ExecuteTruncateGuts(), and standard_ExecutorFinish().

4453 {
4455 
4456  /* Must be inside a query, too */
4458 
4459  /*
4460  * If we never even got as far as initializing the event stack, there
4461  * certainly won't be any events, so exit quickly.
4462  */
4464  {
4466  return;
4467  }
4468 
4469  /*
4470  * Process all immediate-mode triggers queued by the query, and move the
4471  * deferred ones to the main list of deferred events.
4472  *
4473  * Notice that we decide which ones will be fired, and put the deferred
4474  * ones on the main list, before anything is actually fired. This ensures
4475  * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
4476  * IMMEDIATE: all events we have decided to defer will be available for it
4477  * to fire.
4478  *
4479  * We loop in case a trigger queues more events at the same query level.
4480  * Ordinary trigger functions, including all PL/pgSQL trigger functions,
4481  * will instead fire any triggers in a dedicated query level. Foreign key
4482  * enforcement triggers do add to the current query level, thanks to their
4483  * passing fire_triggers = false to SPI_execute_snapshot(). Other
4484  * C-language triggers might do likewise.
4485  *
4486  * If we find no firable events, we don't have to increment
4487  * firing_counter.
4488  */
4490 
4491  for (;;)
4492  {
4494  {
4495  CommandId firing_id = afterTriggers.firing_counter++;
4496  AfterTriggerEventChunk *oldtail = qs->events.tail;
4497 
4498  if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
4499  break; /* all fired */
4500 
4501  /*
4502  * Firing a trigger could result in query_stack being repalloc'd,
4503  * so we must recalculate qs after each afterTriggerInvokeEvents
4504  * call. Furthermore, it's unsafe to pass delete_ok = true here,
4505  * because that could cause afterTriggerInvokeEvents to try to
4506  * access qs->events after the stack has been repalloc'd.
4507  */
4509 
4510  /*
4511  * We'll need to scan the events list again. To reduce the cost
4512  * of doing so, get rid of completely-fired chunks. We know that
4513  * all events were marked IN_PROGRESS or DONE at the conclusion of
4514  * afterTriggerMarkEvents, so any still-interesting events must
4515  * have been added after that, and so must be in the chunk that
4516  * was then the tail chunk, or in later chunks. So, zap all
4517  * chunks before oldtail. This is approximately the same set of
4518  * events we would have gotten rid of by passing delete_ok = true.
4519  */
4520  Assert(oldtail != NULL);
4521  while (qs->events.head != oldtail)
4523  }
4524  else
4525  break;
4526  }
4527 
4528  /* Release query-level-local storage, including tuplestores if any */
4530 
4532 }
uint32 CommandId
Definition: c.h:534
static void afterTriggerDeleteHeadEventChunk(AfterTriggersQueryData *qs)
Definition: trigger.c:3768
AfterTriggersQueryData * query_stack
Definition: trigger.c:3444
AfterTriggerEventChunk * tail
Definition: trigger.c:3333
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4108
CommandId firing_counter
Definition: trigger.c:3438
#define Assert(condition)
Definition: c.h:745
AfterTriggerEventChunk * head
Definition: trigger.c:3332
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4036
AfterTriggerEventList events
Definition: trigger.c:3440
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:4543
AfterTriggerEventList events
Definition: trigger.c:3455
static AfterTriggersData afterTriggers
Definition: trigger.c:3483

◆ AfterTriggerEndSubXact()

void AfterTriggerEndSubXact ( bool  isCommit)

Definition at line 4748 of file trigger.c.

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

4749 {
4750  int my_level = GetCurrentTransactionNestLevel();
4752  AfterTriggerEvent event;
4753  AfterTriggerEventChunk *chunk;
4754  CommandId subxact_firing_id;
4755 
4756  /*
4757  * Pop the prior state if needed.
4758  */
4759  if (isCommit)
4760  {
4761  Assert(my_level < afterTriggers.maxtransdepth);
4762  /* If we saved a prior state, we don't need it anymore */
4763  state = afterTriggers.trans_stack[my_level].state;
4764  if (state != NULL)
4765  pfree(state);
4766  /* this avoids double pfree if error later: */
4767  afterTriggers.trans_stack[my_level].state = NULL;
4770  }
4771  else
4772  {
4773  /*
4774  * Aborting. It is possible subxact start failed before calling
4775  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
4776  * trans_stack levels that aren't there.
4777  */
4778  if (my_level >= afterTriggers.maxtransdepth)
4779  return;
4780 
4781  /*
4782  * Release query-level storage for queries being aborted, and restore
4783  * query_depth to its pre-subxact value. This assumes that a
4784  * subtransaction will not add events to query levels started in a
4785  * earlier transaction state.
4786  */
4788  {
4792  }
4795 
4796  /*
4797  * Restore the global deferred-event list to its former length,
4798  * discarding any events queued by the subxact.
4799  */
4801  &afterTriggers.trans_stack[my_level].events);
4802 
4803  /*
4804  * Restore the trigger state. If the saved state is NULL, then this
4805  * subxact didn't save it, so it doesn't need restoring.
4806  */
4807  state = afterTriggers.trans_stack[my_level].state;
4808  if (state != NULL)
4809  {
4811  afterTriggers.state = state;
4812  }
4813  /* this avoids double pfree if error later: */
4814  afterTriggers.trans_stack[my_level].state = NULL;
4815 
4816  /*
4817  * Scan for any remaining deferred events that were marked DONE or IN
4818  * PROGRESS by this subxact or a child, and un-mark them. We can
4819  * recognize such events because they have a firing ID greater than or
4820  * equal to the firing_counter value we saved at subtransaction start.
4821  * (This essentially assumes that the current subxact includes all
4822  * subxacts started after it.)
4823  */
4824  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
4826  {
4827  AfterTriggerShared evtshared = GetTriggerSharedData(event);
4828 
4829  if (event->ate_flags &
4831  {
4832  if (evtshared->ats_firing_id >= subxact_firing_id)
4833  event->ate_flags &=
4835  }
4836  }
4837  }
4838 }
uint32 CommandId
Definition: c.h:534
AfterTriggersTransData * trans_stack
Definition: trigger.c:3449
TriggerFlags ate_flags
Definition: trigger.c:3283
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3258
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3345
AfterTriggerEventList events
Definition: trigger.c:3464
AfterTriggersQueryData * query_stack
Definition: trigger.c:3444
CommandId firing_counter
Definition: trigger.c:3466
#define GetTriggerSharedData(evt)
Definition: trigger.c:3308
void pfree(void *pointer)
Definition: mcxt.c:1056
SetConstraintState state
Definition: trigger.c:3439
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
#define Assert(condition)
Definition: c.h:745
Definition: regguts.h:298
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:3728
CommandId ats_firing_id
Definition: trigger.c:3274
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3259
AfterTriggerEventList events
Definition: trigger.c:3440
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:4543
static AfterTriggersData afterTriggers
Definition: trigger.c:3483
SetConstraintState state
Definition: trigger.c:3463

◆ AfterTriggerEndXact()

void AfterTriggerEndXact ( bool  isCommit)

Definition at line 4652 of file trigger.c.

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

4653 {
4654  /*
4655  * Forget the pending-events list.
4656  *
4657  * Since all the info is in TopTransactionContext or children thereof, we
4658  * don't really need to do anything to reclaim memory. However, the
4659  * pending-events list could be large, and so it's useful to discard it as
4660  * soon as possible --- especially if we are aborting because we ran out
4661  * of memory for the list!
4662  */
4664  {
4666  afterTriggers.event_cxt = NULL;
4667  afterTriggers.events.head = NULL;
4668  afterTriggers.events.tail = NULL;
4669  afterTriggers.events.tailfree = NULL;
4670  }
4671 
4672  /*
4673  * Forget any subtransaction state as well. Since this can't be very
4674  * large, we let the eventual reset of TopTransactionContext free the
4675  * memory instead of doing it here.
4676  */
4677  afterTriggers.trans_stack = NULL;
4679 
4680 
4681  /*
4682  * Forget the query stack and constraint-related state information. As
4683  * with the subtransaction state information, we don't bother freeing the
4684  * memory here.
4685  */
4686  afterTriggers.query_stack = NULL;
4688  afterTriggers.state = NULL;
4689 
4690  /* No more afterTriggers manipulation until next transaction starts. */
4692 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
AfterTriggersTransData * trans_stack
Definition: trigger.c:3449
AfterTriggersQueryData * query_stack
Definition: trigger.c:3444
AfterTriggerEventChunk * tail
Definition: trigger.c:3333
SetConstraintState state
Definition: trigger.c:3439
AfterTriggerEventChunk * head
Definition: trigger.c:3332
MemoryContext event_cxt
Definition: trigger.c:3441
AfterTriggerEventList events
Definition: trigger.c:3440
static AfterTriggersData afterTriggers
Definition: trigger.c:3483

◆ AfterTriggerFireDeferred()

void AfterTriggerFireDeferred ( void  )

Definition at line 4596 of file trigger.c.

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

Referenced by CommitTransaction(), and PrepareTransaction().

4597 {
4598  AfterTriggerEventList *events;
4599  bool snap_pushed = false;
4600 
4601  /* Must not be inside a query */
4603 
4604  /*
4605  * If there are any triggers to fire, make sure we have set a snapshot for
4606  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
4607  * can't assume ActiveSnapshot is valid on entry.)
4608  */
4609  events = &afterTriggers.events;
4610  if (events->head != NULL)
4611  {
4613  snap_pushed = true;
4614  }
4615 
4616  /*
4617  * Run all the remaining triggers. Loop until they are all gone, in case
4618  * some trigger queues more for us to do.
4619  */
4620  while (afterTriggerMarkEvents(events, NULL, false))
4621  {
4622  CommandId firing_id = afterTriggers.firing_counter++;
4623 
4624  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
4625  break; /* all fired */
4626  }
4627 
4628  /*
4629  * We don't bother freeing the event list, since it will go away anyway
4630  * (and more efficiently than via pfree) in AfterTriggerEndXact.
4631  */
4632 
4633  if (snap_pushed)
4635 }
uint32 CommandId
Definition: c.h:534
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4108
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
CommandId firing_counter
Definition: trigger.c:3438
#define Assert(condition)
Definition: c.h:745
AfterTriggerEventChunk * head
Definition: trigger.c:3332
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4036
AfterTriggerEventList events
Definition: trigger.c:3440
static AfterTriggersData afterTriggers
Definition: trigger.c:3483

◆ AfterTriggerPendingOnRel()

bool AfterTriggerPendingOnRel ( Oid  relid)

Definition at line 5287 of file trigger.c.

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

5288 {
5289  AfterTriggerEvent event;
5290  AfterTriggerEventChunk *chunk;
5291  int depth;
5292 
5293  /* Scan queued events */
5295  {
5296  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5297 
5298  /*
5299  * We can ignore completed events. (Even if a DONE flag is rolled
5300  * back by subxact abort, it's OK because the effects of the TRUNCATE
5301  * or whatever must get rolled back too.)
5302  */
5303  if (event->ate_flags & AFTER_TRIGGER_DONE)
5304  continue;
5305 
5306  if (evtshared->ats_relid == relid)
5307  return true;
5308  }
5309 
5310  /*
5311  * Also scan events queued by incomplete queries. This could only matter
5312  * if TRUNCATE/etc is executed by a function or trigger within an updating
5313  * query on the same relation, which is pretty perverse, but let's check.
5314  */
5315  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
5316  {
5318  {
5319  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5320 
5321  if (event->ate_flags & AFTER_TRIGGER_DONE)
5322  continue;
5323 
5324  if (evtshared->ats_relid == relid)
5325  return true;
5326  }
5327  }
5328 
5329  return false;
5330 }
TriggerFlags ate_flags
Definition: trigger.c:3283
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3258
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3345
AfterTriggersQueryData * query_stack
Definition: trigger.c:3444
#define GetTriggerSharedData(evt)
Definition: trigger.c:3308
AfterTriggerEventList events
Definition: trigger.c:3440
AfterTriggerEventList events
Definition: trigger.c:3455
static AfterTriggersData afterTriggers
Definition: trigger.c:3483

◆ AfterTriggerSetState()

void AfterTriggerSetState ( ConstraintsSetStmt stmt)

Definition at line 4972 of file trigger.c.

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

Referenced by standard_ProcessUtility().

4973 {
4974  int my_level = GetCurrentTransactionNestLevel();
4975 
4976  /* If we haven't already done so, initialize our state. */
4977  if (afterTriggers.state == NULL)
4979 
4980  /*
4981  * If in a subtransaction, and we didn't save the current state already,
4982  * save it so it can be restored if the subtransaction aborts.
4983  */
4984  if (my_level > 1 &&
4985  afterTriggers.trans_stack[my_level].state == NULL)
4986  {
4987  afterTriggers.trans_stack[my_level].state =
4989  }
4990 
4991  /*
4992  * Handle SET CONSTRAINTS ALL ...
4993  */
4994  if (stmt->constraints == NIL)
4995  {
4996  /*
4997  * Forget any previous SET CONSTRAINTS commands in this transaction.
4998  */
5000 
5001  /*
5002  * Set the per-transaction ALL state to known.
5003  */
5004  afterTriggers.state->all_isset = true;
5006  }
5007  else
5008  {
5009  Relation conrel;
5010  Relation tgrel;
5011  List *conoidlist = NIL;
5012  List *tgoidlist = NIL;
5013  ListCell *lc;
5014 
5015  /*
5016  * Handle SET CONSTRAINTS constraint-name [, ...]
5017  *
5018  * First, identify all the named constraints and make a list of their
5019  * OIDs. Since, unlike the SQL spec, we allow multiple constraints of
5020  * the same name within a schema, the specifications are not
5021  * necessarily unique. Our strategy is to target all matching
5022  * constraints within the first search-path schema that has any
5023  * matches, but disregard matches in schemas beyond the first match.
5024  * (This is a bit odd but it's the historical behavior.)
5025  *
5026  * A constraint in a partitioned table may have corresponding
5027  * constraints in the partitions. Grab those too.
5028  */
5029  conrel = table_open(ConstraintRelationId, AccessShareLock);
5030 
5031  foreach(lc, stmt->constraints)
5032  {
5033  RangeVar *constraint = lfirst(lc);
5034  bool found;
5035  List *namespacelist;
5036  ListCell *nslc;
5037 
5038  if (constraint->catalogname)
5039  {
5040  if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
5041  ereport(ERROR,
5042  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5043  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
5044  constraint->catalogname, constraint->schemaname,
5045  constraint->relname)));
5046  }
5047 
5048  /*
5049  * If we're given the schema name with the constraint, look only
5050  * in that schema. If given a bare constraint name, use the
5051  * search path to find the first matching constraint.
5052  */
5053  if (constraint->schemaname)
5054  {
5055  Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
5056  false);
5057 
5058  namespacelist = list_make1_oid(namespaceId);
5059  }
5060  else
5061  {
5062  namespacelist = fetch_search_path(true);
5063  }
5064 
5065  found = false;
5066  foreach(nslc, namespacelist)
5067  {
5068  Oid namespaceId = lfirst_oid(nslc);
5069  SysScanDesc conscan;
5070  ScanKeyData skey[2];
5071  HeapTuple tup;
5072 
5073  ScanKeyInit(&skey[0],
5074  Anum_pg_constraint_conname,
5075  BTEqualStrategyNumber, F_NAMEEQ,
5076  CStringGetDatum(constraint->relname));
5077  ScanKeyInit(&skey[1],
5078  Anum_pg_constraint_connamespace,
5079  BTEqualStrategyNumber, F_OIDEQ,
5080  ObjectIdGetDatum(namespaceId));
5081 
5082  conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
5083  true, NULL, 2, skey);
5084 
5085  while (HeapTupleIsValid(tup = systable_getnext(conscan)))
5086  {
5088 
5089  if (con->condeferrable)
5090  conoidlist = lappend_oid(conoidlist, con->oid);
5091  else if (stmt->deferred)
5092  ereport(ERROR,
5093  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5094  errmsg("constraint \"%s\" is not deferrable",
5095  constraint->relname)));
5096  found = true;
5097  }
5098 
5099  systable_endscan(conscan);
5100 
5101  /*
5102  * Once we've found a matching constraint we do not search
5103  * later parts of the search path.
5104  */
5105  if (found)
5106  break;
5107  }
5108 
5109  list_free(namespacelist);
5110 
5111  /*
5112  * Not found ?
5113  */
5114  if (!found)
5115  ereport(ERROR,
5116  (errcode(ERRCODE_UNDEFINED_OBJECT),
5117  errmsg("constraint \"%s\" does not exist",
5118  constraint->relname)));
5119  }
5120 
5121  /*
5122  * Scan for any possible descendants of the constraints. We append
5123  * whatever we find to the same list that we're scanning; this has the
5124  * effect that we create new scans for those, too, so if there are
5125  * further descendents, we'll also catch them.
5126  */
5127  foreach(lc, conoidlist)
5128  {
5129  Oid parent = lfirst_oid(lc);
5130  ScanKeyData key;
5131  SysScanDesc scan;
5132  HeapTuple tuple;
5133 
5134  ScanKeyInit(&key,
5135  Anum_pg_constraint_conparentid,
5136  BTEqualStrategyNumber, F_OIDEQ,
5137  ObjectIdGetDatum(parent));
5138 
5139  scan = systable_beginscan(conrel, ConstraintParentIndexId, true, NULL, 1, &key);
5140 
5141  while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5142  {
5144 
5145  conoidlist = lappend_oid(conoidlist, con->oid);
5146  }
5147 
5148  systable_endscan(scan);
5149  }
5150 
5151  table_close(conrel, AccessShareLock);
5152 
5153  /*
5154  * Now, locate the trigger(s) implementing each of these constraints,
5155  * and make a list of their OIDs.
5156  */
5157  tgrel = table_open(TriggerRelationId, AccessShareLock);
5158 
5159  foreach(lc, conoidlist)
5160  {
5161  Oid conoid = lfirst_oid(lc);
5162  ScanKeyData skey;
5163  SysScanDesc tgscan;
5164  HeapTuple htup;
5165 
5166  ScanKeyInit(&skey,
5167  Anum_pg_trigger_tgconstraint,
5168  BTEqualStrategyNumber, F_OIDEQ,
5169  ObjectIdGetDatum(conoid));
5170 
5171  tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
5172  NULL, 1, &skey);
5173 
5174  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
5175  {
5176  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
5177 
5178  /*
5179  * Silently skip triggers that are marked as non-deferrable in
5180  * pg_trigger. This is not an error condition, since a
5181  * deferrable RI constraint may have some non-deferrable
5182  * actions.
5183  */
5184  if (pg_trigger->tgdeferrable)
5185  tgoidlist = lappend_oid(tgoidlist, pg_trigger->oid);
5186  }
5187 
5188  systable_endscan(tgscan);
5189  }
5190 
5191  table_close(tgrel, AccessShareLock);
5192 
5193  /*
5194  * Now we can set the trigger states of individual triggers for this
5195  * xact.
5196  */
5197  foreach(lc, tgoidlist)
5198  {
5199  Oid tgoid = lfirst_oid(lc);
5201  bool found = false;
5202  int i;
5203 
5204  for (i = 0; i < state->numstates; i++)
5205  {
5206  if (state->trigstates[i].sct_tgoid == tgoid)
5207  {
5208  state->trigstates[i].sct_tgisdeferred = stmt->deferred;
5209  found = true;
5210  break;
5211  }
5212  }
5213  if (!found)
5214  {
5216  SetConstraintStateAddItem(state, tgoid, stmt->deferred);
5217  }
5218  }
5219  }
5220 
5221  /*
5222  * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
5223  * checks against that constraint must be made when the SET CONSTRAINTS
5224  * command is executed -- i.e. the effects of the SET CONSTRAINTS command
5225  * apply retroactively. We've updated the constraints state, so scan the
5226  * list of previously deferred events to fire any that have now become
5227  * immediate.
5228  *
5229  * Obviously, if this was SET ... DEFERRED then it can't have converted
5230  * any unfired events to immediate, so we need do nothing in that case.
5231  */
5232  if (!stmt->deferred)
5233  {
5235  bool snapshot_set = false;
5236 
5237  while (afterTriggerMarkEvents(events, NULL, true))
5238  {
5239  CommandId firing_id = afterTriggers.firing_counter++;
5240 
5241  /*
5242  * Make sure a snapshot has been established in case trigger
5243  * functions need one. Note that we avoid setting a snapshot if
5244  * we don't find at least one trigger that has to be fired now.
5245  * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
5246  * ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
5247  * at the start of a transaction it's not possible for any trigger
5248  * events to be queued yet.)
5249  */
5250  if (!snapshot_set)
5251  {
5253  snapshot_set = true;
5254  }
5255 
5256  /*
5257  * We can delete fired events if we are at top transaction level,
5258  * but we'd better not if inside a subtransaction, since the
5259  * subtransaction could later get rolled back.
5260  */
5261  if (afterTriggerInvokeEvents(events, firing_id, NULL,
5262  !IsSubTransaction()))
5263  break; /* all fired */
5264  }
5265 
5266  if (snapshot_set)
5268  }
5269 }
#define NIL
Definition: pg_list.h:65
uint32 CommandId
Definition: c.h:534
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2893
AfterTriggersTransData * trans_stack
Definition: trigger.c:3449
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:569
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
SetConstraintTriggerData trigstates[FLEXIBLE_ARRAY_MEMBER]
Definition: trigger.c:3212
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:610
static SetConstraintState SetConstraintStateAddItem(SetConstraintState state, Oid tgoid, bool tgisdeferred)
Definition: trigger.c:4942
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4108
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
char * schemaname
Definition: primnodes.h:67
char * relname
Definition: primnodes.h:68
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
SetConstraintState state
Definition: trigger.c:3439
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
#define CStringGetDatum(X)
Definition: postgres.h:578
#define TriggerConstraintIndexId
Definition: indexing.h:256
static SetConstraintState SetConstraintStateCreate(int numalloc)
Definition: trigger.c:4897
#define list_make1_oid(x1)
Definition: pg_list.h:249
Oid MyDatabaseId
Definition: globals.c:85
CommandId firing_counter
Definition: trigger.c:3438
#define ereport(elevel,...)
Definition: elog.h:144
#define ConstraintNameNspIndexId
Definition: indexing.h:131
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define lfirst(lc)
Definition: pg_list.h:190
Definition: regguts.h:298
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:73
bool IsSubTransaction(void)
Definition: xact.c:4757
int errmsg(const char *fmt,...)
Definition: elog.c:824
void list_free(List *list)
Definition: list.c:1376
int i
#define ConstraintParentIndexId
Definition: indexing.h:139
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4036
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
AfterTriggerEventList events
Definition: trigger.c:3440
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
List * fetch_search_path(bool includeImplicit)
Definition: namespace.c:4383
static AfterTriggersData afterTriggers
Definition: trigger.c:3483
char * catalogname
Definition: primnodes.h:66
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:192
SetConstraintState state
Definition: trigger.c:3463
static SetConstraintState SetConstraintStateCopy(SetConstraintState state)
Definition: trigger.c:4922

◆ CopyTriggerDesc()

TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 1821 of file trigger.c.

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

1822 {
1823  TriggerDesc *newdesc;
1824  Trigger *trigger;
1825  int i;
1826 
1827  if (trigdesc == NULL || trigdesc->numtriggers <= 0)
1828  return NULL;
1829 
1830  newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
1831  memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
1832 
1833  trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
1834  memcpy(trigger, trigdesc->triggers,
1835  trigdesc->numtriggers * sizeof(Trigger));
1836  newdesc->triggers = trigger;
1837 
1838  for (i = 0; i < trigdesc->numtriggers; i++)
1839  {
1840  trigger->tgname = pstrdup(trigger->tgname);
1841  if (trigger->tgnattr > 0)
1842  {
1843  int16 *newattr;
1844 
1845  newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
1846  memcpy(newattr, trigger->tgattr,
1847  trigger->tgnattr * sizeof(int16));
1848  trigger->tgattr = newattr;
1849  }
1850  if (trigger->tgnargs > 0)
1851  {
1852  char **newargs;
1853  int16 j;
1854 
1855  newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
1856  for (j = 0; j < trigger->tgnargs; j++)
1857  newargs[j] = pstrdup(trigger->tgargs[j]);
1858  trigger->tgargs = newargs;
1859  }
1860  if (trigger->tgqual)
1861  trigger->tgqual = pstrdup(trigger->tgqual);
1862  if (trigger->tgoldtable)
1863  trigger->tgoldtable = pstrdup(trigger->tgoldtable);
1864  if (trigger->tgnewtable)
1865  trigger->tgnewtable = pstrdup(trigger->tgnewtable);
1866  trigger++;
1867  }
1868 
1869  return newdesc;
1870 }
signed short int16
Definition: c.h:361
char * pstrdup(const char *in)
Definition: mcxt.c:1186
char * tgqual
Definition: reltrigger.h:42
char * tgname
Definition: reltrigger.h:27
Trigger * triggers
Definition: reltrigger.h:49
int numtriggers
Definition: reltrigger.h:50
char ** tgargs
Definition: reltrigger.h:41
int16 * tgattr
Definition: reltrigger.h:40
char * tgnewtable
Definition: reltrigger.h:44
int16 tgnattr
Definition: reltrigger.h:39
void * palloc(Size size)
Definition: mcxt.c:949
int i
int16 tgnargs
Definition: reltrigger.h:38
char * tgoldtable
Definition: reltrigger.h:43

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

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

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

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

◆ EnableDisableTrigger()

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

Definition at line 1469 of file trigger.c.

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

Referenced by ATExecEnableDisableTrigger(), and EnableDisableTrigger().

1471 {
1472  Relation tgrel;
1473  int nkeys;
1474  ScanKeyData keys[2];
1475  SysScanDesc tgscan;
1476  HeapTuple tuple;
1477  bool found;
1478  bool changed;
1479 
1480  /* Scan the relevant entries in pg_triggers */
1481  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1482 
1483  ScanKeyInit(&keys[0],
1484  Anum_pg_trigger_tgrelid,
1485  BTEqualStrategyNumber, F_OIDEQ,
1487  if (tgname)
1488  {
1489  ScanKeyInit(&keys[1],
1490  Anum_pg_trigger_tgname,
1491  BTEqualStrategyNumber, F_NAMEEQ,
1492  CStringGetDatum(tgname));
1493  nkeys = 2;
1494  }
1495  else
1496  nkeys = 1;
1497 
1498  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1499  NULL, nkeys, keys);
1500 
1501  found = changed = false;
1502 
1503  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1504  {
1505  Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1506 
1507  if (oldtrig->tgisinternal)
1508  {
1509  /* system trigger ... ok to process? */
1510  if (skip_system)
1511  continue;
1512  if (!superuser())
1513  ereport(ERROR,
1514  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1515  errmsg("permission denied: \"%s\" is a system trigger",
1516  NameStr(oldtrig->tgname))));
1517  }
1518 
1519  found = true;
1520 
1521  if (oldtrig->tgenabled != fires_when)
1522  {
1523  /* need to change this one ... make a copy to scribble on */
1524  HeapTuple newtup = heap_copytuple(tuple);
1525  Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1526 
1527  newtrig->tgenabled = fires_when;
1528 
1529  CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1530 
1531  heap_freetuple(newtup);
1532 
1533  /*
1534  * When altering FOR EACH ROW triggers on a partitioned table, do
1535  * the same on the partitions as well.
1536  */
1537  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
1538  (TRIGGER_FOR_ROW(oldtrig->tgtype)))
1539  {
1540  PartitionDesc partdesc = RelationGetPartitionDesc(rel);
1541  int i;
1542 
1543  for (i = 0; i < partdesc->nparts; i++)
1544  {
1545  Relation part;
1546 
1547  part = relation_open(partdesc->oids[i], lockmode);
1548  EnableDisableTrigger(part, NameStr(oldtrig->tgname),
1549  fires_when, skip_system, lockmode);
1550  table_close(part, NoLock); /* keep lock till commit */
1551  }
1552  }
1553 
1554  changed = true;
1555  }
1556 
1557  InvokeObjectPostAlterHook(TriggerRelationId,
1558  oldtrig->oid, 0);
1559  }
1560 
1561  systable_endscan(tgscan);
1562 
1563  table_close(tgrel, RowExclusiveLock);
1564 
1565  if (tgname && !found)
1566  ereport(ERROR,
1567  (errcode(ERRCODE_UNDEFINED_OBJECT),
1568  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1569  tgname, RelationGetRelationName(rel))));
1570 
1571  /*
1572  * If we changed anything, broadcast a SI inval message to force each
1573  * backend (including our own!) to rebuild relation's relcache entry.
1574  * Otherwise they will fail to apply the change promptly.
1575  */
1576  if (changed)
1578 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:569
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
Form_pg_class rd_rel
Definition: rel.h:109
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
#define TriggerRelidNameIndexId
Definition: indexing.h:258
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
ItemPointerData t_self
Definition: htup.h:65
void EnableDisableTrigger(Relation rel, const char *tgname, char fires_when, bool skip_system, LOCKMODE lockmode)
Definition: trigger.c:1469
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
PartitionDesc RelationGetPartitionDesc(Relation rel)
Definition: partdesc.c:65
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:73
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1278
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i
#define NameStr(name)
Definition: c.h:622
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define RelationGetRelid(relation)
Definition: rel.h:456
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ ExecARDeleteTriggers()

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

Definition at line 2498 of file trigger.c.

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

Referenced by ExecDelete(), and ExecSimpleRelationDelete().

2502 {
2503  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2504  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2505 
2506  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2507  (transition_capture && transition_capture->tcs_delete_old_table))
2508  {
2509  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2510  if (fdw_trigtuple == NULL)
2511  GetTupleForTrigger(estate,
2512  NULL,
2513  relinfo,
2514  tupleid,
2516  slot,
2517  NULL);
2518  else
2519  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2520 
2522  true, slot, NULL, NIL, NULL,
2523  transition_capture);
2524  }
2525 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define NIL
Definition: pg_list.h:65
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:2949
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:100
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1145
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
bool trig_delete_after_row
Definition: reltrigger.h:67
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5357
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745

◆ ExecARInsertTriggers()

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

Definition at line 2268 of file trigger.c.

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

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

2271 {
2272  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2273 
2274  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2275  (transition_capture && transition_capture->tcs_insert_new_table))
2277  true, NULL, slot,
2278  recheckIndexes, NULL,
2279  transition_capture);
2280 }
bool trig_insert_after_row
Definition: reltrigger.h:57
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5357
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:99

◆ ExecARUpdateTriggers()

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

Definition at line 2783 of file trigger.c.

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

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

2789 {
2790  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2791  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2792 
2793  ExecClearTuple(oldslot);
2794 
2795  if ((trigdesc && trigdesc->trig_update_after_row) ||
2796  (transition_capture &&
2797  (transition_capture->tcs_update_old_table ||
2798  transition_capture->tcs_update_new_table)))
2799  {
2800  /*
2801  * Note: if the UPDATE is converted into a DELETE+INSERT as part of
2802  * update-partition-key operation, then this function is also called
2803  * separately for DELETE and INSERT to capture transition table rows.
2804  * In such case, either old tuple or new tuple can be NULL.
2805  */
2806  if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
2807  GetTupleForTrigger(estate,
2808  NULL,
2809  relinfo,
2810  tupleid,
2812  oldslot,
2813  NULL);
2814  else if (fdw_trigtuple != NULL)
2815  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
2816 
2818  true, oldslot, newslot, recheckIndexes,
2819  GetAllUpdatedColumns(relinfo, estate),
2820  transition_capture);
2821  }
2822 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:2949
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1145
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
bool trig_update_after_row
Definition: reltrigger.h:62
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5357
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:78
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:101

◆ ExecASDeleteTriggers()

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

Definition at line 2395 of file trigger.c.

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

Referenced by fireASTriggers().

2397 {
2398  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2399 
2400  if (trigdesc && trigdesc->trig_delete_after_statement)
2402  false, NULL, NULL, NIL, NULL, transition_capture);
2403 }
#define NIL
Definition: pg_list.h:65
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:100
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5357
bool trig_delete_after_statement
Definition: reltrigger.h:70

◆ ExecASInsertTriggers()

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

Definition at line 2181 of file trigger.c.

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

Referenced by CopyFrom(), and fireASTriggers().

2183 {
2184  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2185 
2186  if (trigdesc && trigdesc->trig_insert_after_statement)
2188  false, NULL, NULL, NIL, NULL, transition_capture);
2189 }
#define NIL
Definition: pg_list.h:65
bool trig_insert_after_statement
Definition: reltrigger.h:60
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5357
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:99

◆ ExecASTruncateTriggers()

void ExecASTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2938 of file trigger.c.

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

Referenced by ExecuteTruncateGuts().

2939 {
2940  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2941 
2942  if (trigdesc && trigdesc->trig_truncate_after_statement)
2944  false, NULL, NULL, NIL, NULL, NULL);
2945 }
#define NIL
Definition: pg_list.h:65
bool trig_truncate_after_statement
Definition: reltrigger.h:73
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5357
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:102

◆ ExecASUpdateTriggers()

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

Definition at line 2630 of file trigger.c.

References AfterTriggerSaveEvent(), GetAllUpdatedColumns, NIL, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_update_after_statement, and TRIGGER_EVENT_UPDATE.

Referenced by fireASTriggers().

2632 {
2633  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2634 
2635  if (trigdesc && trigdesc->trig_update_after_statement)
2637  false, NULL, NULL, NIL,
2638  GetAllUpdatedColumns(relinfo, estate),
2639  transition_capture);
2640 }
#define NIL
Definition: pg_list.h:65
bool trig_update_after_statement
Definition: reltrigger.h:65
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, TupleTableSlot *oldtup, TupleTableSlot *newtup, List *recheckIndexes, Bitmapset *modifiedCols, TransitionCaptureState *transition_capture)
Definition: trigger.c:5357
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:78
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:101

◆ ExecBRDeleteTriggers()

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

Definition at line 2413 of file trigger.c.

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

Referenced by ExecDelete(), and ExecSimpleRelationDelete().

2418 {
2419  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2420  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2421  bool result = true;
2422  TriggerData LocTriggerData = {0};
2423  HeapTuple trigtuple;
2424  bool should_free = false;
2425  int i;
2426 
2427  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2428  if (fdw_trigtuple == NULL)
2429  {
2430  TupleTableSlot *epqslot_candidate = NULL;
2431 
2432  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2433  LockTupleExclusive, slot, &epqslot_candidate))
2434  return false;
2435 
2436  /*
2437  * If the tuple was concurrently updated and the caller of this
2438  * function requested for the updated tuple, skip the trigger
2439  * execution.
2440  */
2441  if (epqslot_candidate != NULL && epqslot != NULL)
2442  {
2443  *epqslot = epqslot_candidate;
2444  return false;
2445  }
2446 
2447  trigtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2448 
2449  }
2450  else
2451  {
2452  trigtuple = fdw_trigtuple;
2453  ExecForceStoreHeapTuple(trigtuple, slot, false);
2454  }
2455 
2456  LocTriggerData.type = T_TriggerData;
2457  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2460  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2461  for (i = 0; i < trigdesc->numtriggers; i++)
2462  {
2463  HeapTuple newtuple;
2464  Trigger *trigger = &trigdesc->triggers[i];
2465 
2466  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2467  TRIGGER_TYPE_ROW,
2468  TRIGGER_TYPE_BEFORE,
2469  TRIGGER_TYPE_DELETE))
2470  continue;
2471  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2472  NULL, slot, NULL))
2473  continue;
2474 
2475  LocTriggerData.tg_trigslot = slot;
2476  LocTriggerData.tg_trigtuple = trigtuple;
2477  LocTriggerData.tg_trigger = trigger;
2478  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2479  i,
2480  relinfo->ri_TrigFunctions,
2481  relinfo->ri_TrigInstrument,
2482  GetPerTupleMemoryContext(estate));
2483  if (newtuple == NULL)
2484  {
2485  result = false; /* tell caller to suppress delete */
2486  break;
2487  }
2488  if (newtuple != trigtuple)
2489  heap_freetuple(newtuple);
2490  }
2491  if (should_free)
2492  heap_freetuple(trigtuple);
2493 
2494  return result;
2495 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define TRIGGER_EVENT_ROW
Definition: trigger.h:105
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:2949
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:100
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1145
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
HeapTuple tg_trigtuple
Definition: trigger.h:35
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:107
Trigger * triggers
Definition: reltrigger.h:49
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34

◆ ExecBRInsertTriggers()

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

Definition at line 2192 of file trigger.c.

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

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

2194 {
2195  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2196  HeapTuple newtuple = NULL;
2197  bool should_free;
2198  TriggerData LocTriggerData = {0};
2199  int i;
2200 
2201  LocTriggerData.type = T_TriggerData;
2202  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2205  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2206  for (i = 0; i < trigdesc->numtriggers; i++)
2207  {
2208  Trigger *trigger = &trigdesc->triggers[i];
2209  HeapTuple oldtuple;
2210 
2211  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2212  TRIGGER_TYPE_ROW,
2213  TRIGGER_TYPE_BEFORE,
2214  TRIGGER_TYPE_INSERT))
2215  continue;
2216  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2217  NULL, NULL, slot))
2218  continue;
2219 
2220  if (!newtuple)
2221  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2222 
2223  LocTriggerData.tg_trigslot = slot;
2224  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2225  LocTriggerData.tg_trigger = trigger;
2226  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2227  i,
2228  relinfo->ri_TrigFunctions,
2229  relinfo->ri_TrigInstrument,
2230  GetPerTupleMemoryContext(estate));
2231  if (newtuple == NULL)
2232  {
2233  if (should_free)
2234  heap_freetuple(oldtuple);
2235  return false; /* "do nothing" */
2236  }
2237  else if (newtuple != oldtuple)
2238  {
2239  ExecForceStoreHeapTuple(newtuple, slot, false);
2240 
2241  /*
2242  * After a tuple in a partition goes through a trigger, the user
2243  * could have changed the partition key enough that the tuple no
2244  * longer fits the partition. Verify that.
2245  */
2246  if (trigger->tgisclone &&
2247  !ExecPartitionCheck(relinfo, slot, estate, false))
2248  ereport(ERROR,
2249  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2250  errmsg("moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported"),
2251  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2252  trigger->tgname,
2255 
2256  if (should_free)
2257  heap_freetuple(oldtuple);
2258 
2259  /* signal tuple should be re-fetched if used */
2260  newtuple = NULL;
2261  }
2262  }
2263 
2264  return true;
2265 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:105
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:43
char * tgname
Definition: reltrigger.h:27
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:107
Trigger * triggers
Definition: reltrigger.h:49
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define RelationGetRelationName(relation)
Definition: rel.h:490
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
bool tgisclone
Definition: reltrigger.h:32
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:144
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:99
int errmsg(const char *fmt,...)
Definition: elog.c:824
NodeTag type
Definition: trigger.h:32
int i
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1783
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ ExecBRUpdateTriggers()

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

Definition at line 2643 of file trigger.c.

References Assert, ereport, errcode(), errdetail(), errmsg(), ERROR, ExecCallTriggerFunc(), ExecCopySlot(), ExecFetchSlotHeapTuple(), ExecFilterJunk(), ExecForceStoreHeapTuple(), ExecGetTriggerOldSlot(), ExecMaterializeSlot(), ExecPartitionCheck(), ExecUpdateLockMode(), get_namespace_name(), GetAllUpdatedColumns, GetPerTupleMemoryContext, GetTupleForTrigger(), heap_freetuple(), HeapTupleIsValid, i, ItemPointerIsValid, TriggerDesc::numtriggers, RelationGetNamespace, RelationGetRelationName, ResultRelInfo::ri_junkFilter, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newslot, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigslot, TriggerData::tg_trigtuple, TriggerData::tg_updatedcols, Trigger::tgisclone, Trigger::tgname, Trigger::tgtype, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_ROW, TRIGGER_EVENT_UPDATE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecSimpleRelationUpdate(), and ExecUpdate().

2648 {
2649  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2650  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2651  HeapTuple newtuple = NULL;
2652  HeapTuple trigtuple;
2653  bool should_free_trig = false;
2654  bool should_free_new = false;
2655  TriggerData LocTriggerData = {0};
2656  int i;
2657  Bitmapset *updatedCols;
2658  LockTupleMode lockmode;
2659 
2660  /* Determine lock mode to use */
2661  lockmode = ExecUpdateLockMode(estate, relinfo);
2662 
2663  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2664  if (fdw_trigtuple == NULL)
2665  {
2666  TupleTableSlot *epqslot_candidate = NULL;
2667 
2668  /* get a copy of the on-disk tuple we are planning to update */
2669  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2670  lockmode, oldslot, &epqslot_candidate))
2671  return false; /* cancel the update action */
2672 
2673  /*
2674  * In READ COMMITTED isolation level it's possible that target tuple
2675  * was changed due to concurrent update. In that case we have a raw
2676  * subplan output tuple in epqslot_candidate, and need to run it
2677  * through the junk filter to produce an insertable tuple.
2678  *
2679  * Caution: more than likely, the passed-in slot is the same as the
2680  * junkfilter's output slot, so we are clobbering the original value
2681  * of slottuple by doing the filtering. This is OK since neither we
2682  * nor our caller have any more interest in the prior contents of that
2683  * slot.
2684  */
2685  if (epqslot_candidate != NULL)
2686  {
2687  TupleTableSlot *epqslot_clean;
2688 
2689  epqslot_clean = ExecFilterJunk(relinfo->ri_junkFilter, epqslot_candidate);
2690 
2691  if (newslot != epqslot_clean)
2692  ExecCopySlot(newslot, epqslot_clean);
2693  }
2694 
2695  trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
2696  }
2697  else
2698  {
2699  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
2700  trigtuple = fdw_trigtuple;
2701  }
2702 
2703  LocTriggerData.type = T_TriggerData;
2704  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2707  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2708  updatedCols = GetAllUpdatedColumns(relinfo, estate);
2709  LocTriggerData.tg_updatedcols = updatedCols;
2710  for (i = 0; i < trigdesc->numtriggers; i++)
2711  {
2712  Trigger *trigger = &trigdesc->triggers[i];
2713  HeapTuple oldtuple;
2714 
2715  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2716  TRIGGER_TYPE_ROW,
2717  TRIGGER_TYPE_BEFORE,
2718  TRIGGER_TYPE_UPDATE))
2719  continue;
2720  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2721  updatedCols, oldslot, newslot))
2722  continue;
2723 
2724  if (!newtuple)
2725  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
2726 
2727  LocTriggerData.tg_trigslot = oldslot;
2728  LocTriggerData.tg_trigtuple = trigtuple;
2729  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2730  LocTriggerData.tg_newslot = newslot;
2731  LocTriggerData.tg_trigger = trigger;
2732  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2733  i,
2734  relinfo->ri_TrigFunctions,
2735  relinfo->ri_TrigInstrument,
2736  GetPerTupleMemoryContext(estate));
2737 
2738  if (newtuple == NULL)
2739  {
2740  if (should_free_trig)
2741  heap_freetuple(trigtuple);
2742  if (should_free_new)
2743  heap_freetuple(oldtuple);
2744  return false; /* "do nothing" */
2745  }
2746  else if (newtuple != oldtuple)
2747  {
2748  ExecForceStoreHeapTuple(newtuple, newslot, false);
2749 
2750  if (trigger->tgisclone &&
2751  !ExecPartitionCheck(relinfo, newslot, estate, false))
2752  ereport(ERROR,
2753  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2754  errmsg("moving row to another partition during a BEFORE trigger is not supported"),
2755  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2756  trigger->tgname,
2759 
2760  /*
2761  * If the tuple returned by the trigger / being stored, is the old
2762  * row version, and the heap tuple passed to the trigger was
2763  * allocated locally, materialize the slot. Otherwise we might
2764  * free it while still referenced by the slot.
2765  */
2766  if (should_free_trig && newtuple == trigtuple)
2767  ExecMaterializeSlot(newslot);
2768 
2769  if (should_free_new)
2770  heap_freetuple(oldtuple);
2771 
2772  /* signal tuple should be re-fetched if used */
2773  newtuple = NULL;
2774  }
2775  }
2776  if (should_free_trig)
2777  heap_freetuple(trigtuple);
2778 
2779  return true;
2780 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define TRIGGER_EVENT_ROW
Definition: trigger.h:105
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
JunkFilter * ri_junkFilter
Definition: execnodes.h:466
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:413
LockTupleMode
Definition: lockoptions.h:49
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:2949
const Bitmapset * tg_updatedcols
Definition: trigger.h:42
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1145
int errcode(int sqlerrcode)
Definition: elog.c:610
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:43
char * tgname
Definition: reltrigger.h:27
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:107
Trigger * triggers
Definition: reltrigger.h:49
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define RelationGetRelationName(relation)
Definition: rel.h:490
TupleTableSlot * tg_newslot
Definition: trigger.h:39
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
bool tgisclone
Definition: reltrigger.h:32
int numtriggers
Definition: reltrigger.h:50
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:261
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:745
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2313
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:78
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:101
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
int errmsg(const char *fmt,...)
Definition: elog.c:824
NodeTag type
Definition: trigger.h:32
int i
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1783
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ ExecBSDeleteTriggers()

void ExecBSDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2344 of file trigger.c.

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

Referenced by fireBSTriggers().

2345 {
2346  TriggerDesc *trigdesc;
2347  int i;
2348  TriggerData LocTriggerData = {0};
2349 
2350  trigdesc = relinfo->ri_TrigDesc;
2351 
2352  if (trigdesc == NULL)
2353  return;
2354  if (!trigdesc->trig_delete_before_statement)
2355  return;
2356 
2357  /* no-op if we already fired BS triggers in this context */
2359  CMD_DELETE))
2360  return;
2361 
2362  LocTriggerData.type = T_TriggerData;
2363  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2365  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2366  for (i = 0; i < trigdesc->numtriggers; i++)
2367  {
2368  Trigger *trigger = &trigdesc->triggers[i];
2369  HeapTuple newtuple;
2370 
2371  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2372  TRIGGER_TYPE_STATEMENT,
2373  TRIGGER_TYPE_BEFORE,
2374  TRIGGER_TYPE_DELETE))
2375  continue;
2376  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2377  NULL, NULL, NULL))
2378  continue;
2379 
2380  LocTriggerData.tg_trigger = trigger;
2381  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2382  i,
2383  relinfo->ri_TrigFunctions,
2384  relinfo->ri_TrigInstrument,
2385  GetPerTupleMemoryContext(estate));
2386 
2387  if (newtuple)
2388  ereport(ERROR,
2389  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2390  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2391  }
2392 }
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:100
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
int errcode(int sqlerrcode)
Definition: elog.c:610
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5690
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:107
Trigger * triggers
Definition: reltrigger.h:49
bool trig_delete_before_statement
Definition: reltrigger.h:69
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:144
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
int errmsg(const char *fmt,...)
Definition: elog.c:824
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
#define RelationGetRelid(relation)
Definition: rel.h:456
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSInsertTriggers()

void ExecBSInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2130 of file trigger.c.

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

Referenced by CopyFrom(), and fireBSTriggers().

2131 {
2132  TriggerDesc *trigdesc;
2133  int i;
2134  TriggerData LocTriggerData = {0};
2135 
2136  trigdesc = relinfo->ri_TrigDesc;
2137 
2138  if (trigdesc == NULL)
2139  return;
2140  if (!trigdesc->trig_insert_before_statement)
2141  return;
2142 
2143  /* no-op if we already fired BS triggers in this context */
2145  CMD_INSERT))
2146  return;
2147 
2148  LocTriggerData.type = T_TriggerData;
2149  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2151  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2152  for (i = 0; i < trigdesc->numtriggers; i++)
2153  {
2154  Trigger *trigger = &trigdesc->triggers[i];
2155  HeapTuple newtuple;
2156 
2157  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2158  TRIGGER_TYPE_STATEMENT,
2159  TRIGGER_TYPE_BEFORE,
2160  TRIGGER_TYPE_INSERT))
2161  continue;
2162  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2163  NULL, NULL, NULL))
2164  continue;
2165 
2166  LocTriggerData.tg_trigger = trigger;
2167  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2168  i,
2169  relinfo->ri_TrigFunctions,
2170  relinfo->ri_TrigInstrument,
2171  GetPerTupleMemoryContext(estate));
2172 
2173  if (newtuple)
2174  ereport(ERROR,
2175  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2176  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2177  }
2178 }
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
int errcode(int sqlerrcode)
Definition: elog.c:610
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5690
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:107
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:144
TriggerEvent tg_event
Definition: trigger.h:33
bool trig_insert_before_statement
Definition: reltrigger.h:59
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:99
int errmsg(const char *fmt,...)
Definition: elog.c:824
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
#define RelationGetRelid(relation)
Definition: rel.h:456
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSTruncateTriggers()

void ExecBSTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2891 of file trigger.c.

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

Referenced by ExecuteTruncateGuts().

2892 {
2893  TriggerDesc *trigdesc;
2894  int i;
2895  TriggerData LocTriggerData = {0};
2896 
2897  trigdesc = relinfo->ri_TrigDesc;
2898 
2899  if (trigdesc == NULL)
2900  return;
2901  if (!trigdesc->trig_truncate_before_statement)
2902  return;
2903 
2904  LocTriggerData.type = T_TriggerData;
2905  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
2907  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2908 
2909  for (i = 0; i < trigdesc->numtriggers; i++)
2910  {
2911  Trigger *trigger = &trigdesc->triggers[i];
2912  HeapTuple newtuple;
2913 
2914  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2915  TRIGGER_TYPE_STATEMENT,
2916  TRIGGER_TYPE_BEFORE,
2917  TRIGGER_TYPE_TRUNCATE))
2918  continue;
2919  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2920  NULL, NULL, NULL))
2921  continue;
2922 
2923  LocTriggerData.tg_trigger = trigger;
2924  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2925  i,
2926  relinfo->ri_TrigFunctions,
2927  relinfo->ri_TrigInstrument,
2928  GetPerTupleMemoryContext(estate));
2929 
2930  if (newtuple)
2931  ereport(ERROR,
2932  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2933  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2934  }
2935 }
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:107
Trigger * triggers
Definition: reltrigger.h:49
bool trig_truncate_before_statement
Definition: reltrigger.h:72
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:144
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:102
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
int errmsg(const char *fmt,...)
Definition: elog.c:824
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSUpdateTriggers()

void ExecBSUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2575 of file trigger.c.

References before_stmt_triggers_fired(), CMD_UPDATE, ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetAllUpdatedColumns, GetPerTupleMemoryContext, i, TriggerDesc::numtriggers, RelationGetRelid, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_relation, TriggerData::tg_trigger, 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().

2576 {
2577  TriggerDesc *trigdesc;
2578  int i;
2579  TriggerData LocTriggerData = {0};
2580  Bitmapset *updatedCols;
2581 
2582  trigdesc = relinfo->ri_TrigDesc;
2583 
2584  if (trigdesc == NULL)
2585  return;
2586  if (!trigdesc->trig_update_before_statement)
2587  return;
2588 
2589  /* no-op if we already fired BS triggers in this context */
2591  CMD_UPDATE))
2592  return;
2593 
2594  updatedCols = GetAllUpdatedColumns(relinfo, estate);
2595 
2596  LocTriggerData.type = T_TriggerData;
2597  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2599  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2600  LocTriggerData.tg_updatedcols = updatedCols;
2601  for (i = 0; i < trigdesc->numtriggers; i++)
2602  {
2603  Trigger *trigger = &trigdesc->triggers[i];
2604  HeapTuple newtuple;
2605 
2606  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2607  TRIGGER_TYPE_STATEMENT,
2608  TRIGGER_TYPE_BEFORE,
2609  TRIGGER_TYPE_UPDATE))
2610  continue;
2611  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2612  updatedCols, NULL, NULL))
2613  continue;
2614 
2615  LocTriggerData.tg_trigger = trigger;
2616  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2617  i,
2618  relinfo->ri_TrigFunctions,
2619  relinfo->ri_TrigInstrument,
2620  GetPerTupleMemoryContext(estate));
2621 
2622  if (newtuple)
2623  ereport(ERROR,
2624  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2625  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2626  }
2627 }
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
const Bitmapset * tg_updatedcols
Definition: trigger.h:42
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
int errcode(int sqlerrcode)
Definition: elog.c:610
bool trig_update_before_statement
Definition: reltrigger.h:64
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5690
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:107
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
#define ereport(elevel,...)
Definition: elog.h:144
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:78
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:101
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
int errmsg(const char *fmt,...)
Definition: elog.c:824
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
#define RelationGetRelid(relation)
Definition: rel.h:456
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRDeleteTriggers()

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

Definition at line 2528 of file trigger.c.

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

Referenced by ExecDelete().

2530 {
2531  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2532  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2533  TriggerData LocTriggerData = {0};
2534  int i;
2535 
2536  LocTriggerData.type = T_TriggerData;
2537  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2540  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2541 
2542  ExecForceStoreHeapTuple(trigtuple, slot, false);
2543 
2544  for (i = 0; i < trigdesc->numtriggers; i++)
2545  {
2546  HeapTuple rettuple;
2547  Trigger *trigger = &trigdesc->triggers[i];
2548 
2549  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2550  TRIGGER_TYPE_ROW,
2551  TRIGGER_TYPE_INSTEAD,
2552  TRIGGER_TYPE_DELETE))
2553  continue;
2554  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2555  NULL, slot, NULL))
2556  continue;
2557 
2558  LocTriggerData.tg_trigslot = slot;
2559  LocTriggerData.tg_trigtuple = trigtuple;
2560  LocTriggerData.tg_trigger = trigger;
2561  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2562  i,
2563  relinfo->ri_TrigFunctions,
2564  relinfo->ri_TrigInstrument,
2565  GetPerTupleMemoryContext(estate));
2566  if (rettuple == NULL)
2567  return false; /* Delete was suppressed */
2568  if (rettuple != trigtuple)
2569  heap_freetuple(rettuple);
2570  }
2571  return true;
2572 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:105
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:100
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1145
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:109
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRInsertTriggers()

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

Definition at line 2283 of file trigger.c.

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

Referenced by CopyFrom(), and ExecInsert().

2285 {
2286  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2287  HeapTuple newtuple = NULL;
2288  bool should_free;
2289  TriggerData LocTriggerData = {0};
2290  int i;
2291 
2292  LocTriggerData.type = T_TriggerData;
2293  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2296  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2297  for (i = 0; i < trigdesc->numtriggers; i++)
2298  {
2299  Trigger *trigger = &trigdesc->triggers[i];
2300  HeapTuple oldtuple;
2301 
2302  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2303  TRIGGER_TYPE_ROW,
2304  TRIGGER_TYPE_INSTEAD,
2305  TRIGGER_TYPE_INSERT))
2306  continue;
2307  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2308  NULL, NULL, slot))
2309  continue;
2310 
2311  if (!newtuple)
2312  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2313 
2314  LocTriggerData.tg_trigslot = slot;
2315  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2316  LocTriggerData.tg_trigger = trigger;
2317  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2318  i,
2319  relinfo->ri_TrigFunctions,
2320  relinfo->ri_TrigInstrument,
2321  GetPerTupleMemoryContext(estate));
2322  if (newtuple == NULL)
2323  {
2324  if (should_free)
2325  heap_freetuple(oldtuple);
2326  return false; /* "do nothing" */
2327  }
2328  else if (newtuple != oldtuple)
2329  {
2330  ExecForceStoreHeapTuple(newtuple, slot, false);
2331 
2332  if (should_free)
2333  heap_freetuple(oldtuple);
2334 
2335  /* signal tuple should be re-fetched if used */
2336  newtuple = NULL;
2337  }
2338  }
2339 
2340  return true;
2341 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:105
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:109
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:49
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:99
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRUpdateTriggers()

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

Definition at line 2825 of file trigger.c.

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

Referenced by ExecUpdate().

2827 {
2828  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2829  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2830  HeapTuple newtuple = NULL;
2831  bool should_free;
2832  TriggerData LocTriggerData = {0};
2833  int i;
2834 
2835  LocTriggerData.type = T_TriggerData;
2836  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2839  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2840 
2841  ExecForceStoreHeapTuple(trigtuple, oldslot, false);
2842 
2843  for (i = 0; i < trigdesc->numtriggers; i++)
2844  {
2845  Trigger *trigger = &trigdesc->triggers[i];
2846  HeapTuple oldtuple;
2847 
2848  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2849  TRIGGER_TYPE_ROW,
2850  TRIGGER_TYPE_INSTEAD,
2851  TRIGGER_TYPE_UPDATE))
2852  continue;
2853  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2854  NULL, oldslot, newslot))
2855  continue;
2856 
2857  if (!newtuple)
2858  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
2859 
2860  LocTriggerData.tg_trigslot = oldslot;
2861  LocTriggerData.tg_trigtuple = trigtuple;
2862  LocTriggerData.tg_newslot = newslot;
2863  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2864 
2865  LocTriggerData.tg_trigger = trigger;
2866  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2867  i,
2868  relinfo->ri_TrigFunctions,
2869  relinfo->ri_TrigInstrument,
2870  GetPerTupleMemoryContext(estate));
2871  if (newtuple == NULL)
2872  {
2873  return false; /* "do nothing" */
2874  }
2875  else if (newtuple != oldtuple)
2876  {
2877  ExecForceStoreHeapTuple(newtuple, newslot, false);
2878 
2879  if (should_free)
2880  heap_freetuple(oldtuple);
2881 
2882  /* signal tuple should be re-fetched if used */
2883  newtuple = NULL;
2884  }
2885  }
2886 
2887  return true;
2888 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:105
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:413
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3065
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:434
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1145
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:109
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:49
TupleTableSlot * tg_newslot
Definition: trigger.h:39
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
int numtriggers
Definition: reltrigger.h:50
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:101
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
NodeTag type
Definition: trigger.h:32
int i
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2038
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:428
Relation tg_relation
Definition: trigger.h:34

◆ FindTriggerIncompatibleWithInheritance()

const char* FindTriggerIncompatibleWithInheritance ( TriggerDesc trigdesc)

Definition at line 2008 of file trigger.c.

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

Referenced by ATExecAddInherit(), and ATExecAttachPartition().

2009 {
2010  if (trigdesc != NULL)
2011  {
2012  int i;
2013 
2014  for (i = 0; i < trigdesc->numtriggers; ++i)
2015  {
2016  Trigger *trigger = &trigdesc->triggers[i];
2017 
2018  if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
2019  return trigger->tgname;
2020  }
2021  }
2022 
2023  return NULL;
2024 }
char * tgname
Definition: reltrigger.h:27
Trigger * triggers
Definition: reltrigger.h:49
int numtriggers
Definition: reltrigger.h:50
char * tgnewtable
Definition: reltrigger.h:44
int i
char * tgoldtable
Definition: reltrigger.h:43

◆ FreeTriggerDesc()

void FreeTriggerDesc ( TriggerDesc trigdesc)

Definition at line 1876 of file trigger.c.

References i, TriggerDesc::numtriggers, pfree(), 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, and TriggerDesc::triggers.

Referenced by RelationBuildTriggers(), and RelationDestroyRelation().

1877 {
1878  Trigger *trigger;
1879  int i;
1880 
1881  if (trigdesc == NULL)
1882  return;
1883 
1884  trigger = trigdesc->triggers;
1885  for (i = 0; i < trigdesc->numtriggers; i++)
1886  {
1887  pfree(trigger->tgname);
1888  if (trigger->tgnattr > 0)
1889  pfree(trigger->tgattr);
1890  if (trigger->tgnargs > 0)
1891  {
1892  while (--(trigger->tgnargs) >= 0)
1893  pfree(trigger->tgargs[trigger->tgnargs]);
1894  pfree(trigger->tgargs);
1895  }
1896  if (trigger->tgqual)
1897  pfree(trigger->tgqual);
1898  if (trigger->tgoldtable)
1899  pfree(trigger->tgoldtable);
1900  if (trigger->tgnewtable)
1901  pfree(trigger->tgnewtable);
1902  trigger++;
1903  }
1904  pfree(trigdesc->triggers);
1905  pfree(trigdesc);
1906 }
void pfree(void *pointer)
Definition: mcxt.c:1056
char * tgqual
Definition: reltrigger.h:42
char * tgname
Definition: reltrigger.h:27
Trigger * triggers
Definition: reltrigger.h:49
int numtriggers
Definition: reltrigger.h:50
char ** tgargs
Definition: reltrigger.h:41
int16 * tgattr
Definition: reltrigger.h:40
char * tgnewtable
Definition: reltrigger.h:44
int16 tgnattr
Definition: reltrigger.h:39
int i
int16 tgnargs
Definition: reltrigger.h:38
char * tgoldtable
Definition: reltrigger.h:43

◆ get_trigger_oid()

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

Definition at line 1239 of file trigger.c.

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

Referenced by get_object_address_relobject().

1240 {
1241  Relation tgrel;
1242  ScanKeyData skey[2];
1243  SysScanDesc tgscan;
1244  HeapTuple tup;
1245  Oid oid;
1246 
1247  /*
1248  * Find the trigger, verify permissions, set up object address
1249  */
1250  tgrel = table_open(TriggerRelationId, AccessShareLock);
1251 
1252  ScanKeyInit(&skey[0],
1253  Anum_pg_trigger_tgrelid,
1254  BTEqualStrategyNumber, F_OIDEQ,
1255  ObjectIdGetDatum(relid));
1256  ScanKeyInit(&skey[1],
1257  Anum_pg_trigger_tgname,
1258  BTEqualStrategyNumber, F_NAMEEQ,
1259  CStringGetDatum(trigname));
1260 
1261  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1262  NULL, 2, skey);
1263 
1264  tup = systable_getnext(tgscan);
1265 
1266  if (!HeapTupleIsValid(tup))
1267  {
1268  if (!missing_ok)
1269  ereport(ERROR,
1270  (errcode(ERRCODE_UNDEFINED_OBJECT),
1271  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1272  trigname, get_rel_name(relid))));
1273  oid = InvalidOid;
1274  }
1275  else
1276  {
1277  oid = ((Form_pg_trigger) GETSTRUCT(tup))->oid;
1278  }
1279 
1280  systable_endscan(tgscan);
1281  table_close(tgrel, AccessShareLock);
1282  return oid;
1283 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:569
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:357
#define TriggerRelidNameIndexId
Definition: indexing.h:258
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define CStringGetDatum(X)
Definition: postgres.h:578
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:73
int errmsg(const char *fmt,...)
Definition: elog.c:824
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
#define BTEqualStrategyNumber
Definition: stratnum.h:31

◆ MakeTransitionCaptureState()

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

Definition at line 4310 of file trigger.c.

References AfterTriggerEnlargeQueryState(), CMD_DELETE, CMD_INSERT, CMD_UPDATE, CurrentResourceOwner, CurTransactionContext, CurTransactionResourceOwner, elog, ERROR, GetAfterTriggersTableData(), AfterTriggersData::maxquerydepth, MemoryContextSwitchTo(), AfterTriggersTableData::new_tuplestore, AfterTriggersTableData::old_tuplestore, palloc0(), AfterTriggersData::query_depth, TransitionCaptureState::tcs_delete_old_table, TransitionCaptureState::tcs_insert_new_table, TransitionCaptureState::tcs_private, TransitionCaptureState::tcs_update_new_table, TransitionCaptureState::tcs_update_old_table, 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().

4311 {
4313  bool need_old,
4314  need_new;
4315  AfterTriggersTableData *table;
4316  MemoryContext oldcxt;
4317  ResourceOwner saveResourceOwner;
4318 
4319  if (trigdesc == NULL)
4320  return NULL;
4321 
4322  /* Detect which table(s) we need. */
4323  switch (cmdType)
4324  {
4325  case CMD_INSERT:
4326  need_old = false;
4327  need_new = trigdesc->trig_insert_new_table;
4328  break;
4329  case CMD_UPDATE:
4330  need_old = trigdesc->trig_update_old_table;
4331  need_new = trigdesc->trig_update_new_table;
4332  break;
4333  case CMD_DELETE:
4334  need_old = trigdesc->trig_delete_old_table;
4335  need_new = false;
4336  break;
4337  default:
4338  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4339  need_old = need_new = false; /* keep compiler quiet */
4340  break;
4341  }
4342  if (!need_old && !need_new)
4343  return NULL;
4344 
4345  /* Check state, like AfterTriggerSaveEvent. */
4346  if (afterTriggers.query_depth < 0)
4347  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4348 
4349  /* Be sure we have enough space to record events at this query depth. */
4352 
4353  /*
4354  * Find or create an AfterTriggersTableData struct to hold the
4355  * tuplestore(s). If there's a matching struct but it's marked closed,
4356  * ignore it; we need a newer one.
4357  *
4358  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4359  * allocated in the current (sub)transaction's CurTransactionContext, and
4360  * the tuplestores are managed by the (sub)transaction's resource owner.
4361  * This is sufficient lifespan because we do not allow triggers using
4362  * transition tables to be deferrable; they will be fired during
4363  * AfterTriggerEndQuery, after which it's okay to delete the data.
4364  */
4365  table = GetAfterTriggersTableData(relid, cmdType);
4366 
4367  /* Now create required tuplestore(s), if we don't have them already. */
4369  saveResourceOwner = CurrentResourceOwner;
4371 
4372  if (need_old && table->old_tuplestore == NULL)
4373  table->old_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4374  if (need_new && table->new_tuplestore == NULL)
4375  table->new_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4376 
4377  CurrentResourceOwner = saveResourceOwner;
4378  MemoryContextSwitchTo(oldcxt);
4379 
4380  /* Now build the TransitionCaptureState struct, in caller's context */
4382  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4383  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4384  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4385  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4386  state->tcs_private = table;
4387 
4388  return state;
4389 }
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:143
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
Tuplestorestate * old_tuplestore
Definition: trigger.c:3478
bool trig_update_new_table
Definition: reltrigger.h:77
bool trig_insert_new_table
Definition: reltrigger.h:75
struct AfterTriggersTableData * tcs_private
Definition: trigger.h:88
#define ERROR
Definition: elog.h:43
static AfterTriggersTableData * GetAfterTriggersTableData(Oid relid, CmdType cmdType)
Definition: trigger.c:4252
bool trig_update_old_table
Definition: reltrigger.h:76
Tuplestorestate * new_tuplestore
Definition: trigger.c:3479
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
void * palloc0(Size size)
Definition: mcxt.c:980
int work_mem
Definition: globals.c:121
static void AfterTriggerEnlargeQueryState(void)
Definition: trigger.c:4850
Definition: regguts.h:298
#define elog(elevel,...)
Definition: elog.h:214
bool trig_delete_old_table
Definition: reltrigger.h:78
static AfterTriggersData afterTriggers
Definition: trigger.c:3483

◆ RelationBuildTriggers()

void RelationBuildTriggers ( Relation  relation)

Definition at line 1592 of file trigger.c.

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, TriggerRelidNameIndexId, TriggerDesc::triggers, val, and VARDATA_ANY.

Referenced by RelationBuildDesc(), and RelationCacheInitializePhase3().

1593 {
1594  TriggerDesc *trigdesc;
1595  int numtrigs;
1596  int maxtrigs;
1597  Trigger *triggers;
1598  Relation tgrel;
1599  ScanKeyData skey;
1600  SysScanDesc tgscan;
1601  HeapTuple htup;
1602  MemoryContext oldContext;
1603  int i;
1604 
1605  /*
1606  * Allocate a working array to hold the triggers (the array is extended if
1607  * necessary)
1608  */
1609  maxtrigs = 16;
1610  triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
1611  numtrigs = 0;
1612 
1613  /*
1614  * Note: since we scan the triggers using TriggerRelidNameIndexId, we will
1615  * be reading the triggers in name order, except possibly during
1616  * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
1617  * ensures that triggers will be fired in name order.
1618  */
1619  ScanKeyInit(&skey,
1620  Anum_pg_trigger_tgrelid,
1621  BTEqualStrategyNumber, F_OIDEQ,
1622  ObjectIdGetDatum(RelationGetRelid(relation)));
1623 
1624  tgrel = table_open(TriggerRelationId, AccessShareLock);
1625  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1626  NULL, 1, &skey);
1627 
1628  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
1629  {
1630  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
1631  Trigger *build;
1632  Datum datum;
1633  bool isnull;
1634 
1635  if (numtrigs >= maxtrigs)
1636  {
1637  maxtrigs *= 2;
1638  triggers = (Trigger *) repalloc(triggers, maxtrigs * sizeof(Trigger));
1639  }
1640  build = &(triggers[numtrigs]);
1641 
1642  build->tgoid = pg_trigger->oid;
1644  NameGetDatum(&pg_trigger->tgname)));
1645  build->tgfoid = pg_trigger->tgfoid;
1646  build->