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 106 of file trigger.h.

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

◆ AFTER_TRIGGER_INITDEFERRED

#define AFTER_TRIGGER_INITDEFERRED   0x00000040

Definition at line 107 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 264 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 265 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 263 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 141 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_ORIGIN

#define SESSION_REPLICATION_ROLE_ORIGIN   0

Definition at line 139 of file trigger.h.

◆ SESSION_REPLICATION_ROLE_REPLICA

#define SESSION_REPLICATION_ROLE_REPLICA   1

Definition at line 140 of file trigger.h.

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

◆ TRIGGER_DISABLED

#define TRIGGER_DISABLED   'D'

Definition at line 151 of file trigger.h.

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

◆ TRIGGER_EVENT_AFTER

#define TRIGGER_EVENT_AFTER   0x00000000

Definition at line 100 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 101 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 102 of file trigger.h.

◆ TRIGGER_EVENT_TRUNCATE

#define TRIGGER_EVENT_TRUNCATE   0x00000003

Definition at line 94 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), ExecASTruncateTriggers(), and ExecBSTruncateTriggers().

◆ 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 149 of file trigger.h.

Referenced by ATExecCmd().

◆ TRIGGER_FIRES_ON_ORIGIN

◆ TRIGGER_FIRES_ON_REPLICA

#define TRIGGER_FIRES_ON_REPLICA   'R'

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

References AfterTriggersData::query_depth.

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

4414 {
4415  /* Increase the query stack depth */
4417 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3463

◆ AfterTriggerBeginSubXact()

void AfterTriggerBeginSubXact ( void  )

Definition at line 4681 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().

4682 {
4683  int my_level = GetCurrentTransactionNestLevel();
4684 
4685  /*
4686  * Allocate more space in the trans_stack if needed. (Note: because the
4687  * minimum nest level of a subtransaction is 2, we waste the first couple
4688  * entries of the array; not worth the notational effort to avoid it.)
4689  */
4690  while (my_level >= afterTriggers.maxtransdepth)
4691  {
4692  if (afterTriggers.maxtransdepth == 0)
4693  {
4694  /* Arbitrarily initialize for max of 8 subtransaction levels */
4697  8 * sizeof(AfterTriggersTransData));
4699  }
4700  else
4701  {
4702  /* repalloc will keep the stack in the same context */
4703  int new_alloc = afterTriggers.maxtransdepth * 2;
4704 
4707  new_alloc * sizeof(AfterTriggersTransData));
4708  afterTriggers.maxtransdepth = new_alloc;
4709  }
4710  }
4711 
4712  /*
4713  * Push the current information into the stack. The SET CONSTRAINTS state
4714  * is not saved until/unless changed. Likewise, we don't make a
4715  * per-subtransaction event context until needed.
4716  */
4717  afterTriggers.trans_stack[my_level].state = NULL;
4721 }
AfterTriggersTransData * trans_stack
Definition: trigger.c:3429
MemoryContext TopTransactionContext
Definition: mcxt.c:49
AfterTriggerEventList events
Definition: trigger.c:3444
CommandId firing_counter
Definition: trigger.c:3446
CommandId firing_counter
Definition: trigger.c:3418
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
AfterTriggerEventList events
Definition: trigger.c:3420
static AfterTriggersData afterTriggers
Definition: trigger.c:3463
SetConstraintState state
Definition: trigger.c:3443

◆ AfterTriggerBeginXact()

void AfterTriggerBeginXact ( void  )

Definition at line 4381 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().

4382 {
4383  /*
4384  * Initialize after-trigger state structure to empty
4385  */
4386  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4388 
4389  /*
4390  * Verify that there is no leftover state remaining. If these assertions
4391  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4392  * up properly.
4393  */
4394  Assert(afterTriggers.state == NULL);
4395  Assert(afterTriggers.query_stack == NULL);
4397  Assert(afterTriggers.event_cxt == NULL);
4398  Assert(afterTriggers.events.head == NULL);
4399  Assert(afterTriggers.trans_stack == NULL);
4401 }
uint32 CommandId
Definition: c.h:535
AfterTriggersTransData * trans_stack
Definition: trigger.c:3429
AfterTriggersQueryData * query_stack
Definition: trigger.c:3424
SetConstraintState state
Definition: trigger.c:3419
CommandId firing_counter
Definition: trigger.c:3418
#define Assert(condition)
Definition: c.h:746
AfterTriggerEventChunk * head
Definition: trigger.c:3312
MemoryContext event_cxt
Definition: trigger.c:3421
AfterTriggerEventList events
Definition: trigger.c:3420
static AfterTriggersData afterTriggers
Definition: trigger.c:3463

◆ AfterTriggerEndQuery()

void AfterTriggerEndQuery ( EState estate)

Definition at line 4433 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().

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

◆ AfterTriggerEndSubXact()

void AfterTriggerEndSubXact ( bool  isCommit)

Definition at line 4729 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().

4730 {
4731  int my_level = GetCurrentTransactionNestLevel();
4733  AfterTriggerEvent event;
4734  AfterTriggerEventChunk *chunk;
4735  CommandId subxact_firing_id;
4736 
4737  /*
4738  * Pop the prior state if needed.
4739  */
4740  if (isCommit)
4741  {
4742  Assert(my_level < afterTriggers.maxtransdepth);
4743  /* If we saved a prior state, we don't need it anymore */
4744  state = afterTriggers.trans_stack[my_level].state;
4745  if (state != NULL)
4746  pfree(state);
4747  /* this avoids double pfree if error later: */
4748  afterTriggers.trans_stack[my_level].state = NULL;
4751  }
4752  else
4753  {
4754  /*
4755  * Aborting. It is possible subxact start failed before calling
4756  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
4757  * trans_stack levels that aren't there.
4758  */
4759  if (my_level >= afterTriggers.maxtransdepth)
4760  return;
4761 
4762  /*
4763  * Release query-level storage for queries being aborted, and restore
4764  * query_depth to its pre-subxact value. This assumes that a
4765  * subtransaction will not add events to query levels started in a
4766  * earlier transaction state.
4767  */
4769  {
4773  }
4776 
4777  /*
4778  * Restore the global deferred-event list to its former length,
4779  * discarding any events queued by the subxact.
4780  */
4782  &afterTriggers.trans_stack[my_level].events);
4783 
4784  /*
4785  * Restore the trigger state. If the saved state is NULL, then this
4786  * subxact didn't save it, so it doesn't need restoring.
4787  */
4788  state = afterTriggers.trans_stack[my_level].state;
4789  if (state != NULL)
4790  {
4792  afterTriggers.state = state;
4793  }
4794  /* this avoids double pfree if error later: */
4795  afterTriggers.trans_stack[my_level].state = NULL;
4796 
4797  /*
4798  * Scan for any remaining deferred events that were marked DONE or IN
4799  * PROGRESS by this subxact or a child, and un-mark them. We can
4800  * recognize such events because they have a firing ID greater than or
4801  * equal to the firing_counter value we saved at subtransaction start.
4802  * (This essentially assumes that the current subxact includes all
4803  * subxacts started after it.)
4804  */
4805  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
4807  {
4808  AfterTriggerShared evtshared = GetTriggerSharedData(event);
4809 
4810  if (event->ate_flags &
4812  {
4813  if (evtshared->ats_firing_id >= subxact_firing_id)
4814  event->ate_flags &=
4816  }
4817  }
4818  }
4819 }
uint32 CommandId
Definition: c.h:535
AfterTriggersTransData * trans_stack
Definition: trigger.c:3429
TriggerFlags ate_flags
Definition: trigger.c:3263
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3238
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3325
AfterTriggerEventList events
Definition: trigger.c:3444
AfterTriggersQueryData * query_stack
Definition: trigger.c:3424
CommandId firing_counter
Definition: trigger.c:3446
#define GetTriggerSharedData(evt)
Definition: trigger.c:3288
void pfree(void *pointer)
Definition: mcxt.c:1057
SetConstraintState state
Definition: trigger.c:3419
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
#define Assert(condition)
Definition: c.h:746
Definition: regguts.h:298
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:3708
CommandId ats_firing_id
Definition: trigger.c:3254
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3239
AfterTriggerEventList events
Definition: trigger.c:3420
static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
Definition: trigger.c:4524
static AfterTriggersData afterTriggers
Definition: trigger.c:3463
SetConstraintState state
Definition: trigger.c:3443

◆ AfterTriggerEndXact()

void AfterTriggerEndXact ( bool  isCommit)

Definition at line 4633 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().

4634 {
4635  /*
4636  * Forget the pending-events list.
4637  *
4638  * Since all the info is in TopTransactionContext or children thereof, we
4639  * don't really need to do anything to reclaim memory. However, the
4640  * pending-events list could be large, and so it's useful to discard it as
4641  * soon as possible --- especially if we are aborting because we ran out
4642  * of memory for the list!
4643  */
4645  {
4647  afterTriggers.event_cxt = NULL;
4648  afterTriggers.events.head = NULL;
4649  afterTriggers.events.tail = NULL;
4650  afterTriggers.events.tailfree = NULL;
4651  }
4652 
4653  /*
4654  * Forget any subtransaction state as well. Since this can't be very
4655  * large, we let the eventual reset of TopTransactionContext free the
4656  * memory instead of doing it here.
4657  */
4658  afterTriggers.trans_stack = NULL;
4660 
4661 
4662  /*
4663  * Forget the query stack and constraint-related state information. As
4664  * with the subtransaction state information, we don't bother freeing the
4665  * memory here.
4666  */
4667  afterTriggers.query_stack = NULL;
4669  afterTriggers.state = NULL;
4670 
4671  /* No more afterTriggers manipulation until next transaction starts. */
4673 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
AfterTriggersTransData * trans_stack
Definition: trigger.c:3429
AfterTriggersQueryData * query_stack
Definition: trigger.c:3424
AfterTriggerEventChunk * tail
Definition: trigger.c:3313
SetConstraintState state
Definition: trigger.c:3419
AfterTriggerEventChunk * head
Definition: trigger.c:3312
MemoryContext event_cxt
Definition: trigger.c:3421
AfterTriggerEventList events
Definition: trigger.c:3420
static AfterTriggersData afterTriggers
Definition: trigger.c:3463

◆ AfterTriggerFireDeferred()

void AfterTriggerFireDeferred ( void  )

Definition at line 4577 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().

4578 {
4579  AfterTriggerEventList *events;
4580  bool snap_pushed = false;
4581 
4582  /* Must not be inside a query */
4584 
4585  /*
4586  * If there are any triggers to fire, make sure we have set a snapshot for
4587  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
4588  * can't assume ActiveSnapshot is valid on entry.)
4589  */
4590  events = &afterTriggers.events;
4591  if (events->head != NULL)
4592  {
4594  snap_pushed = true;
4595  }
4596 
4597  /*
4598  * Run all the remaining triggers. Loop until they are all gone, in case
4599  * some trigger queues more for us to do.
4600  */
4601  while (afterTriggerMarkEvents(events, NULL, false))
4602  {
4603  CommandId firing_id = afterTriggers.firing_counter++;
4604 
4605  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
4606  break; /* all fired */
4607  }
4608 
4609  /*
4610  * We don't bother freeing the event list, since it will go away anyway
4611  * (and more efficiently than via pfree) in AfterTriggerEndXact.
4612  */
4613 
4614  if (snap_pushed)
4616 }
uint32 CommandId
Definition: c.h:535
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:4088
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
CommandId firing_counter
Definition: trigger.c:3418
#define Assert(condition)
Definition: c.h:746
AfterTriggerEventChunk * head
Definition: trigger.c:3312
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:4016
AfterTriggerEventList events
Definition: trigger.c:3420
static AfterTriggersData afterTriggers
Definition: trigger.c:3463

◆ AfterTriggerPendingOnRel()

bool AfterTriggerPendingOnRel ( Oid  relid)

Definition at line 5268 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().

5269 {
5270  AfterTriggerEvent event;
5271  AfterTriggerEventChunk *chunk;
5272  int depth;
5273 
5274  /* Scan queued events */
5276  {
5277  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5278 
5279  /*
5280  * We can ignore completed events. (Even if a DONE flag is rolled
5281  * back by subxact abort, it's OK because the effects of the TRUNCATE
5282  * or whatever must get rolled back too.)
5283  */
5284  if (event->ate_flags & AFTER_TRIGGER_DONE)
5285  continue;
5286 
5287  if (evtshared->ats_relid == relid)
5288  return true;
5289  }
5290 
5291  /*
5292  * Also scan events queued by incomplete queries. This could only matter
5293  * if TRUNCATE/etc is executed by a function or trigger within an updating
5294  * query on the same relation, which is pretty perverse, but let's check.
5295  */
5296  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
5297  {
5299  {
5300  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5301 
5302  if (event->ate_flags & AFTER_TRIGGER_DONE)
5303  continue;
5304 
5305  if (evtshared->ats_relid == relid)
5306  return true;
5307  }
5308  }
5309 
5310  return false;
5311 }
TriggerFlags ate_flags
Definition: trigger.c:3263
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3238
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3325
AfterTriggersQueryData * query_stack
Definition: trigger.c:3424
#define GetTriggerSharedData(evt)
Definition: trigger.c:3288
AfterTriggerEventList events
Definition: trigger.c:3420
AfterTriggerEventList events
Definition: trigger.c:3435
static AfterTriggersData afterTriggers
Definition: trigger.c:3463

◆ AfterTriggerSetState()

void AfterTriggerSetState ( ConstraintsSetStmt stmt)

Definition at line 4953 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().

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

◆ CopyTriggerDesc()

TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 1801 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().

1802 {
1803  TriggerDesc *newdesc;
1804  Trigger *trigger;
1805  int i;
1806 
1807  if (trigdesc == NULL || trigdesc->numtriggers <= 0)
1808  return NULL;
1809 
1810  newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
1811  memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
1812 
1813  trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
1814  memcpy(trigger, trigdesc->triggers,
1815  trigdesc->numtriggers * sizeof(Trigger));
1816  newdesc->triggers = trigger;
1817 
1818  for (i = 0; i < trigdesc->numtriggers; i++)
1819  {
1820  trigger->tgname = pstrdup(trigger->tgname);
1821  if (trigger->tgnattr > 0)
1822  {
1823  int16 *newattr;
1824 
1825  newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
1826  memcpy(newattr, trigger->tgattr,
1827  trigger->tgnattr * sizeof(int16));
1828  trigger->tgattr = newattr;
1829  }
1830  if (trigger->tgnargs > 0)
1831  {
1832  char **newargs;
1833  int16 j;
1834 
1835  newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
1836  for (j = 0; j < trigger->tgnargs; j++)
1837  newargs[j] = pstrdup(trigger->tgargs[j]);
1838  trigger->tgargs = newargs;
1839  }
1840  if (trigger->tgqual)
1841  trigger->tgqual = pstrdup(trigger->tgqual);
1842  if (trigger->tgoldtable)
1843  trigger->tgoldtable = pstrdup(trigger->tgoldtable);
1844  if (trigger->tgnewtable)
1845  trigger->tgnewtable = pstrdup(trigger->tgnewtable);
1846  trigger++;
1847  }
1848 
1849  return newdesc;
1850 }
signed short int16
Definition: c.h:362
char * pstrdup(const char *in)
Definition: mcxt.c:1187
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:950
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 158 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().

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

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

Referenced by ATExecEnableDisableTrigger().

1472 {
1473  Relation tgrel;
1474  int nkeys;
1475  ScanKeyData keys[2];
1476  SysScanDesc tgscan;
1477  HeapTuple tuple;
1478  bool found;
1479  bool changed;
1480 
1481  /* Scan the relevant entries in pg_triggers */
1482  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1483 
1484  ScanKeyInit(&keys[0],
1485  Anum_pg_trigger_tgrelid,
1486  BTEqualStrategyNumber, F_OIDEQ,
1488  if (tgname)
1489  {
1490  ScanKeyInit(&keys[1],
1491  Anum_pg_trigger_tgname,
1492  BTEqualStrategyNumber, F_NAMEEQ,
1493  CStringGetDatum(tgname));
1494  nkeys = 2;
1495  }
1496  else
1497  nkeys = 1;
1498 
1499  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1500  NULL, nkeys, keys);
1501 
1502  found = changed = false;
1503 
1504  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1505  {
1506  Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1507 
1508  if (oldtrig->tgisinternal)
1509  {
1510  /* system trigger ... ok to process? */
1511  if (skip_system)
1512  continue;
1513  if (!superuser())
1514  ereport(ERROR,
1515  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1516  errmsg("permission denied: \"%s\" is a system trigger",
1517  NameStr(oldtrig->tgname))));
1518  }
1519 
1520  found = true;
1521 
1522  if (oldtrig->tgenabled != fires_when)
1523  {
1524  /* need to change this one ... make a copy to scribble on */
1525  HeapTuple newtup = heap_copytuple(tuple);
1526  Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1527 
1528  newtrig->tgenabled = fires_when;
1529 
1530  CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1531 
1532  heap_freetuple(newtup);
1533 
1534  changed = true;
1535  }
1536 
1537  InvokeObjectPostAlterHook(TriggerRelationId,
1538  oldtrig->oid, 0);
1539  }
1540 
1541  systable_endscan(tgscan);
1542 
1543  table_close(tgrel, RowExclusiveLock);
1544 
1545  if (tgname && !found)
1546  ereport(ERROR,
1547  (errcode(ERRCODE_UNDEFINED_OBJECT),
1548  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1549  tgname, RelationGetRelationName(rel))));
1550 
1551  /*
1552  * If we changed anything, broadcast a SI inval message to force each
1553  * backend (including our own!) to rebuild relation's relcache entry.
1554  * Otherwise they will fail to apply the change promptly.
1555  */
1556  if (changed)
1558 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
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
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:264
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:476
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
#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:821
#define NameStr(name)
Definition: c.h:623
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 2478 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().

2482 {
2483  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2484  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2485 
2486  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2487  (transition_capture && transition_capture->tcs_delete_old_table))
2488  {
2489  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2490  if (fdw_trigtuple == NULL)
2491  GetTupleForTrigger(estate,
2492  NULL,
2493  relinfo,
2494  tupleid,
2496  slot,
2497  NULL);
2498  else
2499  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2500 
2502  true, slot, NULL, NIL, NULL,
2503  transition_capture);
2504  }
2505 }
#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:2929
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
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:424
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:5338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:746

◆ ExecARInsertTriggers()

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

Definition at line 2248 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().

2251 {
2252  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2253 
2254  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2255  (transition_capture && transition_capture->tcs_insert_new_table))
2257  true, NULL, slot,
2258  recheckIndexes, NULL,
2259  transition_capture);
2260 }
bool trig_insert_after_row
Definition: reltrigger.h:57
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5338
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91

◆ ExecARUpdateTriggers()

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

Definition at line 2763 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().

2769 {
2770  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2771  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2772 
2773  ExecClearTuple(oldslot);
2774 
2775  if ((trigdesc && trigdesc->trig_update_after_row) ||
2776  (transition_capture &&
2777  (transition_capture->tcs_update_old_table ||
2778  transition_capture->tcs_update_new_table)))
2779  {
2780  /*
2781  * Note: if the UPDATE is converted into a DELETE+INSERT as part of
2782  * update-partition-key operation, then this function is also called
2783  * separately for DELETE and INSERT to capture transition table rows.
2784  * In such case, either old tuple or new tuple can be NULL.
2785  */
2786  if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
2787  GetTupleForTrigger(estate,
2788  NULL,
2789  relinfo,
2790  tupleid,
2792  oldslot,
2793  NULL);
2794  else if (fdw_trigtuple != NULL)
2795  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
2796 
2798  true, oldslot, newslot, recheckIndexes,
2799  GetAllUpdatedColumns(relinfo, estate),
2800  transition_capture);
2801  }
2802 }
#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:2929
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
void ExecForceStoreHeapTuple(HeapTuple tuple, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1439
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5338
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:79
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93

◆ ExecASDeleteTriggers()

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

Definition at line 2375 of file trigger.c.

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

Referenced by fireASTriggers().

2377 {
2378  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2379 
2380  if (trigdesc && trigdesc->trig_delete_after_statement)
2382  false, NULL, NULL, NIL, NULL, transition_capture);
2383 }
#define NIL
Definition: pg_list.h:65
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5338
bool trig_delete_after_statement
Definition: reltrigger.h:70

◆ ExecASInsertTriggers()

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

Definition at line 2161 of file trigger.c.

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

Referenced by CopyFrom(), and fireASTriggers().

2163 {
2164  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2165 
2166  if (trigdesc && trigdesc->trig_insert_after_statement)
2168  false, NULL, NULL, NIL, NULL, transition_capture);
2169 }
#define NIL
Definition: pg_list.h:65
bool trig_insert_after_statement
Definition: reltrigger.h:60
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5338
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91

◆ ExecASTruncateTriggers()

void ExecASTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2918 of file trigger.c.

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

Referenced by ExecuteTruncateGuts().

2919 {
2920  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2921 
2922  if (trigdesc && trigdesc->trig_truncate_after_statement)
2924  false, NULL, NULL, NIL, NULL, NULL);
2925 }
#define NIL
Definition: pg_list.h:65
bool trig_truncate_after_statement
Definition: reltrigger.h:73
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5338
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:94

◆ ExecASUpdateTriggers()

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

Definition at line 2610 of file trigger.c.

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

Referenced by fireASTriggers().

2612 {
2613  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2614 
2615  if (trigdesc && trigdesc->trig_update_after_statement)
2617  false, NULL, NULL, NIL,
2618  GetAllUpdatedColumns(relinfo, estate),
2619  transition_capture);
2620 }
#define NIL
Definition: pg_list.h:65
bool trig_update_after_statement
Definition: reltrigger.h:65
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:5338
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:79
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93

◆ ExecBRDeleteTriggers()

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

Definition at line 2393 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().

2398 {
2399  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2400  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2401  bool result = true;
2402  TriggerData LocTriggerData = {0};
2403  HeapTuple trigtuple;
2404  bool should_free = false;
2405  int i;
2406 
2407  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2408  if (fdw_trigtuple == NULL)
2409  {
2410  TupleTableSlot *epqslot_candidate = NULL;
2411 
2412  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2413  LockTupleExclusive, slot, &epqslot_candidate))
2414  return false;
2415 
2416  /*
2417  * If the tuple was concurrently updated and the caller of this
2418  * function requested for the updated tuple, skip the trigger
2419  * execution.
2420  */
2421  if (epqslot_candidate != NULL && epqslot != NULL)
2422  {
2423  *epqslot = epqslot_candidate;
2424  return false;
2425  }
2426 
2427  trigtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2428 
2429  }
2430  else
2431  {
2432  trigtuple = fdw_trigtuple;
2433  ExecForceStoreHeapTuple(trigtuple, slot, false);
2434  }
2435 
2436  LocTriggerData.type = T_TriggerData;
2437  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2440  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2441  for (i = 0; i < trigdesc->numtriggers; i++)
2442  {
2443  HeapTuple newtuple;
2444  Trigger *trigger = &trigdesc->triggers[i];
2445 
2446  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2447  TRIGGER_TYPE_ROW,
2448  TRIGGER_TYPE_BEFORE,
2449  TRIGGER_TYPE_DELETE))
2450  continue;
2451  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2452  NULL, slot, NULL))
2453  continue;
2454 
2455  LocTriggerData.tg_trigslot = slot;
2456  LocTriggerData.tg_trigtuple = trigtuple;
2457  LocTriggerData.tg_trigger = trigger;
2458  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2459  i,
2460  relinfo->ri_TrigFunctions,
2461  relinfo->ri_TrigInstrument,
2462  GetPerTupleMemoryContext(estate));
2463  if (newtuple == NULL)
2464  {
2465  result = false; /* tell caller to suppress delete */
2466  break;
2467  }
2468  if (newtuple != trigtuple)
2469  heap_freetuple(newtuple);
2470  }
2471  if (should_free)
2472  heap_freetuple(trigtuple);
2473 
2474  return result;
2475 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:2929
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
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:99
Trigger * triggers
Definition: reltrigger.h:49
HeapTuple ExecFetchSlotHeapTuple(TupleTableSlot *slot, bool materialize, bool *shouldFree)
Definition: execTuples.c:1614
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:746
TriggerEvent tg_event
Definition: trigger.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:511
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:2018
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecBRInsertTriggers()

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

Definition at line 2172 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().

2174 {
2175  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2176  HeapTuple newtuple = NULL;
2177  bool should_free;
2178  TriggerData LocTriggerData = {0};
2179  int i;
2180 
2181  LocTriggerData.type = T_TriggerData;
2182  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2185  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2186  for (i = 0; i < trigdesc->numtriggers; i++)
2187  {
2188  Trigger *trigger = &trigdesc->triggers[i];
2189  HeapTuple oldtuple;
2190 
2191  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2192  TRIGGER_TYPE_ROW,
2193  TRIGGER_TYPE_BEFORE,
2194  TRIGGER_TYPE_INSERT))
2195  continue;
2196  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2197  NULL, NULL, slot))
2198  continue;
2199 
2200  if (!newtuple)
2201  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2202 
2203  LocTriggerData.tg_trigslot = slot;
2204  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2205  LocTriggerData.tg_trigger = trigger;
2206  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2207  i,
2208  relinfo->ri_TrigFunctions,
2209  relinfo->ri_TrigInstrument,
2210  GetPerTupleMemoryContext(estate));
2211  if (newtuple == NULL)
2212  {
2213  if (should_free)
2214  heap_freetuple(oldtuple);
2215  return false; /* "do nothing" */
2216  }
2217  else if (newtuple != oldtuple)
2218  {
2219  ExecForceStoreHeapTuple(newtuple, slot, false);
2220 
2221  /*
2222  * After a tuple in a partition goes through a trigger, the user
2223  * could have changed the partition key enough that the tuple no
2224  * longer fits the partition. Verify that.
2225  */
2226  if (trigger->tgisclone &&
2227  !ExecPartitionCheck(relinfo, slot, estate, false))
2228  ereport(ERROR,
2229  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2230  errmsg("moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported"),
2231  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2232  trigger->tgname,
2235 
2236  if (should_free)
2237  heap_freetuple(oldtuple);
2238 
2239  /* signal tuple should be re-fetched if used */
2240  newtuple = NULL;
2241  }
2242  }
2243 
2244  return true;
2245 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
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:99
Trigger * triggers
Definition: reltrigger.h:49
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
int errdetail(const char *fmt,...)
Definition: elog.c:954
#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:424
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:511
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
NodeTag type
Definition: trigger.h:32
int i
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1679
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2018
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
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 2623 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().

2628 {
2629  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2630  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2631  HeapTuple newtuple = NULL;
2632  HeapTuple trigtuple;
2633  bool should_free_trig = false;
2634  bool should_free_new = false;
2635  TriggerData LocTriggerData = {0};
2636  int i;
2637  Bitmapset *updatedCols;
2638  LockTupleMode lockmode;
2639 
2640  /* Determine lock mode to use */
2641  lockmode = ExecUpdateLockMode(estate, relinfo);
2642 
2643  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2644  if (fdw_trigtuple == NULL)
2645  {
2646  TupleTableSlot *epqslot_candidate = NULL;
2647 
2648  /* get a copy of the on-disk tuple we are planning to update */
2649  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2650  lockmode, oldslot, &epqslot_candidate))
2651  return false; /* cancel the update action */
2652 
2653  /*
2654  * In READ COMMITTED isolation level it's possible that target tuple
2655  * was changed due to concurrent update. In that case we have a raw
2656  * subplan output tuple in epqslot_candidate, and need to run it
2657  * through the junk filter to produce an insertable tuple.
2658  *
2659  * Caution: more than likely, the passed-in slot is the same as the
2660  * junkfilter's output slot, so we are clobbering the original value
2661  * of slottuple by doing the filtering. This is OK since neither we
2662  * nor our caller have any more interest in the prior contents of that
2663  * slot.
2664  */
2665  if (epqslot_candidate != NULL)
2666  {
2667  TupleTableSlot *epqslot_clean;
2668 
2669  epqslot_clean = ExecFilterJunk(relinfo->ri_junkFilter, epqslot_candidate);
2670 
2671  if (newslot != epqslot_clean)
2672  ExecCopySlot(newslot, epqslot_clean);
2673  }
2674 
2675  trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
2676  }
2677  else
2678  {
2679  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
2680  trigtuple = fdw_trigtuple;
2681  }
2682 
2683  LocTriggerData.type = T_TriggerData;
2684  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2687  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2688  updatedCols = GetAllUpdatedColumns(relinfo, estate);
2689  LocTriggerData.tg_updatedcols = updatedCols;
2690  for (i = 0; i < trigdesc->numtriggers; i++)
2691  {
2692  Trigger *trigger = &trigdesc->triggers[i];
2693  HeapTuple oldtuple;
2694 
2695  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2696  TRIGGER_TYPE_ROW,
2697  TRIGGER_TYPE_BEFORE,
2698  TRIGGER_TYPE_UPDATE))
2699  continue;
2700  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2701  updatedCols, oldslot, newslot))
2702  continue;
2703 
2704  if (!newtuple)
2705  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
2706 
2707  LocTriggerData.tg_trigslot = oldslot;
2708  LocTriggerData.tg_trigtuple = trigtuple;
2709  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2710  LocTriggerData.tg_newslot = newslot;
2711  LocTriggerData.tg_trigger = trigger;
2712  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2713  i,
2714  relinfo->ri_TrigFunctions,
2715  relinfo->ri_TrigInstrument,
2716  GetPerTupleMemoryContext(estate));
2717 
2718  if (newtuple == NULL)
2719  {
2720  if (should_free_trig)
2721  heap_freetuple(trigtuple);
2722  if (should_free_new)
2723  heap_freetuple(oldtuple);
2724  return false; /* "do nothing" */
2725  }
2726  else if (newtuple != oldtuple)
2727  {
2728  ExecForceStoreHeapTuple(newtuple, newslot, false);
2729 
2730  if (trigger->tgisclone &&
2731  !ExecPartitionCheck(relinfo, newslot, estate, false))
2732  ereport(ERROR,
2733  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2734  errmsg("moving row to another partition during a BEFORE trigger is not supported"),
2735  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2736  trigger->tgname,
2739 
2740  /*
2741  * If the tuple returned by the trigger / being stored, is the old
2742  * row version, and the heap tuple passed to the trigger was
2743  * allocated locally, materialize the slot. Otherwise we might
2744  * free it while still referenced by the slot.
2745  */
2746  if (should_free_trig && newtuple == trigtuple)
2747  ExecMaterializeSlot(newslot);
2748 
2749  if (should_free_new)
2750  heap_freetuple(oldtuple);
2751 
2752  /* signal tuple should be re-fetched if used */
2753  newtuple = NULL;
2754  }
2755  }
2756  if (should_free_trig)
2757  heap_freetuple(trigtuple);
2758 
2759  return true;
2760 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
JunkFilter * ri_junkFilter
Definition: execnodes.h:465
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
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:3045
static bool GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot *oldslot, TupleTableSlot **newSlot)
Definition: trigger.c:2929
const Bitmapset * tg_updatedcols
Definition: trigger.h:42
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
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:99
Trigger * triggers
Definition: reltrigger.h:49
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
int errdetail(const char *fmt,...)
Definition: elog.c:954
#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:424
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:746
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2217
#define GetAllUpdatedColumns(relinfo, estate)
Definition: trigger.c:79
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:511
int errmsg(const char *fmt,...)
Definition: elog.c:821
NodeTag type
Definition: trigger.h:32
int i
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1679
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2018
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34
#define RelationGetNamespace(relation)
Definition: rel.h:497

◆ ExecBSDeleteTriggers()

void ExecBSDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2324 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().

2325 {
2326  TriggerDesc *trigdesc;
2327  int i;
2328  TriggerData LocTriggerData = {0};
2329 
2330  trigdesc = relinfo->ri_TrigDesc;
2331 
2332  if (trigdesc == NULL)
2333  return;
2334  if (!trigdesc->trig_delete_before_statement)
2335  return;
2336 
2337  /* no-op if we already fired BS triggers in this context */
2339  CMD_DELETE))
2340  return;
2341 
2342  LocTriggerData.type = T_TriggerData;
2343  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2345  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2346  for (i = 0; i < trigdesc->numtriggers; i++)
2347  {
2348  Trigger *trigger = &trigdesc->triggers[i];
2349  HeapTuple newtuple;
2350 
2351  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2352  TRIGGER_TYPE_STATEMENT,
2353  TRIGGER_TYPE_BEFORE,
2354  TRIGGER_TYPE_DELETE))
2355  continue;
2356  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2357  NULL, NULL, NULL))
2358  continue;
2359 
2360  LocTriggerData.tg_trigger = trigger;
2361  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2362  i,
2363  relinfo->ri_TrigFunctions,
2364  relinfo->ri_TrigInstrument,
2365  GetPerTupleMemoryContext(estate));
2366 
2367  if (newtuple)
2368  ereport(ERROR,
2369  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2370  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2371  }
2372 }
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
int errcode(int sqlerrcode)
Definition: elog.c:610
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5671
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
bool trig_delete_before_statement
Definition: reltrigger.h:69
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:511
int errmsg(const char *fmt,...)
Definition: elog.c:821
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:2018
#define RelationGetRelid(relation)
Definition: rel.h:456
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSInsertTriggers()

void ExecBSInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2110 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().

2111 {
2112  TriggerDesc *trigdesc;
2113  int i;
2114  TriggerData LocTriggerData = {0};
2115 
2116  trigdesc = relinfo->ri_TrigDesc;
2117 
2118  if (trigdesc == NULL)
2119  return;
2120  if (!trigdesc->trig_insert_before_statement)
2121  return;
2122 
2123  /* no-op if we already fired BS triggers in this context */
2125  CMD_INSERT))
2126  return;
2127 
2128  LocTriggerData.type = T_TriggerData;
2129  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2131  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2132  for (i = 0; i < trigdesc->numtriggers; i++)
2133  {
2134  Trigger *trigger = &trigdesc->triggers[i];
2135  HeapTuple newtuple;
2136 
2137  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2138  TRIGGER_TYPE_STATEMENT,
2139  TRIGGER_TYPE_BEFORE,
2140  TRIGGER_TYPE_INSERT))
2141  continue;
2142  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2143  NULL, NULL, NULL))
2144  continue;
2145 
2146  LocTriggerData.tg_trigger = trigger;
2147  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2148  i,
2149  relinfo->ri_TrigFunctions,
2150  relinfo->ri_TrigInstrument,
2151  GetPerTupleMemoryContext(estate));
2152 
2153  if (newtuple)
2154  ereport(ERROR,
2155  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2156  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2157  }
2158 }
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
int errcode(int sqlerrcode)
Definition: elog.c:610
static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType)
Definition: trigger.c:5671
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:511
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
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:2018
#define RelationGetRelid(relation)
Definition: rel.h:456
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSTruncateTriggers()

void ExecBSTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2871 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().

2872 {
2873  TriggerDesc *trigdesc;
2874  int i;
2875  TriggerData LocTriggerData = {0};
2876 
2877  trigdesc = relinfo->ri_TrigDesc;
2878 
2879  if (trigdesc == NULL)
2880  return;
2881  if (!trigdesc->trig_truncate_before_statement)
2882  return;
2883 
2884  LocTriggerData.type = T_TriggerData;
2885  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
2887  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2888 
2889  for (i = 0; i < trigdesc->numtriggers; i++)
2890  {
2891  Trigger *trigger = &trigdesc->triggers[i];
2892  HeapTuple newtuple;
2893 
2894  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2895  TRIGGER_TYPE_STATEMENT,
2896  TRIGGER_TYPE_BEFORE,
2897  TRIGGER_TYPE_TRUNCATE))
2898  continue;
2899  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2900  NULL, NULL, NULL))
2901  continue;
2902 
2903  LocTriggerData.tg_trigger = trigger;
2904  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2905  i,
2906  relinfo->ri_TrigFunctions,
2907  relinfo->ri_TrigInstrument,
2908  GetPerTupleMemoryContext(estate));
2909 
2910  if (newtuple)
2911  ereport(ERROR,
2912  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2913  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2914  }
2915 }
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
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:99
Trigger * triggers
Definition: reltrigger.h:49
bool trig_truncate_before_statement
Definition: reltrigger.h:72
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:94
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:511
int errmsg(const char *fmt,...)
Definition: elog.c:821
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:2018
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecBSUpdateTriggers()

void ExecBSUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2555 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().

2556 {
2557  TriggerDesc *trigdesc;
2558  int i;
2559  TriggerData LocTriggerData = {0};
2560  Bitmapset *updatedCols;
2561 
2562  trigdesc = relinfo->ri_TrigDesc;
2563 
2564  if (trigdesc == NULL)
2565  return;
2566  if (!trigdesc->trig_update_before_statement)
2567  return;
2568 
2569  /* no-op if we already fired BS triggers in this context */
2571  CMD_UPDATE))
2572  return;
2573 
2574  updatedCols = GetAllUpdatedColumns(relinfo, estate);
2575 
2576  LocTriggerData.type = T_TriggerData;
2577  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2579  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2580  LocTriggerData.tg_updatedcols = updatedCols;
2581  for (i = 0; i < trigdesc->numtriggers; i++)
2582  {
2583  Trigger *trigger = &trigdesc->triggers[i];
2584  HeapTuple newtuple;
2585 
2586  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2587  TRIGGER_TYPE_STATEMENT,
2588  TRIGGER_TYPE_BEFORE,
2589  TRIGGER_TYPE_UPDATE))
2590  continue;
2591  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2592  updatedCols, NULL, NULL))
2593  continue;
2594 
2595  LocTriggerData.tg_trigger = trigger;
2596  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2597  i,
2598  relinfo->ri_TrigFunctions,
2599  relinfo->ri_TrigInstrument,
2600  GetPerTupleMemoryContext(estate));
2601 
2602  if (newtuple)
2603  ereport(ERROR,
2604  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2605  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2606  }
2607 }
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
const Bitmapset * tg_updatedcols
Definition: trigger.h:42
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
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:5671
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:99
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:79
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:93
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:511
int errmsg(const char *fmt,...)
Definition: elog.c:821
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:2018
#define RelationGetRelid(relation)
Definition: rel.h:456
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRDeleteTriggers()

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

Definition at line 2508 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().

2510 {
2511  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2512  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2513  TriggerData LocTriggerData = {0};
2514  int i;
2515 
2516  LocTriggerData.type = T_TriggerData;
2517  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2520  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2521 
2522  ExecForceStoreHeapTuple(trigtuple, slot, false);
2523 
2524  for (i = 0; i < trigdesc->numtriggers; i++)
2525  {
2526  HeapTuple rettuple;
2527  Trigger *trigger = &trigdesc->triggers[i];
2528 
2529  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2530  TRIGGER_TYPE_ROW,
2531  TRIGGER_TYPE_INSTEAD,
2532  TRIGGER_TYPE_DELETE))
2533  continue;
2534  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2535  NULL, slot, NULL))
2536  continue;
2537 
2538  LocTriggerData.tg_trigslot = slot;
2539  LocTriggerData.tg_trigtuple = trigtuple;
2540  LocTriggerData.tg_trigger = trigger;
2541  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2542  i,
2543  relinfo->ri_TrigFunctions,
2544  relinfo->ri_TrigInstrument,
2545  GetPerTupleMemoryContext(estate));
2546  if (rettuple == NULL)
2547  return false; /* Delete was suppressed */
2548  if (rettuple != trigtuple)
2549  heap_freetuple(rettuple);
2550  }
2551  return true;
2552 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:92
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
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:101
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:49
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
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:511
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:2018
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRInsertTriggers()

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

Definition at line 2263 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().

2265 {
2266  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2267  HeapTuple newtuple = NULL;
2268  bool should_free;
2269  TriggerData LocTriggerData = {0};
2270  int i;
2271 
2272  LocTriggerData.type = T_TriggerData;
2273  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2276  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2277  for (i = 0; i < trigdesc->numtriggers; i++)
2278  {
2279  Trigger *trigger = &trigdesc->triggers[i];
2280  HeapTuple oldtuple;
2281 
2282  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2283  TRIGGER_TYPE_ROW,
2284  TRIGGER_TYPE_INSTEAD,
2285  TRIGGER_TYPE_INSERT))
2286  continue;
2287  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2288  NULL, NULL, slot))
2289  continue;
2290 
2291  if (!newtuple)
2292  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2293 
2294  LocTriggerData.tg_trigslot = slot;
2295  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2296  LocTriggerData.tg_trigger = trigger;
2297  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2298  i,
2299  relinfo->ri_TrigFunctions,
2300  relinfo->ri_TrigInstrument,
2301  GetPerTupleMemoryContext(estate));
2302  if (newtuple == NULL)
2303  {
2304  if (should_free)
2305  heap_freetuple(oldtuple);
2306  return false; /* "do nothing" */
2307  }
2308  else if (newtuple != oldtuple)
2309  {
2310  ExecForceStoreHeapTuple(newtuple, slot, false);
2311 
2312  if (should_free)
2313  heap_freetuple(oldtuple);
2314 
2315  /* signal tuple should be re-fetched if used */
2316  newtuple = NULL;
2317  }
2318  }
2319 
2320  return true;
2321 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
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:101
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:424
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:511
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:91
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:2018
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ ExecIRUpdateTriggers()

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

Definition at line 2805 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().

2807 {
2808  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2809  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2810  HeapTuple newtuple = NULL;
2811  bool should_free;
2812  TriggerData LocTriggerData = {0};
2813  int i;
2814 
2815  LocTriggerData.type = T_TriggerData;
2816  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2819  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2820 
2821  ExecForceStoreHeapTuple(trigtuple, oldslot, false);
2822 
2823  for (i = 0; i < trigdesc->numtriggers; i++)
2824  {
2825  Trigger *trigger = &trigdesc->triggers[i];
2826  HeapTuple oldtuple;
2827 
2828  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2829  TRIGGER_TYPE_ROW,
2830  TRIGGER_TYPE_INSTEAD,
2831  TRIGGER_TYPE_UPDATE))
2832  continue;
2833  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2834  NULL, oldslot, newslot))
2835  continue;
2836 
2837  if (!newtuple)
2838  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
2839 
2840  LocTriggerData.tg_trigslot = oldslot;
2841  LocTriggerData.tg_trigtuple = trigtuple;
2842  LocTriggerData.tg_newslot = newslot;
2843  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2844 
2845  LocTriggerData.tg_trigger = trigger;
2846  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2847  i,
2848  relinfo->ri_TrigFunctions,
2849  relinfo->ri_TrigInstrument,
2850  GetPerTupleMemoryContext(estate));
2851  if (newtuple == NULL)
2852  {
2853  return false; /* "do nothing" */
2854  }
2855  else if (newtuple != oldtuple)
2856  {
2857  ExecForceStoreHeapTuple(newtuple, newslot, false);
2858 
2859  if (should_free)
2860  heap_freetuple(oldtuple);
2861 
2862  /* signal tuple should be re-fetched if used */
2863  newtuple = NULL;
2864  }
2865  }
2866 
2867  return true;
2868 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:97
TupleTableSlot * tg_trigslot
Definition: trigger.h:38
Relation ri_RelationDesc
Definition: execnodes.h:412
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, TupleTableSlot *oldslot, TupleTableSlot *newslot)
Definition: trigger.c:3045
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:433
TupleTableSlot * ExecGetTriggerOldSlot(EState *estate, ResultRelInfo *relInfo)
Definition: execUtils.c:1165
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:101
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:424
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:93
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:511
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:2018
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:427
Relation tg_relation
Definition: trigger.h:34

◆ FindTriggerIncompatibleWithInheritance()

const char* FindTriggerIncompatibleWithInheritance ( TriggerDesc trigdesc)

Definition at line 1988 of file trigger.c.

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

Referenced by ATExecAddInherit(), and ATExecAttachPartition().

1989 {
1990  if (trigdesc != NULL)
1991  {
1992  int i;
1993 
1994  for (i = 0; i < trigdesc->numtriggers; ++i)
1995  {
1996  Trigger *trigger = &trigdesc->triggers[i];
1997 
1998  if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
1999  return trigger->tgname;
2000  }
2001  }
2002 
2003  return NULL;
2004 }
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 1856 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().

1857 {
1858  Trigger *trigger;
1859  int i;
1860 
1861  if (trigdesc == NULL)
1862  return;
1863 
1864  trigger = trigdesc->triggers;
1865  for (i = 0; i < trigdesc->numtriggers; i++)
1866  {
1867  pfree(trigger->tgname);
1868  if (trigger->tgnattr > 0)
1869  pfree(trigger->tgattr);
1870  if (trigger->tgnargs > 0)
1871  {
1872  while (--(trigger->tgnargs) >= 0)
1873  pfree(trigger->tgargs[trigger->tgnargs]);
1874  pfree(trigger->tgargs);
1875  }
1876  if (trigger->tgqual)
1877  pfree(trigger->tgqual);
1878  if (trigger->tgoldtable)
1879  pfree(trigger->tgoldtable);
1880  if (trigger->tgnewtable)
1881  pfree(trigger->tgnewtable);
1882  trigger++;
1883  }
1884  pfree(trigdesc->triggers);
1885  pfree(trigdesc);
1886 }
void pfree(void *pointer)
Definition: mcxt.c:1057
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 1240 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().

1241 {
1242  Relation tgrel;
1243  ScanKeyData skey[2];
1244  SysScanDesc tgscan;
1245  HeapTuple tup;
1246  Oid oid;
1247 
1248  /*
1249  * Find the trigger, verify permissions, set up object address
1250  */
1251  tgrel = table_open(TriggerRelationId, AccessShareLock);
1252 
1253  ScanKeyInit(&skey[0],
1254  Anum_pg_trigger_tgrelid,
1255  BTEqualStrategyNumber, F_OIDEQ,
1256  ObjectIdGetDatum(relid));
1257  ScanKeyInit(&skey[1],
1258  Anum_pg_trigger_tgname,
1259  BTEqualStrategyNumber, F_NAMEEQ,
1260  CStringGetDatum(trigname));
1261 
1262  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1263  NULL, 2, skey);
1264 
1265  tup = systable_getnext(tgscan);
1266 
1267  if (!HeapTupleIsValid(tup))
1268  {
1269  if (!missing_ok)
1270  ereport(ERROR,
1271  (errcode(ERRCODE_UNDEFINED_OBJECT),
1272  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1273  trigname, get_rel_name(relid))));
1274  oid = InvalidOid;
1275  }
1276  else
1277  {
1278  oid = ((Form_pg_trigger) GETSTRUCT(tup))->oid;
1279  }
1280 
1281  systable_endscan(tgscan);
1282  table_close(tgrel, AccessShareLock);
1283  return oid;
1284 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
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:264
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:821
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 4291 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().

4292 {
4294  bool need_old,
4295  need_new;
4296  AfterTriggersTableData *table;
4297  MemoryContext oldcxt;
4298  ResourceOwner saveResourceOwner;
4299 
4300  if (trigdesc == NULL)
4301  return NULL;
4302 
4303  /* Detect which table(s) we need. */
4304  switch (cmdType)
4305  {
4306  case CMD_INSERT:
4307  need_old = false;
4308  need_new = trigdesc->trig_insert_new_table;
4309  break;
4310  case CMD_UPDATE:
4311  need_old = trigdesc->trig_update_old_table;
4312  need_new = trigdesc->trig_update_new_table;
4313  break;
4314  case CMD_DELETE:
4315  need_old = trigdesc->trig_delete_old_table;
4316  need_new = false;
4317  break;
4318  default:
4319  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4320  need_old = need_new = false; /* keep compiler quiet */
4321  break;
4322  }
4323  if (!need_old && !need_new)
4324  return NULL;
4325 
4326  /* Check state, like AfterTriggerSaveEvent. */
4327  if (afterTriggers.query_depth < 0)
4328  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4329 
4330  /* Be sure we have enough space to record events at this query depth. */
4333 
4334  /*
4335  * Find or create an AfterTriggersTableData struct to hold the
4336  * tuplestore(s). If there's a matching struct but it's marked closed,
4337  * ignore it; we need a newer one.
4338  *
4339  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4340  * allocated in the current (sub)transaction's CurTransactionContext, and
4341  * the tuplestores are managed by the (sub)transaction's resource owner.
4342  * This is sufficient lifespan because we do not allow triggers using
4343  * transition tables to be deferrable; they will be fired during
4344  * AfterTriggerEndQuery, after which it's okay to delete the data.
4345  */
4346  table = GetAfterTriggersTableData(relid, cmdType);
4347 
4348  /* Now create required tuplestore(s), if we don't have them already. */
4350  saveResourceOwner = CurrentResourceOwner;
4352 
4353  if (need_old && table->old_tuplestore == NULL)
4354  table->old_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4355  if (need_new && table->new_tuplestore == NULL)
4356  table->new_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4357 
4358  CurrentResourceOwner = saveResourceOwner;
4359  MemoryContextSwitchTo(oldcxt);
4360 
4361  /* Now build the TransitionCaptureState struct, in caller's context */
4363  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4364  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4365  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4366  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4367  state->tcs_private = table;
4368 
4369  return state;
4370 }
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:3458
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:80
#define ERROR
Definition: elog.h:43
static AfterTriggersTableData * GetAfterTriggersTableData(Oid relid, CmdType cmdType)
Definition: trigger.c:4232
bool trig_update_old_table
Definition: reltrigger.h:76
Tuplestorestate * new_tuplestore
Definition: trigger.c:3459
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
void * palloc0(Size size)
Definition: mcxt.c:981
int work_mem
Definition: globals.c:121
static void AfterTriggerEnlargeQueryState(void)
Definition: trigger.c:4831
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:3463

◆ RelationBuildTriggers()

void RelationBuildTriggers ( Relation  relation)

Definition at line 1572 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().

1573 {
1574  TriggerDesc *trigdesc;
1575  int numtrigs;
1576  int maxtrigs;
1577  Trigger *triggers;
1578  Relation tgrel;
1579  ScanKeyData skey;
1580  SysScanDesc tgscan;
1581  HeapTuple htup;
1582  MemoryContext oldContext;
1583  int i;
1584 
1585  /*
1586  * Allocate a working array to hold the triggers (the array is extended if
1587  * necessary)
1588  */
1589  maxtrigs = 16;
1590  triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
1591  numtrigs = 0;
1592 
1593  /*
1594  * Note: since we scan the triggers using TriggerRelidNameIndexId, we will
1595  * be reading the triggers in name order, except possibly during
1596  * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
1597  * ensures that triggers will be fired in name order.
1598  */
1599  ScanKeyInit(&skey,
1600  Anum_pg_trigger_tgrelid,
1601  BTEqualStrategyNumber, F_OIDEQ,
1602  ObjectIdGetDatum(RelationGetRelid(relation)));
1603 
1604  tgrel = table_open(TriggerRelationId, AccessShareLock);
1605  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1606  NULL, 1, &skey);
1607 
1608  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
1609  {
1610  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
1611  Trigger *build;
1612  Datum datum;
1613  bool isnull;
1614 
1615  if (numtrigs >= maxtrigs)
1616  {
1617  maxtrigs *= 2;
1618  triggers = (Trigger *) repalloc(triggers, maxtrigs * sizeof(Trigger));
1619  }
1620  build = &(triggers[numtrigs]);
1621 
1622  build->tgoid = pg_trigger->oid;
1624  NameGetDatum(&pg_trigger->tgname)));
1625  build->tgfoid = pg_trigger->tgfoid;
1626  build->tgtype = pg_trigger->tgtype;
1627  build->tgenabled = pg_trigger->tgenabled;
1628  build->tgisinternal = pg_trigger->tgisinternal;
1629  build->tgisclone = OidIsValid(pg_trigger->tgparentid);
1630  build->tgconstrrelid = pg_trigger->tgconstrrelid;
1631  build->tgconstrindid = pg_trigger->tgconstrindid;
1632  build->tgconstraint = pg_trigger->tgconstraint;
1633  build->tgdeferrable = pg_trigger->tgdeferrable;
1634  build->tginitdeferred = pg_trigger->tginitdeferred;
1635  build->tgnargs = pg_trigger->tgnargs;
1636  /* tgattr is first var-width field, so OK to access directly */
1637  build->tgnattr = pg_trigger->tgattr.dim1;
1638  if (build->tgnattr > 0)
1639  {
1640  build->tgattr = (int16 *) palloc(build->tgnattr * sizeof(int16));
1641  memcpy(build->tgattr, &(pg_trigger->tgattr.values),
1642  build->tgnattr * sizeof(int16));
1643  }
1644  else
1645  build->tgattr = NULL;
1646  if (build->tgnargs > 0)
1647  {
1648  bytea *val;
1649  char *p;
1650 
1651  val = DatumGetByteaPP(fastgetattr(htup,
1652  Anum_pg_trigger_tgargs,
1653  tgrel->rd_att, &isnull));
1654  if (isnull)
1655  elog(ERROR, "tgargs is null in trigger for relation \"%s\"",
1656  RelationGetRelationName(relation));
1657  p = (char *) VARDATA_ANY(val);
1658  build->tgargs = (char **) palloc(build->tgnargs * sizeof(char *));
1659  for (i = 0; i < build->