PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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
 

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
 

Functions

ObjectAddress CreateTrigger (CreateTrigStmt *stmt, const char *queryString, Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid, bool isInternal)
 
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)
 
void RelationBuildTriggers (Relation relation)
 
TriggerDescCopyTriggerDesc (TriggerDesc *trigdesc)
 
void FreeTriggerDesc (TriggerDesc *trigdesc)
 
void ExecBSInsertTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASInsertTriggers (EState *estate, ResultRelInfo *relinfo)
 
TupleTableSlotExecBRInsertTriggers (EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
 
void ExecARInsertTriggers (EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, List *recheckIndexes)
 
TupleTableSlotExecIRInsertTriggers (EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
 
void ExecBSDeleteTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASDeleteTriggers (EState *estate, ResultRelInfo *relinfo)
 
bool ExecBRDeleteTriggers (EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple)
 
void ExecARDeleteTriggers (EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple)
 
bool ExecIRDeleteTriggers (EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple)
 
void ExecBSUpdateTriggers (EState *estate, ResultRelInfo *relinfo)
 
void ExecASUpdateTriggers (EState *estate, ResultRelInfo *relinfo)
 
TupleTableSlotExecBRUpdateTriggers (EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, TupleTableSlot *slot)
 
void ExecARUpdateTriggers (EState *estate, ResultRelInfo *relinfo, ItemPointer tupleid, HeapTuple fdw_trigtuple, HeapTuple newtuple, List *recheckIndexes)
 
TupleTableSlotExecIRUpdateTriggers (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, HeapTuple old_row, HeapTuple new_row)
 
bool RI_FKey_fk_upd_check_required (Trigger *trigger, Relation fk_rel, HeapTuple old_row, HeapTuple new_row)
 
bool RI_Initial_Check (Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
int RI_FKey_trigger_type (Oid tgfoid)
 

Variables

PGDLLIMPORT int SessionReplicationRole
 

Macro Definition Documentation

#define AFTER_TRIGGER_DEFERRABLE   0x00000020

Definition at line 67 of file trigger.h.

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

#define AFTER_TRIGGER_INITDEFERRED   0x00000040

Definition at line 68 of file trigger.h.

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

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

Definition at line 210 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), and RI_FKey_trigger_type().

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

Definition at line 211 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), CreateTrigger(), and RI_FKey_trigger_type().

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

Definition at line 209 of file trigger.h.

Referenced by AfterTriggerSaveEvent(), and RI_FKey_trigger_type().

#define SESSION_REPLICATION_ROLE_LOCAL   2

Definition at line 102 of file trigger.h.

#define SESSION_REPLICATION_ROLE_ORIGIN   0

Definition at line 100 of file trigger.h.

#define SESSION_REPLICATION_ROLE_REPLICA   1

Definition at line 101 of file trigger.h.

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

#define TRIGGER_DISABLED   'D'

Definition at line 112 of file trigger.h.

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

#define TRIGGER_EVENT_AFTER   0x00000000

Definition at line 61 of file trigger.h.

#define TRIGGER_EVENT_DELETE   0x00000001
#define TRIGGER_EVENT_INSTEAD   0x00000010

Definition at line 62 of file trigger.h.

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

#define TRIGGER_EVENT_OPMASK   0x00000003

Definition at line 56 of file trigger.h.

Referenced by AfterTriggerExecute(), and AfterTriggerSaveEvent().

#define TRIGGER_EVENT_TIMINGMASK   0x00000018

Definition at line 63 of file trigger.h.

#define TRIGGER_EVENT_TRUNCATE   0x00000003

Definition at line 55 of file trigger.h.

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

#define TRIGGER_FIRED_BY_TRUNCATE (   event)    (((event) & TRIGGER_EVENT_OPMASK) == TRIGGER_EVENT_TRUNCATE)
#define TRIGGER_FIRED_FOR_STATEMENT (   event)    (!TRIGGER_FIRED_FOR_ROW(event))
#define TRIGGER_FIRED_INSTEAD (   event)    (((event) & TRIGGER_EVENT_TIMINGMASK) == TRIGGER_EVENT_INSTEAD)
#define TRIGGER_FIRES_ALWAYS   'A'

Definition at line 110 of file trigger.h.

Referenced by ATExecCmd().

#define TRIGGER_FIRES_ON_ORIGIN   'O'
#define TRIGGER_FIRES_ON_REPLICA   'R'

Definition at line 111 of file trigger.h.

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

Typedef Documentation

Definition at line 28 of file trigger.h.

Function Documentation

void AfterTriggerBeginQuery ( void  )

Definition at line 4157 of file trigger.c.

References AfterTriggersData::query_depth.

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

4158 {
4159  /* Increase the query stack depth */
4161 }
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
void AfterTriggerBeginSubXact ( void  )

Definition at line 4381 of file trigger.c.

References DEFTRIG_INITALLOC, AfterTriggersData::depth_stack, AfterTriggersData::events, AfterTriggersData::events_stack, AfterTriggersData::firing_counter, AfterTriggersData::firing_stack, GetCurrentTransactionNestLevel(), AfterTriggersData::maxtransdepth, MemoryContextSwitchTo(), NULL, palloc(), AfterTriggersData::query_depth, repalloc(), AfterTriggersData::state_stack, and TopTransactionContext.

Referenced by StartSubTransaction().

4382 {
4383  int my_level = GetCurrentTransactionNestLevel();
4384 
4385  /*
4386  * Allocate more space in the stacks if needed. (Note: because the
4387  * minimum nest level of a subtransaction is 2, we waste the first couple
4388  * entries of each array; not worth the notational effort to avoid it.)
4389  */
4390  while (my_level >= afterTriggers.maxtransdepth)
4391  {
4392  if (afterTriggers.maxtransdepth == 0)
4393  {
4394  MemoryContext old_cxt;
4395 
4397 
4398 #define DEFTRIG_INITALLOC 8
4403  afterTriggers.depth_stack = (int *)
4404  palloc(DEFTRIG_INITALLOC * sizeof(int));
4406  palloc(DEFTRIG_INITALLOC * sizeof(CommandId));
4408 
4409  MemoryContextSwitchTo(old_cxt);
4410  }
4411  else
4412  {
4413  /* repalloc will keep the stacks in the same context */
4414  int new_alloc = afterTriggers.maxtransdepth * 2;
4415 
4418  new_alloc * sizeof(SetConstraintState));
4421  new_alloc * sizeof(AfterTriggerEventList));
4422  afterTriggers.depth_stack = (int *)
4424  new_alloc * sizeof(int));
4427  new_alloc * sizeof(CommandId));
4428  afterTriggers.maxtransdepth = new_alloc;
4429  }
4430  }
4431 
4432  /*
4433  * Push the current information into the stack. The SET CONSTRAINTS state
4434  * is not saved until/unless changed. Likewise, we don't make a
4435  * per-subtransaction event context until needed.
4436  */
4437  afterTriggers.state_stack[my_level] = NULL;
4441 }
uint32 CommandId
Definition: c.h:411
MemoryContext TopTransactionContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define DEFTRIG_INITALLOC
CommandId * firing_stack
Definition: trigger.c:3407
SetConstraintState * state_stack
Definition: trigger.c:3404
CommandId firing_counter
Definition: trigger.c:3391
AfterTriggerEventList * events_stack
Definition: trigger.c:3405
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:761
#define NULL
Definition: c.h:229
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:963
void * palloc(Size size)
Definition: mcxt.c:849
AfterTriggerEventList events
Definition: trigger.c:3393
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
void AfterTriggerBeginXact ( void  )

Definition at line 4119 of file trigger.c.

References Assert, AfterTriggersData::depth_stack, AfterTriggersData::event_cxt, AfterTriggersData::events, AfterTriggersData::events_stack, AfterTriggersData::fdw_tuplestores, AfterTriggersData::firing_counter, AfterTriggersData::firing_stack, AfterTriggerEventList::head, AfterTriggersData::maxquerydepth, AfterTriggersData::maxtransdepth, AfterTriggersData::new_tuplestores, NULL, AfterTriggersData::old_tuplestores, AfterTriggersData::query_depth, AfterTriggersData::query_stack, AfterTriggersData::state, and AfterTriggersData::state_stack.

Referenced by StartTransaction().

4120 {
4121  /*
4122  * Initialize after-trigger state structure to empty
4123  */
4124  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4126 
4127  /*
4128  * Verify that there is no leftover state remaining. If these assertions
4129  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4130  * up properly.
4131  */
4145 }
uint32 CommandId
Definition: c.h:411
Tuplestorestate ** old_tuplestores
Definition: trigger.c:3397
CommandId * firing_stack
Definition: trigger.c:3407
SetConstraintState * state_stack
Definition: trigger.c:3404
SetConstraintState state
Definition: trigger.c:3392
CommandId firing_counter
Definition: trigger.c:3391
AfterTriggerEventList * events_stack
Definition: trigger.c:3405
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
AfterTriggerEventChunk * head
Definition: trigger.c:3313
MemoryContext event_cxt
Definition: trigger.c:3400
Tuplestorestate ** fdw_tuplestores
Definition: trigger.c:3396
AfterTriggerEventList events
Definition: trigger.c:3393
AfterTriggerEventList * query_stack
Definition: trigger.c:3395
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
Tuplestorestate ** new_tuplestores
Definition: trigger.c:3398
void AfterTriggerEndQuery ( EState estate)

Definition at line 4177 of file trigger.c.

References afterTriggerFreeEventList(), afterTriggerInvokeEvents(), afterTriggerMarkEvents(), Assert, AfterTriggersData::events, AfterTriggersData::fdw_tuplestores, AfterTriggersData::firing_counter, AfterTriggersData::maxquerydepth, AfterTriggersData::new_tuplestores, NULL, AfterTriggersData::old_tuplestores, AfterTriggersData::query_depth, AfterTriggersData::query_stack, and tuplestore_end().

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

4178 {
4179  AfterTriggerEventList *events;
4180  Tuplestorestate *fdw_tuplestore;
4181  Tuplestorestate *old_tuplestore;
4182  Tuplestorestate *new_tuplestore;
4183 
4184  /* Must be inside a query, too */
4186 
4187  /*
4188  * If we never even got as far as initializing the event stack, there
4189  * certainly won't be any events, so exit quickly.
4190  */
4192  {
4194  return;
4195  }
4196 
4197  /*
4198  * Process all immediate-mode triggers queued by the query, and move the
4199  * deferred ones to the main list of deferred events.
4200  *
4201  * Notice that we decide which ones will be fired, and put the deferred
4202  * ones on the main list, before anything is actually fired. This ensures
4203  * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
4204  * IMMEDIATE: all events we have decided to defer will be available for it
4205  * to fire.
4206  *
4207  * We loop in case a trigger queues more events at the same query level.
4208  * Ordinary trigger functions, including all PL/pgSQL trigger functions,
4209  * will instead fire any triggers in a dedicated query level. Foreign key
4210  * enforcement triggers do add to the current query level, thanks to their
4211  * passing fire_triggers = false to SPI_execute_snapshot(). Other
4212  * C-language triggers might do likewise. Be careful here: firing a
4213  * trigger could result in query_stack being repalloc'd, so we can't save
4214  * its address across afterTriggerInvokeEvents calls.
4215  *
4216  * If we find no firable events, we don't have to increment
4217  * firing_counter.
4218  */
4219  for (;;)
4220  {
4222  if (afterTriggerMarkEvents(events, &afterTriggers.events, true))
4223  {
4224  CommandId firing_id = afterTriggers.firing_counter++;
4225 
4226  /* OK to delete the immediate events after processing them */
4227  if (afterTriggerInvokeEvents(events, firing_id, estate, true))
4228  break; /* all fired */
4229  }
4230  else
4231  break;
4232  }
4233 
4234  /* Release query-local storage for events, including tuplestore if any */
4236  if (fdw_tuplestore)
4237  {
4238  tuplestore_end(fdw_tuplestore);
4240  }
4242  if (old_tuplestore)
4243  {
4244  tuplestore_end(old_tuplestore);
4246  }
4248  if (new_tuplestore)
4249  {
4250  tuplestore_end(new_tuplestore);
4252  }
4254 
4256 }
uint32 CommandId
Definition: c.h:411
Tuplestorestate ** old_tuplestores
Definition: trigger.c:3397
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:3974
static void afterTriggerFreeEventList(AfterTriggerEventList *events)
Definition: trigger.c:3637
CommandId firing_counter
Definition: trigger.c:3391
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:3902
Tuplestorestate ** fdw_tuplestores
Definition: trigger.c:3396
AfterTriggerEventList events
Definition: trigger.c:3393
AfterTriggerEventList * query_stack
Definition: trigger.c:3395
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
Tuplestorestate ** new_tuplestores
Definition: trigger.c:3398
void AfterTriggerEndSubXact ( bool  isCommit)

Definition at line 4449 of file trigger.c.

References AFTER_TRIGGER_DONE, AFTER_TRIGGER_IN_PROGRESS, afterTriggerFreeEventList(), afterTriggerRestoreEventList(), Assert, AfterTriggerEventData::ate_flags, AfterTriggerSharedData::ats_firing_id, AfterTriggersData::depth_stack, AfterTriggersData::events, AfterTriggersData::events_stack, AfterTriggersData::fdw_tuplestores, AfterTriggersData::firing_stack, for_each_event_chunk, GetCurrentTransactionNestLevel(), GetTriggerSharedData, AfterTriggersData::maxquerydepth, AfterTriggersData::maxtransdepth, AfterTriggersData::new_tuplestores, NULL, AfterTriggersData::old_tuplestores, pfree(), AfterTriggersData::query_depth, AfterTriggersData::query_stack, AfterTriggersData::state, AfterTriggersData::state_stack, and tuplestore_end().

Referenced by AbortSubTransaction(), and CommitSubTransaction().

4450 {
4451  int my_level = GetCurrentTransactionNestLevel();
4453  AfterTriggerEvent event;
4454  AfterTriggerEventChunk *chunk;
4455  CommandId subxact_firing_id;
4456 
4457  /*
4458  * Pop the prior state if needed.
4459  */
4460  if (isCommit)
4461  {
4462  Assert(my_level < afterTriggers.maxtransdepth);
4463  /* If we saved a prior state, we don't need it anymore */
4464  state = afterTriggers.state_stack[my_level];
4465  if (state != NULL)
4466  pfree(state);
4467  /* this avoids double pfree if error later: */
4468  afterTriggers.state_stack[my_level] = NULL;
4470  afterTriggers.depth_stack[my_level]);
4471  }
4472  else
4473  {
4474  /*
4475  * Aborting. It is possible subxact start failed before calling
4476  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
4477  * stack levels that aren't there.
4478  */
4479  if (my_level >= afterTriggers.maxtransdepth)
4480  return;
4481 
4482  /*
4483  * Release any event lists from queries being aborted, and restore
4484  * query_depth to its pre-subxact value. This assumes that a
4485  * subtransaction will not add events to query levels started in a
4486  * earlier transaction state.
4487  */
4489  {
4491  {
4492  Tuplestorestate *ts;
4493 
4495  if (ts)
4496  {
4497  tuplestore_end(ts);
4499  }
4501  if (ts)
4502  {
4503  tuplestore_end(ts);
4505  }
4507  if (ts)
4508  {
4509  tuplestore_end(ts);
4511  }
4512 
4514  }
4515 
4517  }
4519  afterTriggers.depth_stack[my_level]);
4520 
4521  /*
4522  * Restore the global deferred-event list to its former length,
4523  * discarding any events queued by the subxact.
4524  */
4526  &afterTriggers.events_stack[my_level]);
4527 
4528  /*
4529  * Restore the trigger state. If the saved state is NULL, then this
4530  * subxact didn't save it, so it doesn't need restoring.
4531  */
4532  state = afterTriggers.state_stack[my_level];
4533  if (state != NULL)
4534  {
4536  afterTriggers.state = state;
4537  }
4538  /* this avoids double pfree if error later: */
4539  afterTriggers.state_stack[my_level] = NULL;
4540 
4541  /*
4542  * Scan for any remaining deferred events that were marked DONE or IN
4543  * PROGRESS by this subxact or a child, and un-mark them. We can
4544  * recognize such events because they have a firing ID greater than or
4545  * equal to the firing_counter value we saved at subtransaction start.
4546  * (This essentially assumes that the current subxact includes all
4547  * subxacts started after it.)
4548  */
4549  subxact_firing_id = afterTriggers.firing_stack[my_level];
4551  {
4552  AfterTriggerShared evtshared = GetTriggerSharedData(event);
4553 
4554  if (event->ate_flags &
4556  {
4557  if (evtshared->ats_firing_id >= subxact_firing_id)
4558  event->ate_flags &=
4560  }
4561  }
4562  }
4563 }
uint32 CommandId
Definition: c.h:411
Tuplestorestate ** old_tuplestores
Definition: trigger.c:3397
TriggerFlags ate_flags
Definition: trigger.c:3264
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3241
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3326
CommandId * firing_stack
Definition: trigger.c:3407
#define GetTriggerSharedData(evt)
Definition: trigger.c:3289
void pfree(void *pointer)
Definition: mcxt.c:950
SetConstraintState * state_stack
Definition: trigger.c:3404
SetConstraintState state
Definition: trigger.c:3392
static void afterTriggerFreeEventList(AfterTriggerEventList *events)
Definition: trigger.c:3637
AfterTriggerEventList * events_stack
Definition: trigger.c:3405
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:761
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
Definition: regguts.h:298
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
static void afterTriggerRestoreEventList(AfterTriggerEventList *events, const AfterTriggerEventList *old_events)
Definition: trigger.c:3660
CommandId ats_firing_id
Definition: trigger.c:3257
#define AFTER_TRIGGER_IN_PROGRESS
Definition: trigger.c:3242
Tuplestorestate ** fdw_tuplestores
Definition: trigger.c:3396
AfterTriggerEventList events
Definition: trigger.c:3393
AfterTriggerEventList * query_stack
Definition: trigger.c:3395
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
Tuplestorestate ** new_tuplestores
Definition: trigger.c:3398
void AfterTriggerEndXact ( bool  isCommit)

Definition at line 4327 of file trigger.c.

References AfterTriggersData::depth_stack, AfterTriggersData::event_cxt, AfterTriggersData::events, AfterTriggersData::events_stack, AfterTriggersData::fdw_tuplestores, AfterTriggersData::firing_stack, AfterTriggerEventList::head, AfterTriggersData::maxquerydepth, AfterTriggersData::maxtransdepth, MemoryContextDelete(), AfterTriggersData::new_tuplestores, NULL, AfterTriggersData::old_tuplestores, AfterTriggersData::query_depth, AfterTriggersData::query_stack, AfterTriggersData::state, AfterTriggersData::state_stack, AfterTriggerEventList::tail, and AfterTriggerEventList::tailfree.

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

4328 {
4329  /*
4330  * Forget the pending-events list.
4331  *
4332  * Since all the info is in TopTransactionContext or children thereof, we
4333  * don't really need to do anything to reclaim memory. However, the
4334  * pending-events list could be large, and so it's useful to discard it as
4335  * soon as possible --- especially if we are aborting because we ran out
4336  * of memory for the list!
4337  */
4339  {
4345  }
4346 
4347  /*
4348  * Forget any subtransaction state as well. Since this can't be very
4349  * large, we let the eventual reset of TopTransactionContext free the
4350  * memory instead of doing it here.
4351  */
4357 
4358 
4359  /*
4360  * Forget the query stack and constraint-related state information. As
4361  * with the subtransaction state information, we don't bother freeing the
4362  * memory here.
4363  */
4370 
4371  /* No more afterTriggers manipulation until next transaction starts. */
4373 }
Tuplestorestate ** old_tuplestores
Definition: trigger.c:3397
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
AfterTriggerEventChunk * tail
Definition: trigger.c:3314
CommandId * firing_stack
Definition: trigger.c:3407
SetConstraintState * state_stack
Definition: trigger.c:3404
SetConstraintState state
Definition: trigger.c:3392
AfterTriggerEventList * events_stack
Definition: trigger.c:3405
#define NULL
Definition: c.h:229
AfterTriggerEventChunk * head
Definition: trigger.c:3313
MemoryContext event_cxt
Definition: trigger.c:3400
Tuplestorestate ** fdw_tuplestores
Definition: trigger.c:3396
AfterTriggerEventList events
Definition: trigger.c:3393
AfterTriggerEventList * query_stack
Definition: trigger.c:3395
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
Tuplestorestate ** new_tuplestores
Definition: trigger.c:3398
void AfterTriggerFireDeferred ( void  )

Definition at line 4271 of file trigger.c.

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

Referenced by CommitTransaction(), and PrepareTransaction().

4272 {
4273  AfterTriggerEventList *events;
4274  bool snap_pushed = false;
4275 
4276  /* Must not be inside a query */
4278 
4279  /*
4280  * If there are any triggers to fire, make sure we have set a snapshot for
4281  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
4282  * can't assume ActiveSnapshot is valid on entry.)
4283  */
4284  events = &afterTriggers.events;
4285  if (events->head != NULL)
4286  {
4288  snap_pushed = true;
4289  }
4290 
4291  /*
4292  * Run all the remaining triggers. Loop until they are all gone, in case
4293  * some trigger queues more for us to do.
4294  */
4295  while (afterTriggerMarkEvents(events, NULL, false))
4296  {
4297  CommandId firing_id = afterTriggers.firing_counter++;
4298 
4299  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
4300  break; /* all fired */
4301  }
4302 
4303  /*
4304  * We don't bother freeing the event list, since it will go away anyway
4305  * (and more efficiently than via pfree) in AfterTriggerEndXact.
4306  */
4307 
4308  if (snap_pushed)
4310 }
uint32 CommandId
Definition: c.h:411
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:3974
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
CommandId firing_counter
Definition: trigger.c:3391
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
AfterTriggerEventChunk * head
Definition: trigger.c:3313
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:3902
AfterTriggerEventList events
Definition: trigger.c:3393
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
bool AfterTriggerPendingOnRel ( Oid  relid)

Definition at line 5015 of file trigger.c.

References AFTER_TRIGGER_DONE, AfterTriggerEventData::ate_flags, AfterTriggerSharedData::ats_relid, AfterTriggersData::events, for_each_event_chunk, GetTriggerSharedData, AfterTriggersData::maxquerydepth, AfterTriggersData::query_depth, and AfterTriggersData::query_stack.

Referenced by CheckTableNotInUse().

5016 {
5017  AfterTriggerEvent event;
5018  AfterTriggerEventChunk *chunk;
5019  int depth;
5020 
5021  /* Scan queued events */
5023  {
5024  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5025 
5026  /*
5027  * We can ignore completed events. (Even if a DONE flag is rolled
5028  * back by subxact abort, it's OK because the effects of the TRUNCATE
5029  * or whatever must get rolled back too.)
5030  */
5031  if (event->ate_flags & AFTER_TRIGGER_DONE)
5032  continue;
5033 
5034  if (evtshared->ats_relid == relid)
5035  return true;
5036  }
5037 
5038  /*
5039  * Also scan events queued by incomplete queries. This could only matter
5040  * if TRUNCATE/etc is executed by a function or trigger within an updating
5041  * query on the same relation, which is pretty perverse, but let's check.
5042  */
5043  for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
5044  {
5045  for_each_event_chunk(event, chunk, afterTriggers.query_stack[depth])
5046  {
5047  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5048 
5049  if (event->ate_flags & AFTER_TRIGGER_DONE)
5050  continue;
5051 
5052  if (evtshared->ats_relid == relid)
5053  return true;
5054  }
5055  }
5056 
5057  return false;
5058 }
TriggerFlags ate_flags
Definition: trigger.c:3264
#define AFTER_TRIGGER_DONE
Definition: trigger.c:3241
#define for_each_event_chunk(eptr, cptr, evtlist)
Definition: trigger.c:3326
#define GetTriggerSharedData(evt)
Definition: trigger.c:3289
AfterTriggerEventList events
Definition: trigger.c:3393
AfterTriggerEventList * query_stack
Definition: trigger.c:3395
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
void AfterTriggerSetState ( ConstraintsSetStmt stmt)

Definition at line 4721 of file trigger.c.

References AccessShareLock, afterTriggerInvokeEvents(), afterTriggerMarkEvents(), SetConstraintStateData::all_isdeferred, SetConstraintStateData::all_isset, Anum_pg_constraint_conname, Anum_pg_constraint_connamespace, Anum_pg_trigger_tgconstraint, BTEqualStrategyNumber, RangeVar::catalogname, ConstraintNameNspIndexId, ConstraintRelationId, ConstraintsSetStmt::constraints, CStringGetDatum, ConstraintsSetStmt::deferred, elog, ereport, errcode(), errmsg(), ERROR, AfterTriggersData::events, fetch_search_path(), AfterTriggersData::firing_counter, get_database_name(), GetCurrentTransactionNestLevel(), GETSTRUCT, GetTransactionSnapshot(), heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, i, IsSubTransaction(), lappend_oid(), lfirst, lfirst_oid, list_free(), list_make1_oid, LookupExplicitNamespace(), MyDatabaseId, NIL, NULL, SetConstraintStateData::numstates, ObjectIdGetDatum, PopActiveSnapshot(), PushActiveSnapshot(), RangeVar::relname, ScanKeyInit(), RangeVar::schemaname, SetConstraintTriggerData::sct_tgisdeferred, SetConstraintTriggerData::sct_tgoid, SetConstraintStateAddItem(), SetConstraintStateCopy(), SetConstraintStateCreate(), AfterTriggersData::state, AfterTriggersData::state_stack, systable_beginscan(), systable_endscan(), systable_getnext(), TriggerConstraintIndexId, TriggerRelationId, and SetConstraintStateData::trigstates.

Referenced by standard_ProcessUtility().

4722 {
4723  int my_level = GetCurrentTransactionNestLevel();
4724 
4725  /* If we haven't already done so, initialize our state. */
4726  if (afterTriggers.state == NULL)
4728 
4729  /*
4730  * If in a subtransaction, and we didn't save the current state already,
4731  * save it so it can be restored if the subtransaction aborts.
4732  */
4733  if (my_level > 1 &&
4734  afterTriggers.state_stack[my_level] == NULL)
4735  {
4736  afterTriggers.state_stack[my_level] =
4738  }
4739 
4740  /*
4741  * Handle SET CONSTRAINTS ALL ...
4742  */
4743  if (stmt->constraints == NIL)
4744  {
4745  /*
4746  * Forget any previous SET CONSTRAINTS commands in this transaction.
4747  */
4749 
4750  /*
4751  * Set the per-transaction ALL state to known.
4752  */
4753  afterTriggers.state->all_isset = true;
4755  }
4756  else
4757  {
4758  Relation conrel;
4759  Relation tgrel;
4760  List *conoidlist = NIL;
4761  List *tgoidlist = NIL;
4762  ListCell *lc;
4763 
4764  /*
4765  * Handle SET CONSTRAINTS constraint-name [, ...]
4766  *
4767  * First, identify all the named constraints and make a list of their
4768  * OIDs. Since, unlike the SQL spec, we allow multiple constraints of
4769  * the same name within a schema, the specifications are not
4770  * necessarily unique. Our strategy is to target all matching
4771  * constraints within the first search-path schema that has any
4772  * matches, but disregard matches in schemas beyond the first match.
4773  * (This is a bit odd but it's the historical behavior.)
4774  */
4776 
4777  foreach(lc, stmt->constraints)
4778  {
4779  RangeVar *constraint = lfirst(lc);
4780  bool found;
4781  List *namespacelist;
4782  ListCell *nslc;
4783 
4784  if (constraint->catalogname)
4785  {
4786  if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
4787  ereport(ERROR,
4788  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4789  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
4790  constraint->catalogname, constraint->schemaname,
4791  constraint->relname)));
4792  }
4793 
4794  /*
4795  * If we're given the schema name with the constraint, look only
4796  * in that schema. If given a bare constraint name, use the
4797  * search path to find the first matching constraint.
4798  */
4799  if (constraint->schemaname)
4800  {
4801  Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
4802  false);
4803 
4804  namespacelist = list_make1_oid(namespaceId);
4805  }
4806  else
4807  {
4808  namespacelist = fetch_search_path(true);
4809  }
4810 
4811  found = false;
4812  foreach(nslc, namespacelist)
4813  {
4814  Oid namespaceId = lfirst_oid(nslc);
4815  SysScanDesc conscan;
4816  ScanKeyData skey[2];
4817  HeapTuple tup;
4818 
4819  ScanKeyInit(&skey[0],
4821  BTEqualStrategyNumber, F_NAMEEQ,
4822  CStringGetDatum(constraint->relname));
4823  ScanKeyInit(&skey[1],
4825  BTEqualStrategyNumber, F_OIDEQ,
4826  ObjectIdGetDatum(namespaceId));
4827 
4828  conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
4829  true, NULL, 2, skey);
4830 
4831  while (HeapTupleIsValid(tup = systable_getnext(conscan)))
4832  {
4834 
4835  if (con->condeferrable)
4836  conoidlist = lappend_oid(conoidlist,
4837  HeapTupleGetOid(tup));
4838  else if (stmt->deferred)
4839  ereport(ERROR,
4840  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4841  errmsg("constraint \"%s\" is not deferrable",
4842  constraint->relname)));
4843  found = true;
4844  }
4845 
4846  systable_endscan(conscan);
4847 
4848  /*
4849  * Once we've found a matching constraint we do not search
4850  * later parts of the search path.
4851  */
4852  if (found)
4853  break;
4854  }
4855 
4856  list_free(namespacelist);
4857 
4858  /*
4859  * Not found ?
4860  */
4861  if (!found)
4862  ereport(ERROR,
4863  (errcode(ERRCODE_UNDEFINED_OBJECT),
4864  errmsg("constraint \"%s\" does not exist",
4865  constraint->relname)));
4866  }
4867 
4868  heap_close(conrel, AccessShareLock);
4869 
4870  /*
4871  * Now, locate the trigger(s) implementing each of these constraints,
4872  * and make a list of their OIDs.
4873  */
4875 
4876  foreach(lc, conoidlist)
4877  {
4878  Oid conoid = lfirst_oid(lc);
4879  bool found;
4880  ScanKeyData skey;
4881  SysScanDesc tgscan;
4882  HeapTuple htup;
4883 
4884  found = false;
4885 
4886  ScanKeyInit(&skey,
4888  BTEqualStrategyNumber, F_OIDEQ,
4889  ObjectIdGetDatum(conoid));
4890 
4891  tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
4892  NULL, 1, &skey);
4893 
4894  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
4895  {
4896  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
4897 
4898  /*
4899  * Silently skip triggers that are marked as non-deferrable in
4900  * pg_trigger. This is not an error condition, since a
4901  * deferrable RI constraint may have some non-deferrable
4902  * actions.
4903  */
4904  if (pg_trigger->tgdeferrable)
4905  tgoidlist = lappend_oid(tgoidlist,
4906  HeapTupleGetOid(htup));
4907 
4908  found = true;
4909  }
4910 
4911  systable_endscan(tgscan);
4912 
4913  /* Safety check: a deferrable constraint should have triggers */
4914  if (!found)
4915  elog(ERROR, "no triggers found for constraint with OID %u",
4916  conoid);
4917  }
4918 
4919  heap_close(tgrel, AccessShareLock);
4920 
4921  /*
4922  * Now we can set the trigger states of individual triggers for this
4923  * xact.
4924  */
4925  foreach(lc, tgoidlist)
4926  {
4927  Oid tgoid = lfirst_oid(lc);
4929  bool found = false;
4930  int i;
4931 
4932  for (i = 0; i < state->numstates; i++)
4933  {
4934  if (state->trigstates[i].sct_tgoid == tgoid)
4935  {
4936  state->trigstates[i].sct_tgisdeferred = stmt->deferred;
4937  found = true;
4938  break;
4939  }
4940  }
4941  if (!found)
4942  {
4944  SetConstraintStateAddItem(state, tgoid, stmt->deferred);
4945  }
4946  }
4947  }
4948 
4949  /*
4950  * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
4951  * checks against that constraint must be made when the SET CONSTRAINTS
4952  * command is executed -- i.e. the effects of the SET CONSTRAINTS command
4953  * apply retroactively. We've updated the constraints state, so scan the
4954  * list of previously deferred events to fire any that have now become
4955  * immediate.
4956  *
4957  * Obviously, if this was SET ... DEFERRED then it can't have converted
4958  * any unfired events to immediate, so we need do nothing in that case.
4959  */
4960  if (!stmt->deferred)
4961  {
4963  bool snapshot_set = false;
4964 
4965  while (afterTriggerMarkEvents(events, NULL, true))
4966  {
4967  CommandId firing_id = afterTriggers.firing_counter++;
4968 
4969  /*
4970  * Make sure a snapshot has been established in case trigger
4971  * functions need one. Note that we avoid setting a snapshot if
4972  * we don't find at least one trigger that has to be fired now.
4973  * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
4974  * ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
4975  * at the start of a transaction it's not possible for any trigger
4976  * events to be queued yet.)
4977  */
4978  if (!snapshot_set)
4979  {
4981  snapshot_set = true;
4982  }
4983 
4984  /*
4985  * We can delete fired events if we are at top transaction level,
4986  * but we'd better not if inside a subtransaction, since the
4987  * subtransaction could later get rolled back.
4988  */
4989  if (afterTriggerInvokeEvents(events, firing_id, NULL,
4990  !IsSubTransaction()))
4991  break; /* all fired */
4992  }
4993 
4994  if (snapshot_set)
4996  }
4997 }
#define NIL
Definition: pg_list.h:69
uint32 CommandId
Definition: c.h:411
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:2743
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define Anum_pg_trigger_tgconstraint
Definition: pg_trigger.h:87
SetConstraintTriggerData trigstates[FLEXIBLE_ARRAY_MEMBER]
Definition: trigger.c:3201
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
static SetConstraintState SetConstraintStateAddItem(SetConstraintState state, Oid tgoid, bool tgisdeferred)
Definition: trigger.c:4691
static bool afterTriggerInvokeEvents(AfterTriggerEventList *events, CommandId firing_id, EState *estate, bool delete_ok)
Definition: trigger.c:3974
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
#define heap_close(r, l)
Definition: heapam.h:97
#define Anum_pg_constraint_conname
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
char * schemaname
Definition: primnodes.h:67
char * relname
Definition: primnodes.h:68
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
SetConstraintState * state_stack
Definition: trigger.c:3404
SetConstraintState state
Definition: trigger.c:3392
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
#define CStringGetDatum(X)
Definition: postgres.h:584
#define TriggerConstraintIndexId
Definition: indexing.h:247
#define ereport(elevel, rest)
Definition: elog.h:122
static SetConstraintState SetConstraintStateCreate(int numalloc)
Definition: trigger.c:4646
#define list_make1_oid(x1)
Definition: pg_list.h:151
Oid MyDatabaseId
Definition: globals.c:76
#define Anum_pg_constraint_connamespace
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
CommandId firing_counter
Definition: trigger.c:3391
#define ConstraintNameNspIndexId
Definition: indexing.h:124
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:761
FormData_pg_constraint * Form_pg_constraint
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
Definition: regguts.h:298
#define TriggerRelationId
Definition: pg_trigger.h:34
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:72
bool IsSubTransaction(void)
Definition: xact.c:4376
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
int i
static bool afterTriggerMarkEvents(AfterTriggerEventList *events, AfterTriggerEventList *move_list, bool immediate_only)
Definition: trigger.c:3902
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
AfterTriggerEventList events
Definition: trigger.c:3393
#define ConstraintRelationId
Definition: pg_constraint.h:29
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
Definition: pg_list.h:45
List * fetch_search_path(bool includeImplicit)
Definition: namespace.c:4074
static AfterTriggersData afterTriggers
Definition: trigger.c:3411
char * catalogname
Definition: primnodes.h:66
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define lfirst_oid(lc)
Definition: pg_list.h:108
static SetConstraintState SetConstraintStateCopy(SetConstraintState state)
Definition: trigger.c:4671
TriggerDesc* CopyTriggerDesc ( TriggerDesc trigdesc)

Definition at line 1833 of file trigger.c.

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

1834 {
1835  TriggerDesc *newdesc;
1836  Trigger *trigger;
1837  int i;
1838 
1839  if (trigdesc == NULL || trigdesc->numtriggers <= 0)
1840  return NULL;
1841 
1842  newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
1843  memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
1844 
1845  trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
1846  memcpy(trigger, trigdesc->triggers,
1847  trigdesc->numtriggers * sizeof(Trigger));
1848  newdesc->triggers = trigger;
1849 
1850  for (i = 0; i < trigdesc->numtriggers; i++)
1851  {
1852  trigger->tgname = pstrdup(trigger->tgname);
1853  if (trigger->tgnattr > 0)
1854  {
1855  int16 *newattr;
1856 
1857  newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
1858  memcpy(newattr, trigger->tgattr,
1859  trigger->tgnattr * sizeof(int16));
1860  trigger->tgattr = newattr;
1861  }
1862  if (trigger->tgnargs > 0)
1863  {
1864  char **newargs;
1865  int16 j;
1866 
1867  newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
1868  for (j = 0; j < trigger->tgnargs; j++)
1869  newargs[j] = pstrdup(trigger->tgargs[j]);
1870  trigger->tgargs = newargs;
1871  }
1872  if (trigger->tgqual)
1873  trigger->tgqual = pstrdup(trigger->tgqual);
1874  if (trigger->tgoldtable)
1875  trigger->tgoldtable = pstrdup(trigger->tgoldtable);
1876  if (trigger->tgnewtable)
1877  trigger->tgnewtable = pstrdup(trigger->tgnewtable);
1878  trigger++;
1879  }
1880 
1881  return newdesc;
1882 }
signed short int16
Definition: c.h:255
char * pstrdup(const char *in)
Definition: mcxt.c:1077
char * tgqual
Definition: reltrigger.h:41
char * tgname
Definition: reltrigger.h:27
Trigger * triggers
Definition: reltrigger.h:48
int numtriggers
Definition: reltrigger.h:49
char ** tgargs
Definition: reltrigger.h:40
int16 * tgattr
Definition: reltrigger.h:39
char * tgnewtable
Definition: reltrigger.h:43
#define NULL
Definition: c.h:229
int16 tgnattr
Definition: reltrigger.h:38
void * palloc(Size size)
Definition: mcxt.c:849
int i
int16 tgnargs
Definition: reltrigger.h:37
char * tgoldtable
Definition: reltrigger.h:42
ObjectAddress CreateTrigger ( CreateTrigStmt stmt,
const char *  queryString,
Oid  relOid,
Oid  refRelOid,
Oid  constraintOid,
Oid  indexOid,
bool  isInternal 
)

Definition at line 138 of file trigger.c.

References AccessShareLock, ACL_EXECUTE, ACL_KIND_CLASS, ACL_KIND_PROC, ACL_TRIGGER, aclcheck_error(), ACLCHECK_OK, addRangeTableEntryForRelation(), addRTEtoQuery(), allowSystemTableMods, Anum_pg_trigger_tgargs, Anum_pg_trigger_tgattr, Anum_pg_trigger_tgconstraint, Anum_pg_trigger_tgconstrindid, Anum_pg_trigger_tgconstrrelid, Anum_pg_trigger_tgdeferrable, Anum_pg_trigger_tgenabled, Anum_pg_trigger_tgfoid, Anum_pg_trigger_tginitdeferred, Anum_pg_trigger_tgisinternal, Anum_pg_trigger_tgname, Anum_pg_trigger_tgnargs, Anum_pg_trigger_tgnewtable, Anum_pg_trigger_tgoldtable, Anum_pg_trigger_tgqual, Anum_pg_trigger_tgrelid, Anum_pg_trigger_tgtype, generate_unaccent_rules::args, CreateTrigStmt::args, Assert, assign_expr_collations(), attnameAttNum(), BoolGetDatum, BTEqualStrategyNumber, buildint2vector(), byteain(), CatalogTupleInsert(), CatalogTupleUpdate(), CharGetDatum, ObjectAddress::classId, CreateTrigStmt::columns, CONSTRAINT_TRIGGER, ConstraintRelationId, CreateTrigStmt::constrrel, ConvertTriggerToFK(), copyObject, CreateConstraintEntry(), CStringGetDatum, CStringGetTextDatum, DatumGetPointer, CreateTrigStmt::deferrable, DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, DEPENDENCY_NORMAL, DirectFunctionCall1, elog, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errhint(), errmsg(), ERROR, CreateTrigStmt::events, EXPR_KIND_TRIGGER_WHEN, free_parsestate(), CreateTrigStmt::funcname, get_func_rettype(), get_rel_name(), GetNewOid(), GETSTRUCT, GetUserId(), heap_close, heap_form_tuple(), heap_freetuple(), heap_open(), heap_openrv(), HeapTupleIsValid, HeapTupleSetOid, i, CreateTrigStmt::initdeferred, Int16GetDatum, InvalidAttrNumber, InvalidObjectAddress, InvalidOid, InvokeObjectPostCreateHookArg, CreateTrigStmt::isconstraint, TriggerTransition::isNew, IsSystemRelation(), TriggerTransition::isTable, lfirst, lfirst_node, list_length(), Var::location, LockRelationOid(), LookupFuncName(), make_parsestate(), makeAlias(), name, TriggerTransition::name, NAMEDATALEN, namein(), NameListToString(), namestrcmp(), Natts_pg_trigger, NIL, nodeToString(), NoLock, NULL, ObjectAddress::objectId, ObjectIdGetDatum, ObjectAddress::objectSubId, OidIsValid, OPAQUEOID, ParseState::p_rtable, ParseState::p_sourcetext, palloc(), parser_errposition(), pfree(), pg_class_aclcheck(), pg_proc_aclcheck(), PointerGetDatum, ProcedureRelationId, PRS2_NEW_VARNO, PRS2_OLD_VARNO, pull_var_clause(), RangeVarGetRelid, RelationData::rd_att, RelationData::rd_rel, recordDependencyOn(), recordDependencyOnExpr(), CreateTrigStmt::relation, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RelationRelationId, RELKIND_FOREIGN_TABLE, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_VIEW, RELOID, RI_FKey_trigger_type(), RI_TRIGGER_NONE, CreateTrigStmt::row, RowExclusiveLock, ScanKeyInit(), SearchSysCacheCopy1, SetFunctionReturnType(), ShareRowExclusiveLock, snprintf(), strVal, systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, CreateTrigStmt::timing, transformWhereClause(), CreateTrigStmt::transitionRels, TRIGGER_CLEAR_TYPE, TRIGGER_FIRES_ON_ORIGIN, TRIGGER_FOR_BEFORE, TRIGGER_FOR_DELETE, TRIGGER_FOR_INSERT, TRIGGER_FOR_INSTEAD, TRIGGER_FOR_ROW, TRIGGER_FOR_TRUNCATE, TRIGGER_FOR_UPDATE, TRIGGER_SETT_ROW, TRIGGER_TYPE_AFTER, TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSTEAD, TRIGGEROID, TriggerRelationId, TriggerRelidNameIndexId, CreateTrigStmt::trigname, values, Var::varattno, Var::varno, WARNING, and CreateTrigStmt::whenClause.

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

141 {
142  int16 tgtype;
143  int ncolumns;
144  int16 *columns;
145  int2vector *tgattr;
146  Node *whenClause;
147  List *whenRtable;
148  char *qual;
150  bool nulls[Natts_pg_trigger];
151  Relation rel;
152  AclResult aclresult;
153  Relation tgrel;
154  SysScanDesc tgscan;
155  ScanKeyData key;
156  Relation pgrel;
157  HeapTuple tuple;
158  Oid fargtypes[1]; /* dummy */
159  Oid funcoid;
160  Oid funcrettype;
161  Oid trigoid;
162  char internaltrigname[NAMEDATALEN];
163  char *trigname;
164  Oid constrrelid = InvalidOid;
165  ObjectAddress myself,
166  referenced;
167  char *oldtablename = NULL;
168  char *newtablename = NULL;
169 
170  if (OidIsValid(relOid))
171  rel = heap_open(relOid, ShareRowExclusiveLock);
172  else
174 
175  /*
176  * Triggers must be on tables or views, and there are additional
177  * relation-type-specific restrictions.
178  */
179  if (rel->rd_rel->relkind == RELKIND_RELATION ||
180  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
181  {
182  /* Tables can't have INSTEAD OF triggers */
183  if (stmt->timing != TRIGGER_TYPE_BEFORE &&
184  stmt->timing != TRIGGER_TYPE_AFTER)
185  ereport(ERROR,
186  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
187  errmsg("\"%s\" is a table",
189  errdetail("Tables cannot have INSTEAD OF triggers.")));
190  /* Disallow ROW triggers on partitioned tables */
191  if (stmt->row && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
192  ereport(ERROR,
193  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
194  errmsg("\"%s\" is a partitioned table",
196  errdetail("Partitioned tables cannot have ROW triggers.")));
197  }
198  else if (rel->rd_rel->relkind == RELKIND_VIEW)
199  {
200  /*
201  * Views can have INSTEAD OF triggers (which we check below are
202  * row-level), or statement-level BEFORE/AFTER triggers.
203  */
204  if (stmt->timing != TRIGGER_TYPE_INSTEAD && stmt->row)
205  ereport(ERROR,
206  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
207  errmsg("\"%s\" is a view",
209  errdetail("Views cannot have row-level BEFORE or AFTER triggers.")));
210  /* Disallow TRUNCATE triggers on VIEWs */
211  if (TRIGGER_FOR_TRUNCATE(stmt->events))
212  ereport(ERROR,
213  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
214  errmsg("\"%s\" is a view",
216  errdetail("Views cannot have TRUNCATE triggers.")));
217  }
218  else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
219  {
220  if (stmt->timing != TRIGGER_TYPE_BEFORE &&
221  stmt->timing != TRIGGER_TYPE_AFTER)
222  ereport(ERROR,
223  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
224  errmsg("\"%s\" is a foreign table",
226  errdetail("Foreign tables cannot have INSTEAD OF triggers.")));
227 
228  if (TRIGGER_FOR_TRUNCATE(stmt->events))
229  ereport(ERROR,
230  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
231  errmsg("\"%s\" is a foreign table",
233  errdetail("Foreign tables cannot have TRUNCATE triggers.")));
234 
235  if (stmt->isconstraint)
236  ereport(ERROR,
237  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
238  errmsg("\"%s\" is a foreign table",
240  errdetail("Foreign tables cannot have constraint triggers.")));
241  }
242  else
243  ereport(ERROR,
244  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
245  errmsg("\"%s\" is not a table or view",
246  RelationGetRelationName(rel))));
247 
249  ereport(ERROR,
250  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
251  errmsg("permission denied: \"%s\" is a system catalog",
252  RelationGetRelationName(rel))));
253 
254  if (stmt->isconstraint)
255  {
256  /*
257  * We must take a lock on the target relation to protect against
258  * concurrent drop. It's not clear that AccessShareLock is strong
259  * enough, but we certainly need at least that much... otherwise, we
260  * might end up creating a pg_constraint entry referencing a
261  * nonexistent table.
262  */
263  if (OidIsValid(refRelOid))
264  {
265  LockRelationOid(refRelOid, AccessShareLock);
266  constrrelid = refRelOid;
267  }
268  else if (stmt->constrrel != NULL)
269  constrrelid = RangeVarGetRelid(stmt->constrrel, AccessShareLock,
270  false);
271  }
272 
273  /* permission checks */
274  if (!isInternal)
275  {
276  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
277  ACL_TRIGGER);
278  if (aclresult != ACLCHECK_OK)
279  aclcheck_error(aclresult, ACL_KIND_CLASS,
281 
282  if (OidIsValid(constrrelid))
283  {
284  aclresult = pg_class_aclcheck(constrrelid, GetUserId(),
285  ACL_TRIGGER);
286  if (aclresult != ACLCHECK_OK)
287  aclcheck_error(aclresult, ACL_KIND_CLASS,
288  get_rel_name(constrrelid));
289  }
290  }
291 
292  /* Compute tgtype */
293  TRIGGER_CLEAR_TYPE(tgtype);
294  if (stmt->row)
295  TRIGGER_SETT_ROW(tgtype);
296  tgtype |= stmt->timing;
297  tgtype |= stmt->events;
298 
299  /* Disallow ROW-level TRUNCATE triggers */
300  if (TRIGGER_FOR_ROW(tgtype) && TRIGGER_FOR_TRUNCATE(tgtype))
301  ereport(ERROR,
302  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
303  errmsg("TRUNCATE FOR EACH ROW triggers are not supported")));
304 
305  /* INSTEAD triggers must be row-level, and can't have WHEN or columns */
306  if (TRIGGER_FOR_INSTEAD(tgtype))
307  {
308  if (!TRIGGER_FOR_ROW(tgtype))
309  ereport(ERROR,
310  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
311  errmsg("INSTEAD OF triggers must be FOR EACH ROW")));
312  if (stmt->whenClause)
313  ereport(ERROR,
314  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
315  errmsg("INSTEAD OF triggers cannot have WHEN conditions")));
316  if (stmt->columns != NIL)
317  ereport(ERROR,
318  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
319  errmsg("INSTEAD OF triggers cannot have column lists")));
320  }
321 
322  /*
323  * We don't yet support naming ROW transition variables, but the parser
324  * recognizes the syntax so we can give a nicer message here.
325  *
326  * Per standard, REFERENCING TABLE names are only allowed on AFTER
327  * triggers. Per standard, REFERENCING ROW names are not allowed with FOR
328  * EACH STATEMENT. Per standard, each OLD/NEW, ROW/TABLE permutation is
329  * only allowed once. Per standard, OLD may not be specified when
330  * creating a trigger only for INSERT, and NEW may not be specified when
331  * creating a trigger only for DELETE.
332  *
333  * Notice that the standard allows an AFTER ... FOR EACH ROW trigger to
334  * reference both ROW and TABLE transition data.
335  */
336  if (stmt->transitionRels != NIL)
337  {
338  List *varList = stmt->transitionRels;
339  ListCell *lc;
340 
341  foreach(lc, varList)
342  {
344 
345  if (!(tt->isTable))
346  ereport(ERROR,
347  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
348  errmsg("ROW variable naming in the REFERENCING clause is not supported"),
349  errhint("Use OLD TABLE or NEW TABLE for naming transition tables.")));
350 
351  /*
352  * Because of the above test, we omit further ROW-related testing
353  * below. If we later allow naming OLD and NEW ROW variables,
354  * adjustments will be needed below.
355  */
356 
357  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
358  ereport(ERROR,
359  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
360  errmsg("\"%s\" is a partitioned table",
362  errdetail("Triggers on partitioned tables cannot have transition tables.")));
363 
364  if (stmt->timing != TRIGGER_TYPE_AFTER)
365  ereport(ERROR,
366  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
367  errmsg("transition table name can only be specified for an AFTER trigger")));
368 
369  if (tt->isNew)
370  {
371  if (!(TRIGGER_FOR_INSERT(tgtype) ||
372  TRIGGER_FOR_UPDATE(tgtype)))
373  ereport(ERROR,
374  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
375  errmsg("NEW TABLE can only be specified for an INSERT or UPDATE trigger")));
376 
377  if (newtablename != NULL)
378  ereport(ERROR,
379  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
380  errmsg("NEW TABLE cannot be specified multiple times")));
381 
382  newtablename = tt->name;
383  }
384  else
385  {
386  if (!(TRIGGER_FOR_DELETE(tgtype) ||
387  TRIGGER_FOR_UPDATE(tgtype)))
388  ereport(ERROR,
389  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
390  errmsg("OLD TABLE can only be specified for a DELETE or UPDATE trigger")));
391 
392  if (oldtablename != NULL)
393  ereport(ERROR,
394  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
395  errmsg("OLD TABLE cannot be specified multiple times")));
396 
397  oldtablename = tt->name;
398  }
399  }
400 
401  if (newtablename != NULL && oldtablename != NULL &&
402  strcmp(newtablename, oldtablename) == 0)
403  ereport(ERROR,
404  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
405  errmsg("OLD TABLE name and NEW TABLE name cannot be the same")));
406  }
407 
408  /*
409  * Parse the WHEN clause, if any
410  */
411  if (stmt->whenClause)
412  {
413  ParseState *pstate;
414  RangeTblEntry *rte;
415  List *varList;
416  ListCell *lc;
417 
418  /* Set up a pstate to parse with */
419  pstate = make_parsestate(NULL);
420  pstate->p_sourcetext = queryString;
421 
422  /*
423  * Set up RTEs for OLD and NEW references.
424  *
425  * 'OLD' must always have varno equal to 1 and 'NEW' equal to 2.
426  */
427  rte = addRangeTableEntryForRelation(pstate, rel,
428  makeAlias("old", NIL),
429  false, false);
430  addRTEtoQuery(pstate, rte, false, true, true);
431  rte = addRangeTableEntryForRelation(pstate, rel,
432  makeAlias("new", NIL),
433  false, false);
434  addRTEtoQuery(pstate, rte, false, true, true);
435 
436  /* Transform expression. Copy to be sure we don't modify original */
437  whenClause = transformWhereClause(pstate,
438  copyObject(stmt->whenClause),
440  "WHEN");
441  /* we have to fix its collations too */
442  assign_expr_collations(pstate, whenClause);
443 
444  /*
445  * Check for disallowed references to OLD/NEW.
446  *
447  * NB: pull_var_clause is okay here only because we don't allow
448  * subselects in WHEN clauses; it would fail to examine the contents
449  * of subselects.
450  */
451  varList = pull_var_clause(whenClause, 0);
452  foreach(lc, varList)
453  {
454  Var *var = (Var *) lfirst(lc);
455 
456  switch (var->varno)
457  {
458  case PRS2_OLD_VARNO:
459  if (!TRIGGER_FOR_ROW(tgtype))
460  ereport(ERROR,
461  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
462  errmsg("statement trigger's WHEN condition cannot reference column values"),
463  parser_errposition(pstate, var->location)));
464  if (TRIGGER_FOR_INSERT(tgtype))
465  ereport(ERROR,
466  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
467  errmsg("INSERT trigger's WHEN condition cannot reference OLD values"),
468  parser_errposition(pstate, var->location)));
469  /* system columns are okay here */
470  break;
471  case PRS2_NEW_VARNO:
472  if (!TRIGGER_FOR_ROW(tgtype))
473  ereport(ERROR,
474  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
475  errmsg("statement trigger's WHEN condition cannot reference column values"),
476  parser_errposition(pstate, var->location)));
477  if (TRIGGER_FOR_DELETE(tgtype))
478  ereport(ERROR,
479  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
480  errmsg("DELETE trigger's WHEN condition cannot reference NEW values"),
481  parser_errposition(pstate, var->location)));
482  if (var->varattno < 0 && TRIGGER_FOR_BEFORE(tgtype))
483  ereport(ERROR,
484  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
485  errmsg("BEFORE trigger's WHEN condition cannot reference NEW system columns"),
486  parser_errposition(pstate, var->location)));
487  break;
488  default:
489  /* can't happen without add_missing_from, so just elog */
490  elog(ERROR, "trigger WHEN condition cannot contain references to other relations");
491  break;
492  }
493  }
494 
495  /* we'll need the rtable for recordDependencyOnExpr */
496  whenRtable = pstate->p_rtable;
497 
498  qual = nodeToString(whenClause);
499 
500  free_parsestate(pstate);
501  }
502  else
503  {
504  whenClause = NULL;
505  whenRtable = NIL;
506  qual = NULL;
507  }
508 
509  /*
510  * Find and validate the trigger function.
511  */
512  funcoid = LookupFuncName(stmt->funcname, 0, fargtypes, false);
513  if (!isInternal)
514  {
515  aclresult = pg_proc_aclcheck(funcoid, GetUserId(), ACL_EXECUTE);
516  if (aclresult != ACLCHECK_OK)
517  aclcheck_error(aclresult, ACL_KIND_PROC,
518  NameListToString(stmt->funcname));
519  }
520  funcrettype = get_func_rettype(funcoid);
521  if (funcrettype != TRIGGEROID)
522  {
523  /*
524  * We allow OPAQUE just so we can load old dump files. When we see a
525  * trigger function declared OPAQUE, change it to TRIGGER.
526  */
527  if (funcrettype == OPAQUEOID)
528  {
530  (errmsg("changing return type of function %s from %s to %s",
531  NameListToString(stmt->funcname),
532  "opaque", "trigger")));
534  }
535  else
536  ereport(ERROR,
537  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
538  errmsg("function %s must return type %s",
539  NameListToString(stmt->funcname), "trigger")));
540  }
541 
542  /*
543  * If the command is a user-entered CREATE CONSTRAINT TRIGGER command that
544  * references one of the built-in RI_FKey trigger functions, assume it is
545  * from a dump of a pre-7.3 foreign key constraint, and take steps to
546  * convert this legacy representation into a regular foreign key
547  * constraint. Ugly, but necessary for loading old dump files.
548  */
549  if (stmt->isconstraint && !isInternal &&
550  list_length(stmt->args) >= 6 &&
551  (list_length(stmt->args) % 2) == 0 &&
553  {
554  /* Keep lock on target rel until end of xact */
555  heap_close(rel, NoLock);
556 
557  ConvertTriggerToFK(stmt, funcoid);
558 
559  return InvalidObjectAddress;
560  }
561 
562  /*
563  * If it's a user-entered CREATE CONSTRAINT TRIGGER command, make a
564  * corresponding pg_constraint entry.
565  */
566  if (stmt->isconstraint && !OidIsValid(constraintOid))
567  {
568  /* Internal callers should have made their own constraints */
569  Assert(!isInternal);
570  constraintOid = CreateConstraintEntry(stmt->trigname,
573  stmt->deferrable,
574  stmt->initdeferred,
575  true,
576  RelationGetRelid(rel),
577  NULL, /* no conkey */
578  0,
579  InvalidOid, /* no domain */
580  InvalidOid, /* no index */
581  InvalidOid, /* no foreign key */
582  NULL,
583  NULL,
584  NULL,
585  NULL,
586  0,
587  ' ',
588  ' ',
589  ' ',
590  NULL, /* no exclusion */
591  NULL, /* no check constraint */
592  NULL,
593  NULL,
594  true, /* islocal */
595  0, /* inhcount */
596  true, /* isnoinherit */
597  isInternal); /* is_internal */
598  }
599 
600  /*
601  * Generate the trigger's OID now, so that we can use it in the name if
602  * needed.
603  */
605 
606  trigoid = GetNewOid(tgrel);
607 
608  /*
609  * If trigger is internally generated, modify the provided trigger name to
610  * ensure uniqueness by appending the trigger OID. (Callers will usually
611  * supply a simple constant trigger name in these cases.)
612  */
613  if (isInternal)
614  {
615  snprintf(internaltrigname, sizeof(internaltrigname),
616  "%s_%u", stmt->trigname, trigoid);
617  trigname = internaltrigname;
618  }
619  else
620  {
621  /* user-defined trigger; use the specified trigger name as-is */
622  trigname = stmt->trigname;
623  }
624 
625  /*
626  * Scan pg_trigger for existing triggers on relation. We do this only to
627  * give a nice error message if there's already a trigger of the same
628  * name. (The unique index on tgrelid/tgname would complain anyway.) We
629  * can skip this for internally generated triggers, since the name
630  * modification above should be sufficient.
631  *
632  * NOTE that this is cool only because we have ShareRowExclusiveLock on
633  * the relation, so the trigger set won't be changing underneath us.
634  */
635  if (!isInternal)
636  {
637  ScanKeyInit(&key,
639  BTEqualStrategyNumber, F_OIDEQ,
641  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
642  NULL, 1, &key);
643  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
644  {
645  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(tuple);
646 
647  if (namestrcmp(&(pg_trigger->tgname), trigname) == 0)
648  ereport(ERROR,
650  errmsg("trigger \"%s\" for relation \"%s\" already exists",
651  trigname, RelationGetRelationName(rel))));
652  }
653  systable_endscan(tgscan);
654  }
655 
656  /*
657  * Build the new pg_trigger tuple.
658  */
659  memset(nulls, false, sizeof(nulls));
660 
663  CStringGetDatum(trigname));
664  values[Anum_pg_trigger_tgfoid - 1] = ObjectIdGetDatum(funcoid);
665  values[Anum_pg_trigger_tgtype - 1] = Int16GetDatum(tgtype);
667  values[Anum_pg_trigger_tgisinternal - 1] = BoolGetDatum(isInternal);
668  values[Anum_pg_trigger_tgconstrrelid - 1] = ObjectIdGetDatum(constrrelid);
669  values[Anum_pg_trigger_tgconstrindid - 1] = ObjectIdGetDatum(indexOid);
670  values[Anum_pg_trigger_tgconstraint - 1] = ObjectIdGetDatum(constraintOid);
673 
674  if (stmt->args)
675  {
676  ListCell *le;
677  char *args;
678  int16 nargs = list_length(stmt->args);
679  int len = 0;
680 
681  foreach(le, stmt->args)
682  {
683  char *ar = strVal(lfirst(le));
684 
685  len += strlen(ar) + 4;
686  for (; *ar; ar++)
687  {
688  if (*ar == '\\')
689  len++;
690  }
691  }
692  args = (char *) palloc(len + 1);
693  args[0] = '\0';
694  foreach(le, stmt->args)
695  {
696  char *s = strVal(lfirst(le));
697  char *d = args + strlen(args);
698 
699  while (*s)
700  {
701  if (*s == '\\')
702  *d++ = '\\';
703  *d++ = *s++;
704  }
705  strcpy(d, "\\000");
706  }
707  values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(nargs);
709  CStringGetDatum(args));
710  }
711  else
712  {
713  values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(0);
715  CStringGetDatum(""));
716  }
717 
718  /* build column number array if it's a column-specific trigger */
719  ncolumns = list_length(stmt->columns);
720  if (ncolumns == 0)
721  columns = NULL;
722  else
723  {
724  ListCell *cell;
725  int i = 0;
726 
727  columns = (int16 *) palloc(ncolumns * sizeof(int16));
728  foreach(cell, stmt->columns)
729  {
730  char *name = strVal(lfirst(cell));
731  int16 attnum;
732  int j;
733 
734  /* Lookup column name. System columns are not allowed */
735  attnum = attnameAttNum(rel, name, false);
736  if (attnum == InvalidAttrNumber)
737  ereport(ERROR,
738  (errcode(ERRCODE_UNDEFINED_COLUMN),
739  errmsg("column \"%s\" of relation \"%s\" does not exist",
740  name, RelationGetRelationName(rel))));
741 
742  /* Check for duplicates */
743  for (j = i - 1; j >= 0; j--)
744  {
745  if (columns[j] == attnum)
746  ereport(ERROR,
747  (errcode(ERRCODE_DUPLICATE_COLUMN),
748  errmsg("column \"%s\" specified more than once",
749  name)));
750  }
751 
752  columns[i++] = attnum;
753  }
754  }
755  tgattr = buildint2vector(columns, ncolumns);
756  values[Anum_pg_trigger_tgattr - 1] = PointerGetDatum(tgattr);
757 
758  /* set tgqual if trigger has WHEN clause */
759  if (qual)
760  values[Anum_pg_trigger_tgqual - 1] = CStringGetTextDatum(qual);
761  else
762  nulls[Anum_pg_trigger_tgqual - 1] = true;
763 
764  if (oldtablename)
766  CStringGetDatum(oldtablename));
767  else
768  nulls[Anum_pg_trigger_tgoldtable - 1] = true;
769  if (newtablename)
771  CStringGetDatum(newtablename));
772  else
773  nulls[Anum_pg_trigger_tgnewtable - 1] = true;
774 
775  tuple = heap_form_tuple(tgrel->rd_att, values, nulls);
776 
777  /* force tuple to have the desired OID */
778  HeapTupleSetOid(tuple, trigoid);
779 
780  /*
781  * Insert tuple into pg_trigger.
782  */
783  CatalogTupleInsert(tgrel, tuple);
784 
785  heap_freetuple(tuple);
787 
791  if (oldtablename)
793  if (newtablename)
795 
796  /*
797  * Update relation's pg_class entry. Crucial side-effect: other backends
798  * (and this one too!) are sent SI message to make them rebuild relcache
799  * entries.
800  */
802  tuple = SearchSysCacheCopy1(RELOID,
804  if (!HeapTupleIsValid(tuple))
805  elog(ERROR, "cache lookup failed for relation %u",
806  RelationGetRelid(rel));
807 
808  ((Form_pg_class) GETSTRUCT(tuple))->relhastriggers = true;
809 
810  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
811 
812  heap_freetuple(tuple);
814 
815  /*
816  * We used to try to update the rel's relcache entry here, but that's
817  * fairly pointless since it will happen as a byproduct of the upcoming
818  * CommandCounterIncrement...
819  */
820 
821  /*
822  * Record dependencies for trigger. Always place a normal dependency on
823  * the function.
824  */
825  myself.classId = TriggerRelationId;
826  myself.objectId = trigoid;
827  myself.objectSubId = 0;
828 
829  referenced.classId = ProcedureRelationId;
830  referenced.objectId = funcoid;
831  referenced.objectSubId = 0;
832  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
833 
834  if (isInternal && OidIsValid(constraintOid))
835  {
836  /*
837  * Internally-generated trigger for a constraint, so make it an
838  * internal dependency of the constraint. We can skip depending on
839  * the relation(s), as there'll be an indirect dependency via the
840  * constraint.
841  */
842  referenced.classId = ConstraintRelationId;
843  referenced.objectId = constraintOid;
844  referenced.objectSubId = 0;
845  recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
846  }
847  else
848  {
849  /*
850  * User CREATE TRIGGER, so place dependencies. We make trigger be
851  * auto-dropped if its relation is dropped or if the FK relation is
852  * dropped. (Auto drop is compatible with our pre-7.3 behavior.)
853  */
854  referenced.classId = RelationRelationId;
855  referenced.objectId = RelationGetRelid(rel);
856  referenced.objectSubId = 0;
857  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
858  if (OidIsValid(constrrelid))
859  {
860  referenced.classId = RelationRelationId;
861  referenced.objectId = constrrelid;
862  referenced.objectSubId = 0;
863  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
864  }
865  /* Not possible to have an index dependency in this case */
866  Assert(!OidIsValid(indexOid));
867 
868  /*
869  * If it's a user-specified constraint trigger, make the constraint
870  * internally dependent on the trigger instead of vice versa.
871  */
872  if (OidIsValid(constraintOid))
873  {
874  referenced.classId = ConstraintRelationId;
875  referenced.objectId = constraintOid;
876  referenced.objectSubId = 0;
877  recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL);
878  }
879  }
880 
881  /* If column-specific trigger, add normal dependencies on columns */
882  if (columns != NULL)
883  {
884  int i;
885 
886  referenced.classId = RelationRelationId;
887  referenced.objectId = RelationGetRelid(rel);
888  for (i = 0; i < ncolumns; i++)
889  {
890  referenced.objectSubId = columns[i];
891  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
892  }
893  }
894 
895  /*
896  * If it has a WHEN clause, add dependencies on objects mentioned in the
897  * expression (eg, functions, as well as any columns used).
898  */
899  if (whenClause != NULL)
900  recordDependencyOnExpr(&myself, whenClause, whenRtable,
902 
903  /* Post creation hook for new trigger */
905  isInternal);
906 
907  /* Keep lock on target rel until end of xact */
908  heap_close(rel, NoLock);
909 
910  return myself;
911 }
signed short int16
Definition: c.h:255
#define NIL
Definition: pg_list.h:69
#define Anum_pg_trigger_tgdeferrable
Definition: pg_trigger.h:88
#define TRIGGER_FOR_DELETE(type)
Definition: pg_trigger.h:135
int RI_FKey_trigger_type(Oid tgfoid)
Definition: ri_triggers.c:3704
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:46
int errhint(const char *fmt,...)
Definition: elog.c:987
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
bool IsSystemRelation(Relation relation)
Definition: catalog.c:62
Oid GetUserId(void)
Definition: miscinit.c:283
#define PointerGetDatum(X)
Definition: postgres.h:562
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:53
#define Anum_pg_trigger_tgconstraint
Definition: pg_trigger.h:87
#define ProcedureRelationId
Definition: pg_proc.h:33
Node * whenClause
Definition: parsenodes.h:2327
#define RelationRelationId
Definition: pg_class.h:29
int2vector * buildint2vector(const int16 *int2s, int n)
Definition: int.c:112
#define Anum_pg_trigger_tgqual
Definition: pg_trigger.h:93
#define TRIGGER_CLEAR_TYPE(type)
Definition: pg_trigger.h:118
#define Int16GetDatum(X)
Definition: postgres.h:457
#define Anum_pg_trigger_tgtype
Definition: pg_trigger.h:82
#define AccessShareLock
Definition: lockdefs.h:36
#define Anum_pg_trigger_tgnargs
Definition: pg_trigger.h:90
Definition: nodes.h:509
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
int namestrcmp(Name name, const char *str)
Definition: name.c:248
#define TRIGGER_FOR_UPDATE(type)
Definition: pg_trigger.h:136
AttrNumber varattno
Definition: primnodes.h:168
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:44
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:692
#define heap_close(r, l)
Definition: heapam.h:97
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
#define Anum_pg_trigger_tgisinternal
Definition: pg_trigger.h:84
#define OidIsValid(objectId)
Definition: c.h:538
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:109
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1459
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
#define TriggerRelidNameIndexId
Definition: indexing.h:249
#define HeapTupleSetOid(tuple, oid)
Definition: htup_details.h:698
#define NAMEDATALEN
void assign_expr_collations(ParseState *pstate, Node *expr)
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:384
RangeVar * constrrel
Definition: parsenodes.h:2334
#define TRIGGER_TYPE_INSTEAD
Definition: pg_trigger.h:104
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define TRIGGER_FOR_ROW(type)
Definition: pg_trigger.h:130
void pfree(void *pointer)
Definition: mcxt.c:950
#define OPAQUEOID
Definition: pg_type.h:700
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
Oid CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:162
#define TRIGGER_TYPE_AFTER
Definition: pg_trigger.h:112
#define TRIGGEROID
Definition: pg_type.h:692
ItemPointerData t_self
Definition: htup.h:65
Datum byteain(PG_FUNCTION_ARGS)
Definition: varlena.c:255
#define lfirst_node(type, lc)
Definition: pg_list.h:109
#define ACL_TRIGGER
Definition: parsenodes.h:78
int location
Definition: primnodes.h:178
#define NoLock
Definition: lockdefs.h:34
#define TRIGGER_SETT_ROW(type)
Definition: pg_trigger.h:120
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define CStringGetDatum(X)
Definition: postgres.h:584
void recordDependencyOnExpr(const ObjectAddress *depender, Node *expr, List *rtable, DependencyType behavior)
Definition: dependency.c:1338
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
const char * p_sourcetext
Definition: parse_node.h:168
#define TRIGGER_FOR_BEFORE(type)
Definition: pg_trigger.h:131
static void ConvertTriggerToFK(CreateTrigStmt *stmt, Oid funcoid)
Definition: trigger.c:941
List * transitionRels
Definition: parsenodes.h:2330
#define ereport(elevel, rest)
Definition: elog.h:122
void addRTEtoQuery(ParseState *pstate, RangeTblEntry *rte, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define PRS2_OLD_VARNO
Definition: primnodes.h:160
#define Anum_pg_trigger_tgrelid
Definition: pg_trigger.h:79
#define WARNING
Definition: elog.h:40
Index varno
Definition: primnodes.h:166
char * NameListToString(List *names)
Definition: namespace.c:2953
#define Anum_pg_trigger_tgnewtable
Definition: pg_trigger.h:95
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
Definition: c.h:467
#define Anum_pg_trigger_tgconstrindid
Definition: pg_trigger.h:86
AclResult
Definition: acl.h:170
uintptr_t Datum
Definition: postgres.h:372
#define Anum_pg_trigger_tgenabled
Definition: pg_trigger.h:83
Oid GetNewOid(Relation relation)
Definition: catalog.c:288
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
void SetFunctionReturnType(Oid funcOid, Oid newRetType)
#define TRIGGER_FOR_TRUNCATE(type)
Definition: pg_trigger.h:137
#define InvokeObjectPostCreateHookArg(classId, objectId, subId, is_internal)
Definition: objectaccess.h:147
TupleDesc rd_att
Definition: rel.h:115
#define BoolGetDatum(X)
Definition: postgres.h:408
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1312
bool allowSystemTableMods
Definition: globals.c:111
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
#define Anum_pg_trigger_tgargs
Definition: pg_trigger.h:92
#define ShareRowExclusiveLock
Definition: lockdefs.h:42
#define Anum_pg_trigger_tgconstrrelid
Definition: pg_trigger.h:85
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
#define Anum_pg_trigger_tgname
Definition: pg_trigger.h:80
#define TriggerRelationId
Definition: pg_trigger.h:34
#define TRIGGER_FOR_INSERT(type)
Definition: pg_trigger.h:134
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:72
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
const char * name
Definition: encode.c:521
#define InvalidAttrNumber
Definition: attnum.h:23
#define CharGetDatum(X)
Definition: postgres.h:422
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4422
#define DatumGetPointer(X)
Definition: postgres.h:555
#define TRIGGER_TYPE_BEFORE
Definition: pg_trigger.h:99
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1910
#define Anum_pg_trigger_tgoldtable
Definition: pg_trigger.h:94
static Datum values[MAXATTR]
Definition: bootstrap.c:163
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:161
const ObjectAddress InvalidObjectAddress
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define ACL_EXECUTE
Definition: parsenodes.h:79
#define RELKIND_VIEW
Definition: pg_class.h:164
AclResult pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4446
int i
RangeVar * relation
Definition: parsenodes.h:2318
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define CStringGetTextDatum(s)
Definition: builtins.h:91
char * nodeToString(const void *obj)
Definition: outfuncs.c:4217
#define ConstraintRelationId
Definition: pg_constraint.h:29
#define elog
Definition: elog.h:219
#define CONSTRAINT_TRIGGER
#define copyObject(obj)
Definition: nodes.h:621
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:105
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:77
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RI_TRIGGER_NONE
Definition: trigger.h:211
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
#define RelationGetRelid(relation)
Definition: rel.h:417
Oid CreateConstraintEntry(const char *constraintName, Oid constraintNamespace, char constraintType, bool isDeferrable, bool isDeferred, bool isValidated, Oid relId, const int16 *constraintKey, int constraintNKeys, 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, const char *conSrc, bool conIsLocal, int conInhCount, bool conNoInherit, bool is_internal)
Definition: pg_constraint.c:49
#define PRS2_NEW_VARNO
Definition: primnodes.h:161
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define Anum_pg_trigger_tgfoid
Definition: pg_trigger.h:81
#define Anum_pg_trigger_tginitdeferred
Definition: pg_trigger.h:89
#define Anum_pg_trigger_tgattr
Definition: pg_trigger.h:91
#define Natts_pg_trigger
Definition: pg_trigger.h:78
#define TRIGGER_FOR_INSTEAD(type)
Definition: pg_trigger.h:133
#define RelationGetNamespace(relation)
Definition: rel.h:444
List * p_rtable
Definition: parse_node.h:169
void EnableDisableTrigger ( Relation  rel,
const char *  tgname,
char  fires_when,
bool  skip_system 
)

Definition at line 1503 of file trigger.c.

References Anum_pg_trigger_tgname, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber, CacheInvalidateRelcache(), CatalogTupleUpdate(), CStringGetDatum, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_close, heap_copytuple(), heap_freetuple(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvokeObjectPostAlterHook, NameStr, NULL, ObjectIdGetDatum, RelationGetRelationName, RelationGetRelid, RowExclusiveLock, ScanKeyInit(), superuser(), systable_beginscan(), systable_endscan(), systable_getnext(), HeapTupleData::t_self, TriggerRelationId, and TriggerRelidNameIndexId.

Referenced by ATExecEnableDisableTrigger().

1505 {
1506  Relation tgrel;
1507  int nkeys;
1508  ScanKeyData keys[2];
1509  SysScanDesc tgscan;
1510  HeapTuple tuple;
1511  bool found;
1512  bool changed;
1513 
1514  /* Scan the relevant entries in pg_triggers */
1516 
1517  ScanKeyInit(&keys[0],
1519  BTEqualStrategyNumber, F_OIDEQ,
1521  if (tgname)
1522  {
1523  ScanKeyInit(&keys[1],
1525  BTEqualStrategyNumber, F_NAMEEQ,
1526  CStringGetDatum(tgname));
1527  nkeys = 2;
1528  }
1529  else
1530  nkeys = 1;
1531 
1532  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1533  NULL, nkeys, keys);
1534 
1535  found = changed = false;
1536 
1537  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1538  {
1539  Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1540 
1541  if (oldtrig->tgisinternal)
1542  {
1543  /* system trigger ... ok to process? */
1544  if (skip_system)
1545  continue;
1546  if (!superuser())
1547  ereport(ERROR,
1548  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1549  errmsg("permission denied: \"%s\" is a system trigger",
1550  NameStr(oldtrig->tgname))));
1551  }
1552 
1553  found = true;
1554 
1555  if (oldtrig->tgenabled != fires_when)
1556  {
1557  /* need to change this one ... make a copy to scribble on */
1558  HeapTuple newtup = heap_copytuple(tuple);
1559  Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1560 
1561  newtrig->tgenabled = fires_when;
1562 
1563  CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1564 
1565  heap_freetuple(newtup);
1566 
1567  changed = true;
1568  }
1569 
1571  HeapTupleGetOid(tuple), 0);
1572  }
1573 
1574  systable_endscan(tgscan);
1575 
1576  heap_close(tgrel, RowExclusiveLock);
1577 
1578  if (tgname && !found)
1579  ereport(ERROR,
1580  (errcode(ERRCODE_UNDEFINED_OBJECT),
1581  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1582  tgname, RelationGetRelationName(rel))));
1583 
1584  /*
1585  * If we changed anything, broadcast a SI inval message to force each
1586  * backend (including our own!) to rebuild relation's relcache entry.
1587  * Otherwise they will fail to apply the change promptly.
1588  */
1589  if (changed)
1591 }
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:608
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
#define TriggerRelidNameIndexId
Definition: indexing.h:249
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#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:584
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:163
#define Anum_pg_trigger_tgrelid
Definition: pg_trigger.h:79
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Anum_pg_trigger_tgname
Definition: pg_trigger.h:80
#define TriggerRelationId
Definition: pg_trigger.h:34
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:210
FormData_pg_trigger * Form_pg_trigger
Definition: pg_trigger.h:72
void CacheInvalidateRelcache(Relation relation)
Definition: inval.c:1226
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:499
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define RelationGetRelid(relation)
Definition: rel.h:417
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void ExecARDeleteTriggers ( EState estate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple 
)

Definition at line 2455 of file trigger.c.

References AfterTriggerSaveEvent(), Assert, GetTupleForTrigger(), heap_freetuple(), HeapTupleIsValid, ItemPointerIsValid, LockTupleExclusive, NIL, NULL, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_delete_after_row, TriggerDesc::trig_delete_old_table, and TRIGGER_EVENT_DELETE.

Referenced by ExecDelete(), and ExecSimpleRelationDelete().

2458 {
2459  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2460 
2461  if (trigdesc &&
2462  (trigdesc->trig_delete_after_row || trigdesc->trig_delete_old_table))
2463  {
2464  HeapTuple trigtuple;
2465 
2466  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2467  if (fdw_trigtuple == NULL)
2468  trigtuple = GetTupleForTrigger(estate,
2469  NULL,
2470  relinfo,
2471  tupleid,
2473  NULL);
2474  else
2475  trigtuple = fdw_trigtuple;
2476 
2478  true, trigtuple, NULL, NIL, NULL);
2479  if (trigtuple != fdw_trigtuple)
2480  heap_freetuple(trigtuple);
2481  }
2482 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:59
#define NIL
Definition: pg_list.h:69
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:53
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
bool trig_delete_after_row
Definition: reltrigger.h:66
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, HeapTuple oldtup, HeapTuple newtup, List *recheckIndexes, Bitmapset *modifiedCols)
Definition: trigger.c:5080
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static HeapTuple GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot **newSlot)
Definition: trigger.c:2877
bool trig_delete_old_table
Definition: reltrigger.h:77
void ExecARInsertTriggers ( EState estate,
ResultRelInfo relinfo,
HeapTuple  trigtuple,
List recheckIndexes 
)

Definition at line 2246 of file trigger.c.

References AfterTriggerSaveEvent(), NULL, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_insert_after_row, TriggerDesc::trig_insert_new_table, and TRIGGER_EVENT_INSERT.

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

2248 {
2249  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2250 
2251  if (trigdesc &&
2252  (trigdesc->trig_insert_after_row || trigdesc->trig_insert_new_table))
2254  true, NULL, trigtuple, recheckIndexes, NULL);
2255 }
bool trig_insert_new_table
Definition: reltrigger.h:74
bool trig_insert_after_row
Definition: reltrigger.h:56
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, HeapTuple oldtup, HeapTuple newtup, List *recheckIndexes, Bitmapset *modifiedCols)
Definition: trigger.c:5080
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
#define NULL
Definition: c.h:229
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:52
void ExecARUpdateTriggers ( EState estate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple,
HeapTuple  newtuple,
List recheckIndexes 
)

Definition at line 2715 of file trigger.c.

References AfterTriggerSaveEvent(), Assert, GetTupleForTrigger(), GetUpdatedColumns, heap_freetuple(), HeapTupleIsValid, ItemPointerIsValid, LockTupleExclusive, NULL, ResultRelInfo::ri_TrigDesc, TriggerDesc::trig_update_after_row, TriggerDesc::trig_update_new_table, TriggerDesc::trig_update_old_table, and TRIGGER_EVENT_UPDATE.

Referenced by ExecSimpleRelationUpdate(), and ExecUpdate().

2720 {
2721  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2722 
2723  if (trigdesc && (trigdesc->trig_update_after_row ||
2724  trigdesc->trig_update_old_table || trigdesc->trig_update_new_table))
2725  {
2726  HeapTuple trigtuple;
2727 
2728  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2729  if (fdw_trigtuple == NULL)
2730  trigtuple = GetTupleForTrigger(estate,
2731  NULL,
2732  relinfo,
2733  tupleid,
2735  NULL);
2736  else
2737  trigtuple = fdw_trigtuple;
2738 
2740  true, trigtuple, newtuple, recheckIndexes,
2741  GetUpdatedColumns(relinfo, estate));
2742  if (trigtuple != fdw_trigtuple)
2743  heap_freetuple(trigtuple);
2744  }
2745 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:59
bool trig_update_new_table
Definition: reltrigger.h:76
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
bool trig_update_old_table
Definition: reltrigger.h:75
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, HeapTuple oldtup, HeapTuple newtup, List *recheckIndexes, Bitmapset *modifiedCols)
Definition: trigger.c:5080
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
bool trig_update_after_row
Definition: reltrigger.h:61
#define GetUpdatedColumns(relinfo, estate)
Definition: trigger.c:75
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:54
static HeapTuple GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot **newSlot)
Definition: trigger.c:2877
void ExecASDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2376 of file trigger.c.

References AfterTriggerSaveEvent(), NIL, NULL, 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);
2383 }
#define NIL
Definition: pg_list.h:69
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:53
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, HeapTuple oldtup, HeapTuple newtup, List *recheckIndexes, Bitmapset *modifiedCols)
Definition: trigger.c:5080
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
#define NULL
Definition: c.h:229
bool trig_delete_after_statement
Definition: reltrigger.h:69
void ExecASInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2170 of file trigger.c.

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

Referenced by CopyFrom(), and fireASTriggers().

2171 {
2172  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2173 
2174  if (trigdesc && trigdesc->trig_insert_after_statement)
2176  false, NULL, NULL, NIL, NULL);
2177 }
#define NIL
Definition: pg_list.h:69
bool trig_insert_after_statement
Definition: reltrigger.h:59
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, HeapTuple oldtup, HeapTuple newtup, List *recheckIndexes, Bitmapset *modifiedCols)
Definition: trigger.c:5080
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
#define NULL
Definition: c.h:229
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:52
void ExecASTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2866 of file trigger.c.

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

Referenced by ExecuteTruncate().

2867 {
2868  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2869 
2870  if (trigdesc && trigdesc->trig_truncate_after_statement)
2872  false, NULL, NULL, NIL, NULL);
2873 }
#define NIL
Definition: pg_list.h:69
bool trig_truncate_after_statement
Definition: reltrigger.h:72
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, HeapTuple oldtup, HeapTuple newtup, List *recheckIndexes, Bitmapset *modifiedCols)
Definition: trigger.c:5080
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
#define NULL
Definition: c.h:229
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:55
void ExecASUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2587 of file trigger.c.

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

Referenced by fireASTriggers().

2588 {
2589  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2590 
2591  if (trigdesc && trigdesc->trig_update_after_statement)
2593  false, NULL, NULL, NIL,
2594  GetUpdatedColumns(relinfo, estate));
2595 }
#define NIL
Definition: pg_list.h:69
bool trig_update_after_statement
Definition: reltrigger.h:64
static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo, int event, bool row_trigger, HeapTuple oldtup, HeapTuple newtup, List *recheckIndexes, Bitmapset *modifiedCols)
Definition: trigger.c:5080
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
#define GetUpdatedColumns(relinfo, estate)
Definition: trigger.c:75
#define NULL
Definition: c.h:229
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:54
bool ExecBRDeleteTriggers ( EState estate,
EPQState epqstate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple 
)

Definition at line 2386 of file trigger.c.

References Assert, ExecCallTriggerFunc(), GetPerTupleMemoryContext, GetTupleForTrigger(), heap_freetuple(), HeapTupleIsValid, i, InvalidBuffer, ItemPointerIsValid, LockTupleExclusive, NULL, TriggerDesc::numtriggers, result, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_DELETE, TRIGGER_EVENT_ROW, TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_ROW, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecDelete(), and ExecSimpleRelationDelete().

2390 {
2391  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2392  bool result = true;
2393  TriggerData LocTriggerData;
2394  HeapTuple trigtuple;
2395  HeapTuple newtuple;
2396  TupleTableSlot *newSlot;
2397  int i;
2398 
2399  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2400  if (fdw_trigtuple == NULL)
2401  {
2402  trigtuple = GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2403  LockTupleExclusive, &newSlot);
2404  if (trigtuple == NULL)
2405  return false;
2406  }
2407  else
2408  trigtuple = fdw_trigtuple;
2409 
2410  LocTriggerData.type = T_TriggerData;
2411  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2414  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2415  LocTriggerData.tg_newtuple = NULL;
2416  LocTriggerData.tg_oldtable = NULL;
2417  LocTriggerData.tg_newtable = NULL;
2418  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2419  for (i = 0; i < trigdesc->numtriggers; i++)
2420  {
2421  Trigger *trigger = &trigdesc->triggers[i];
2422 
2423  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2427  continue;
2428  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2429  NULL, trigtuple, NULL))
2430  continue;
2431 
2432  LocTriggerData.tg_trigtuple = trigtuple;
2433  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2434  LocTriggerData.tg_trigger = trigger;
2435  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2436  i,
2437  relinfo->ri_TrigFunctions,
2438  relinfo->ri_TrigInstrument,
2439  GetPerTupleMemoryContext(estate));
2440  if (newtuple == NULL)
2441  {
2442  result = false; /* tell caller to suppress delete */
2443  break;
2444  }
2445  if (newtuple != trigtuple)
2446  heap_freetuple(newtuple);
2447  }
2448  if (trigtuple != fdw_trigtuple)
2449  heap_freetuple(trigtuple);
2450 
2451  return result;
2452 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:59
#define TRIGGER_EVENT_ROW
Definition: trigger.h:58
Relation ri_RelationDesc
Definition: execnodes.h:374
#define TRIGGER_TYPE_DELETE
Definition: pg_trigger.h:101
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:53
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
return result
Definition: formatting.c:1618
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
HeapTuple tg_trigtuple
Definition: trigger.h:35
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:60
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
#define TRIGGER_TYPE_ROW
Definition: pg_trigger.h:98
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
TriggerEvent tg_event
Definition: trigger.h:33
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
#define TRIGGER_TYPE_BEFORE
Definition: pg_trigger.h:99
static HeapTuple GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot **newSlot)
Definition: trigger.c:2877
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
TupleTableSlot* ExecBRInsertTriggers ( EState estate,
ResultRelInfo relinfo,
TupleTableSlot slot 
)

Definition at line 2180 of file trigger.c.

References EState::es_trig_tuple_slot, ExecCallTriggerFunc(), ExecMaterializeSlot(), ExecSetSlotDescriptor(), ExecStoreTuple(), GetPerTupleMemoryContext, heap_freetuple(), i, InvalidBuffer, NULL, TriggerDesc::numtriggers, RelationGetDescr, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_INSERT, TRIGGER_EVENT_ROW, TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_ROW, TriggerEnabled(), TriggerDesc::triggers, TupleTableSlot::tts_tupleDescriptor, and TriggerData::type.

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

2182 {
2183  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2184  HeapTuple slottuple = ExecMaterializeSlot(slot);
2185  HeapTuple newtuple = slottuple;
2186  HeapTuple oldtuple;
2187  TriggerData LocTriggerData;
2188  int i;
2189 
2190  LocTriggerData.type = T_TriggerData;
2191  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2194  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2195  LocTriggerData.tg_newtuple = NULL;
2196  LocTriggerData.tg_oldtable = NULL;
2197  LocTriggerData.tg_newtable = NULL;
2198  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2199  for (i = 0; i < trigdesc->numtriggers; i++)
2200  {
2201  Trigger *trigger = &trigdesc->triggers[i];
2202 
2203  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2207  continue;
2208  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2209  NULL, NULL, newtuple))
2210  continue;
2211 
2212  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2213  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2214  LocTriggerData.tg_trigger = trigger;
2215  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2216  i,
2217  relinfo->ri_TrigFunctions,
2218  relinfo->ri_TrigInstrument,
2219  GetPerTupleMemoryContext(estate));
2220  if (oldtuple != newtuple && oldtuple != slottuple)
2221  heap_freetuple(oldtuple);
2222  if (newtuple == NULL)
2223  return NULL; /* "do nothing" */
2224  }
2225 
2226  if (newtuple != slottuple)
2227  {
2228  /*
2229  * Return the modified tuple using the es_trig_tuple_slot. We assume
2230  * the tuple was allocated in per-tuple memory context, and therefore
2231  * will go away by itself. The tuple table slot should not try to
2232  * clear it.
2233  */
2234  TupleTableSlot *newslot = estate->es_trig_tuple_slot;
2235  TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
2236 
2237  if (newslot->tts_tupleDescriptor != tupdesc)
2238  ExecSetSlotDescriptor(newslot, tupdesc);
2239  ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
2240  slot = newslot;
2241  }
2242  return slot;
2243 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:58
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:374
#define RelationGetDescr(relation)
Definition: rel.h:429
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
HeapTuple tg_trigtuple
Definition: trigger.h:35
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:60
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
#define TRIGGER_TYPE_ROW
Definition: pg_trigger.h:98
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:427
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define NULL
Definition: c.h:229
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_TYPE_INSERT
Definition: pg_trigger.h:100
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
#define TRIGGER_TYPE_BEFORE
Definition: pg_trigger.h:99
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:52
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
TupleTableSlot* ExecBRUpdateTriggers ( EState estate,
EPQState epqstate,
ResultRelInfo relinfo,
ItemPointer  tupleid,
HeapTuple  fdw_trigtuple,
TupleTableSlot slot 
)

Definition at line 2598 of file trigger.c.

References Assert, EState::es_trig_tuple_slot, ExecCallTriggerFunc(), ExecFilterJunk(), ExecMaterializeSlot(), ExecSetSlotDescriptor(), ExecStoreTuple(), ExecUpdateLockMode(), GetPerTupleMemoryContext, GetTupleForTrigger(), GetUpdatedColumns, heap_freetuple(), HeapTupleIsValid, i, InvalidBuffer, ItemPointerIsValid, NULL, TriggerDesc::numtriggers, RelationGetDescr, ResultRelInfo::ri_junkFilter, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_ROW, TRIGGER_EVENT_UPDATE, TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_ROW, TRIGGER_TYPE_UPDATE, TriggerEnabled(), TriggerDesc::triggers, TupleTableSlot::tts_tupleDescriptor, and TriggerData::type.

Referenced by ExecSimpleRelationUpdate(), and ExecUpdate().

2603 {
2604  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2605  HeapTuple slottuple = ExecMaterializeSlot(slot);
2606  HeapTuple newtuple = slottuple;
2607  TriggerData LocTriggerData;
2608  HeapTuple trigtuple;
2609  HeapTuple oldtuple;
2610  TupleTableSlot *newSlot;
2611  int i;
2612  Bitmapset *updatedCols;
2613  LockTupleMode lockmode;
2614 
2615  /* Determine lock mode to use */
2616  lockmode = ExecUpdateLockMode(estate, relinfo);
2617 
2618  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2619  if (fdw_trigtuple == NULL)
2620  {
2621  /* get a copy of the on-disk tuple we are planning to update */
2622  trigtuple = GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2623  lockmode, &newSlot);
2624  if (trigtuple == NULL)
2625  return NULL; /* cancel the update action */
2626  }
2627  else
2628  {
2629  trigtuple = fdw_trigtuple;
2630  newSlot = NULL;
2631  }
2632 
2633  /*
2634  * In READ COMMITTED isolation level it's possible that target tuple was
2635  * changed due to concurrent update. In that case we have a raw subplan
2636  * output tuple in newSlot, and need to run it through the junk filter to
2637  * produce an insertable tuple.
2638  *
2639  * Caution: more than likely, the passed-in slot is the same as the
2640  * junkfilter's output slot, so we are clobbering the original value of
2641  * slottuple by doing the filtering. This is OK since neither we nor our
2642  * caller have any more interest in the prior contents of that slot.
2643  */
2644  if (newSlot != NULL)
2645  {
2646  slot = ExecFilterJunk(relinfo->ri_junkFilter, newSlot);
2647  slottuple = ExecMaterializeSlot(slot);
2648  newtuple = slottuple;
2649  }
2650 
2651 
2652  LocTriggerData.type = T_TriggerData;
2653  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2656  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2657  LocTriggerData.tg_oldtable = NULL;
2658  LocTriggerData.tg_newtable = NULL;
2659  updatedCols = GetUpdatedColumns(relinfo, estate);
2660  for (i = 0; i < trigdesc->numtriggers; i++)
2661  {
2662  Trigger *trigger = &trigdesc->triggers[i];
2663 
2664  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2668  continue;
2669  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2670  updatedCols, trigtuple, newtuple))
2671  continue;
2672 
2673  LocTriggerData.tg_trigtuple = trigtuple;
2674  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2675  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2676  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2677  LocTriggerData.tg_trigger = trigger;
2678  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2679  i,
2680  relinfo->ri_TrigFunctions,
2681  relinfo->ri_TrigInstrument,
2682  GetPerTupleMemoryContext(estate));
2683  if (oldtuple != newtuple && oldtuple != slottuple)
2684  heap_freetuple(oldtuple);
2685  if (newtuple == NULL)
2686  {
2687  if (trigtuple != fdw_trigtuple)
2688  heap_freetuple(trigtuple);
2689  return NULL; /* "do nothing" */
2690  }
2691  }
2692  if (trigtuple != fdw_trigtuple)
2693  heap_freetuple(trigtuple);
2694 
2695  if (newtuple != slottuple)
2696  {
2697  /*
2698  * Return the modified tuple using the es_trig_tuple_slot. We assume
2699  * the tuple was allocated in per-tuple memory context, and therefore
2700  * will go away by itself. The tuple table slot should not try to
2701  * clear it.
2702  */
2703  TupleTableSlot *newslot = estate->es_trig_tuple_slot;
2704  TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
2705 
2706  if (newslot->tts_tupleDescriptor != tupdesc)
2707  ExecSetSlotDescriptor(newslot, tupdesc);
2708  ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
2709  slot = newslot;
2710  }
2711  return slot;
2712 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:59
#define TRIGGER_EVENT_ROW
Definition: trigger.h:58
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
JunkFilter * ri_junkFilter
Definition: execnodes.h:388
Relation ri_RelationDesc
Definition: execnodes.h:374
#define RelationGetDescr(relation)
Definition: rel.h:429
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
HeapTuple tg_trigtuple
Definition: trigger.h:35
LockTupleMode
Definition: heapam.h:38
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:60
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
#define TRIGGER_TYPE_ROW
Definition: pg_trigger.h:98
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:427
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
TupleTableSlot * ExecFilterJunk(JunkFilter *junkfilter, TupleTableSlot *slot)
Definition: execJunk.c:262
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define TRIGGER_TYPE_UPDATE
Definition: pg_trigger.h:102
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define GetUpdatedColumns(relinfo, estate)
Definition: trigger.c:75
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
LockTupleMode ExecUpdateLockMode(EState *estate, ResultRelInfo *relinfo)
Definition: execMain.c:2259
TriggerEvent tg_event
Definition: trigger.h:33
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:54
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
#define TRIGGER_TYPE_BEFORE
Definition: pg_trigger.h:99
static HeapTuple GetTupleForTrigger(EState *estate, EPQState *epqstate, ResultRelInfo *relinfo, ItemPointer tid, LockTupleMode lockmode, TupleTableSlot **newSlot)
Definition: trigger.c:2877
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
void ExecBSDeleteTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2324 of file trigger.c.

References ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetPerTupleMemoryContext, i, InvalidBuffer, NULL, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TriggerDesc::trig_delete_before_statement, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_DELETE, TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_STATEMENT, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by fireBSTriggers().

2325 {
2326  TriggerDesc *trigdesc;
2327  int i;
2328  TriggerData LocTriggerData;
2329 
2330  trigdesc = relinfo->ri_TrigDesc;
2331 
2332  if (trigdesc == NULL)
2333  return;
2334  if (!trigdesc->trig_delete_before_statement)
2335  return;
2336 
2337  LocTriggerData.type = T_TriggerData;
2338  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2340  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2341  LocTriggerData.tg_trigtuple = NULL;
2342  LocTriggerData.tg_newtuple = NULL;
2343  LocTriggerData.tg_oldtable = NULL;
2344  LocTriggerData.tg_newtable = NULL;
2345  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2346  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2347  for (i = 0; i < trigdesc->numtriggers; i++)
2348  {
2349  Trigger *trigger = &trigdesc->triggers[i];
2350  HeapTuple newtuple;
2351 
2352  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2356  continue;
2357  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2358  NULL, NULL, NULL))
2359  continue;
2360 
2361  LocTriggerData.tg_trigger = trigger;
2362  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2363  i,
2364  relinfo->ri_TrigFunctions,
2365  relinfo->ri_TrigInstrument,
2366  GetPerTupleMemoryContext(estate));
2367 
2368  if (newtuple)
2369  ereport(ERROR,
2370  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2371  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2372  }
2373 }
Relation ri_RelationDesc
Definition: execnodes.h:374
#define TRIGGER_TYPE_DELETE
Definition: pg_trigger.h:101
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:53
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:60
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
bool trig_delete_before_statement
Definition: reltrigger.h:68
#define ereport(elevel, rest)
Definition: elog.h:122
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define NULL
Definition: c.h:229
TriggerEvent tg_event
Definition: trigger.h:33
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
#define TRIGGER_TYPE_BEFORE
Definition: pg_trigger.h:99
int errmsg(const char *fmt,...)
Definition: elog.c:797
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
#define TRIGGER_TYPE_STATEMENT
Definition: pg_trigger.h:107
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
void ExecBSInsertTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2118 of file trigger.c.

References ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetPerTupleMemoryContext, i, InvalidBuffer, NULL, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TriggerDesc::trig_insert_before_statement, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_INSERT, TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_STATEMENT, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by CopyFrom(), and fireBSTriggers().

2119 {
2120  TriggerDesc *trigdesc;
2121  int i;
2122  TriggerData LocTriggerData;
2123 
2124  trigdesc = relinfo->ri_TrigDesc;
2125 
2126  if (trigdesc == NULL)
2127  return;
2128  if (!trigdesc->trig_insert_before_statement)
2129  return;
2130 
2131  LocTriggerData.type = T_TriggerData;
2132  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2134  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2135  LocTriggerData.tg_trigtuple = NULL;
2136  LocTriggerData.tg_newtuple = NULL;
2137  LocTriggerData.tg_oldtable = NULL;
2138  LocTriggerData.tg_newtable = NULL;
2139  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2140  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2141  for (i = 0; i < trigdesc->numtriggers; i++)
2142  {
2143  Trigger *trigger = &trigdesc->triggers[i];
2144  HeapTuple newtuple;
2145 
2146  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2150  continue;
2151  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2152  NULL, NULL, NULL))
2153  continue;
2154 
2155  LocTriggerData.tg_trigger = trigger;
2156  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2157  i,
2158  relinfo->ri_TrigFunctions,
2159  relinfo->ri_TrigInstrument,
2160  GetPerTupleMemoryContext(estate));
2161 
2162  if (newtuple)
2163  ereport(ERROR,
2164  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2165  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2166  }
2167 }
Relation ri_RelationDesc
Definition: execnodes.h:374
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:60
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define NULL
Definition: c.h:229
TriggerEvent tg_event
Definition: trigger.h:33
bool trig_insert_before_statement
Definition: reltrigger.h:58
#define TRIGGER_TYPE_INSERT
Definition: pg_trigger.h:100
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
#define TRIGGER_TYPE_BEFORE
Definition: pg_trigger.h:99
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:52
int errmsg(const char *fmt,...)
Definition: elog.c:797
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
#define TRIGGER_TYPE_STATEMENT
Definition: pg_trigger.h:107
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
void ExecBSTruncateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2814 of file trigger.c.

References ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetPerTupleMemoryContext, i, InvalidBuffer, NULL, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TriggerDesc::trig_truncate_before_statement, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_TRUNCATE, TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_STATEMENT, TRIGGER_TYPE_TRUNCATE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecuteTruncate().

2815 {
2816  TriggerDesc *trigdesc;
2817  int i;
2818  TriggerData LocTriggerData;
2819 
2820  trigdesc = relinfo->ri_TrigDesc;
2821 
2822  if (trigdesc == NULL)
2823  return;
2824  if (!trigdesc->trig_truncate_before_statement)
2825  return;
2826 
2827  LocTriggerData.type = T_TriggerData;
2828  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
2830  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2831  LocTriggerData.tg_trigtuple = NULL;
2832  LocTriggerData.tg_newtuple = NULL;
2833  LocTriggerData.tg_oldtable = NULL;
2834  LocTriggerData.tg_newtable = NULL;
2835  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2836  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2837  for (i = 0; i < trigdesc->numtriggers; i++)
2838  {
2839  Trigger *trigger = &trigdesc->triggers[i];
2840  HeapTuple newtuple;
2841 
2842  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2846  continue;
2847  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2848  NULL, NULL, NULL))
2849  continue;
2850 
2851  LocTriggerData.tg_trigger = trigger;
2852  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2853  i,
2854  relinfo->ri_TrigFunctions,
2855  relinfo->ri_TrigInstrument,
2856  GetPerTupleMemoryContext(estate));
2857 
2858  if (newtuple)
2859  ereport(ERROR,
2860  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2861  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2862  }
2863 }
Relation ri_RelationDesc
Definition: execnodes.h:374
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:60
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
bool trig_truncate_before_statement
Definition: reltrigger.h:71
#define ereport(elevel, rest)
Definition: elog.h:122
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
#define TRIGGER_TYPE_TRUNCATE
Definition: pg_trigger.h:103
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define NULL
Definition: c.h:229
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_TRUNCATE
Definition: trigger.h:55
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
#define TRIGGER_TYPE_BEFORE
Definition: pg_trigger.h:99
int errmsg(const char *fmt,...)
Definition: elog.c:797
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
#define TRIGGER_TYPE_STATEMENT
Definition: pg_trigger.h:107
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
void ExecBSUpdateTriggers ( EState estate,
ResultRelInfo relinfo 
)

Definition at line 2532 of file trigger.c.

References ereport, errcode(), errmsg(), ERROR, ExecCallTriggerFunc(), GetPerTupleMemoryContext, GetUpdatedColumns, i, InvalidBuffer, NULL, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TriggerDesc::trig_update_before_statement, TRIGGER_EVENT_BEFORE, TRIGGER_EVENT_UPDATE, TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_STATEMENT, TRIGGER_TYPE_UPDATE, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by fireBSTriggers().

2533 {
2534  TriggerDesc *trigdesc;
2535  int i;
2536  TriggerData LocTriggerData;
2537  Bitmapset *updatedCols;
2538 
2539  trigdesc = relinfo->ri_TrigDesc;
2540 
2541  if (trigdesc == NULL)
2542  return;
2543  if (!trigdesc->trig_update_before_statement)
2544  return;
2545 
2546  updatedCols = GetUpdatedColumns(relinfo, estate);
2547 
2548  LocTriggerData.type = T_TriggerData;
2549  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2551  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2552  LocTriggerData.tg_trigtuple = NULL;
2553  LocTriggerData.tg_newtuple = NULL;
2554  LocTriggerData.tg_oldtable = NULL;
2555  LocTriggerData.tg_newtable = NULL;
2556  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2557  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2558  for (i = 0; i < trigdesc->numtriggers; i++)
2559  {
2560  Trigger *trigger = &trigdesc->triggers[i];
2561  HeapTuple newtuple;
2562 
2563  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2567  continue;
2568  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2569  updatedCols, NULL, NULL))
2570  continue;
2571 
2572  LocTriggerData.tg_trigger = trigger;
2573  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2574  i,
2575  relinfo->ri_TrigFunctions,
2576  relinfo->ri_TrigInstrument,
2577  GetPerTupleMemoryContext(estate));
2578 
2579  if (newtuple)
2580  ereport(ERROR,
2581  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2582  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2583  }
2584 }
Relation ri_RelationDesc
Definition: execnodes.h:374
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
int errcode(int sqlerrcode)
Definition: elog.c:575
bool trig_update_before_statement
Definition: reltrigger.h:63
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define ERROR
Definition: elog.h:43
int16 tgtype
Definition: reltrigger.h:29
#define TRIGGER_EVENT_BEFORE
Definition: trigger.h:60
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
#define ereport(elevel, rest)
Definition: elog.h:122
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define TRIGGER_TYPE_UPDATE
Definition: pg_trigger.h:102
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define GetUpdatedColumns(relinfo, estate)
Definition: trigger.c:75
#define NULL
Definition: c.h:229
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:54
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
#define TRIGGER_TYPE_BEFORE
Definition: pg_trigger.h:99
int errmsg(const char *fmt,...)
Definition: elog.c:797
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
#define TRIGGER_TYPE_STATEMENT
Definition: pg_trigger.h:107
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
bool ExecIRDeleteTriggers ( EState estate,
ResultRelInfo relinfo,
HeapTuple  trigtuple 
)

Definition at line 2485 of file trigger.c.

References ExecCallTriggerFunc(), GetPerTupleMemoryContext, heap_freetuple(), i, InvalidBuffer, NULL, TriggerDesc::numtriggers, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TRIGGER_EVENT_DELETE, TRIGGER_EVENT_INSTEAD, TRIGGER_EVENT_ROW, TRIGGER_TYPE_DELETE, TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_ROW, TriggerEnabled(), TriggerDesc::triggers, and TriggerData::type.

Referenced by ExecDelete().

2487 {
2488  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2489  TriggerData LocTriggerData;
2490  HeapTuple rettuple;
2491  int i;
2492 
2493  LocTriggerData.type = T_TriggerData;
2494  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2497  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2498  LocTriggerData.tg_newtuple = NULL;
2499  LocTriggerData.tg_oldtable = NULL;
2500  LocTriggerData.tg_newtable = NULL;
2501  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2502  for (i = 0; i < trigdesc->numtriggers; i++)
2503  {
2504  Trigger *trigger = &trigdesc->triggers[i];
2505 
2506  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2510  continue;
2511  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2512  NULL, trigtuple, NULL))
2513  continue;
2514 
2515  LocTriggerData.tg_trigtuple = trigtuple;
2516  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2517  LocTriggerData.tg_trigger = trigger;
2518  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2519  i,
2520  relinfo->ri_TrigFunctions,
2521  relinfo->ri_TrigInstrument,
2522  GetPerTupleMemoryContext(estate));
2523  if (rettuple == NULL)
2524  return false; /* Delete was suppressed */
2525  if (rettuple != trigtuple)
2526  heap_freetuple(rettuple);
2527  }
2528  return true;
2529 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:58
Relation ri_RelationDesc
Definition: execnodes.h:374
#define TRIGGER_TYPE_DELETE
Definition: pg_trigger.h:101
#define TRIGGER_EVENT_DELETE
Definition: trigger.h:53
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_TYPE_INSTEAD
Definition: pg_trigger.h:104
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:62
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
#define TRIGGER_TYPE_ROW
Definition: pg_trigger.h:98
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define NULL
Definition: c.h:229
TriggerEvent tg_event
Definition: trigger.h:33
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
TupleTableSlot* ExecIRInsertTriggers ( EState estate,
ResultRelInfo relinfo,
TupleTableSlot slot 
)

Definition at line 2258 of file trigger.c.

References EState::es_trig_tuple_slot, ExecCallTriggerFunc(), ExecMaterializeSlot(), ExecSetSlotDescriptor(), ExecStoreTuple(), GetPerTupleMemoryContext, heap_freetuple(), i, InvalidBuffer, NULL, TriggerDesc::numtriggers, RelationGetDescr, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TRIGGER_EVENT_INSERT, TRIGGER_EVENT_INSTEAD, TRIGGER_EVENT_ROW, TRIGGER_TYPE_INSERT, TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_ROW, TriggerEnabled(), TriggerDesc::triggers, TupleTableSlot::tts_tupleDescriptor, and TriggerData::type.

Referenced by CopyFrom(), and ExecInsert().

2260 {
2261  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2262  HeapTuple slottuple = ExecMaterializeSlot(slot);
2263  HeapTuple newtuple = slottuple;
2264  HeapTuple oldtuple;
2265  TriggerData LocTriggerData;
2266  int i;
2267 
2268  LocTriggerData.type = T_TriggerData;
2269  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2272  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2273  LocTriggerData.tg_newtuple = NULL;
2274  LocTriggerData.tg_oldtable = NULL;
2275  LocTriggerData.tg_newtable = NULL;
2276  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2277  for (i = 0; i < trigdesc->numtriggers; i++)
2278  {
2279  Trigger *trigger = &trigdesc->triggers[i];
2280 
2281  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2285  continue;
2286  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2287  NULL, NULL, newtuple))
2288  continue;
2289 
2290  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2291  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2292  LocTriggerData.tg_trigger = trigger;
2293  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2294  i,
2295  relinfo->ri_TrigFunctions,
2296  relinfo->ri_TrigInstrument,
2297  GetPerTupleMemoryContext(estate));
2298  if (oldtuple != newtuple && oldtuple != slottuple)
2299  heap_freetuple(oldtuple);
2300  if (newtuple == NULL)
2301  return NULL; /* "do nothing" */
2302  }
2303 
2304  if (newtuple != slottuple)
2305  {
2306  /*
2307  * Return the modified tuple using the es_trig_tuple_slot. We assume
2308  * the tuple was allocated in per-tuple memory context, and therefore
2309  * will go away by itself. The tuple table slot should not try to
2310  * clear it.
2311  */
2312  TupleTableSlot *newslot = estate->es_trig_tuple_slot;
2313  TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
2314 
2315  if (newslot->tts_tupleDescriptor != tupdesc)
2316  ExecSetSlotDescriptor(newslot, tupdesc);
2317  ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
2318  slot = newslot;
2319  }
2320  return slot;
2321 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:58
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:374
#define RelationGetDescr(relation)
Definition: rel.h:429
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_TYPE_INSTEAD
Definition: pg_trigger.h:104
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:62
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
#define TRIGGER_TYPE_ROW
Definition: pg_trigger.h:98
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:427
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define NULL
Definition: c.h:229
TriggerEvent tg_event
Definition: trigger.h:33
#define TRIGGER_TYPE_INSERT
Definition: pg_trigger.h:100
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
#define TRIGGER_EVENT_INSERT
Definition: trigger.h:52
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
TupleTableSlot* ExecIRUpdateTriggers ( EState estate,
ResultRelInfo relinfo,
HeapTuple  trigtuple,
TupleTableSlot slot 
)

Definition at line 2748 of file trigger.c.

References EState::es_trig_tuple_slot, ExecCallTriggerFunc(), ExecMaterializeSlot(), ExecSetSlotDescriptor(), ExecStoreTuple(), GetPerTupleMemoryContext, heap_freetuple(), i, InvalidBuffer, NULL, TriggerDesc::numtriggers, RelationGetDescr, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ResultRelInfo::ri_TrigFunctions, ResultRelInfo::ri_TrigInstrument, T_TriggerData, TriggerData::tg_event, TriggerData::tg_newtable, TriggerData::tg_newtuple, TriggerData::tg_newtuplebuf, TriggerData::tg_oldtable, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, TriggerData::tg_trigtuplebuf, Trigger::tgtype, TRIGGER_EVENT_INSTEAD, TRIGGER_EVENT_ROW, TRIGGER_EVENT_UPDATE, TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_MATCHES, TRIGGER_TYPE_ROW, TRIGGER_TYPE_UPDATE, TriggerEnabled(), TriggerDesc::triggers, TupleTableSlot::tts_tupleDescriptor, and TriggerData::type.

Referenced by ExecUpdate().

2750 {
2751  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2752  HeapTuple slottuple = ExecMaterializeSlot(slot);
2753  HeapTuple newtuple = slottuple;
2754  TriggerData LocTriggerData;
2755  HeapTuple oldtuple;
2756  int i;
2757 
2758  LocTriggerData.type = T_TriggerData;
2759  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2762  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2763  LocTriggerData.tg_oldtable = NULL;
2764  LocTriggerData.tg_newtable = NULL;
2765  for (i = 0; i < trigdesc->numtriggers; i++)
2766  {
2767  Trigger *trigger = &trigdesc->triggers[i];
2768 
2769  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2773  continue;
2774  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2775  NULL, trigtuple, newtuple))
2776  continue;
2777 
2778  LocTriggerData.tg_trigtuple = trigtuple;
2779  LocTriggerData.tg_newtuple = oldtuple = newtuple;
2780  LocTriggerData.tg_trigtuplebuf = InvalidBuffer;
2781  LocTriggerData.tg_newtuplebuf = InvalidBuffer;
2782  LocTriggerData.tg_trigger = trigger;
2783  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2784  i,
2785  relinfo->ri_TrigFunctions,
2786  relinfo->ri_TrigInstrument,
2787  GetPerTupleMemoryContext(estate));
2788  if (oldtuple != newtuple && oldtuple != slottuple)
2789  heap_freetuple(oldtuple);
2790  if (newtuple == NULL)
2791  return NULL; /* "do nothing" */
2792  }
2793 
2794  if (newtuple != slottuple)
2795  {
2796  /*
2797  * Return the modified tuple using the es_trig_tuple_slot. We assume
2798  * the tuple was allocated in per-tuple memory context, and therefore
2799  * will go away by itself. The tuple table slot should not try to
2800  * clear it.
2801  */
2802  TupleTableSlot *newslot = estate->es_trig_tuple_slot;
2803  TupleDesc tupdesc = RelationGetDescr(relinfo->ri_RelationDesc);
2804 
2805  if (newslot->tts_tupleDescriptor != tupdesc)
2806  ExecSetSlotDescriptor(newslot, tupdesc);
2807  ExecStoreTuple(newtuple, newslot, InvalidBuffer, false);
2808  slot = newslot;
2809  }
2810  return slot;
2811 }
#define TRIGGER_EVENT_ROW
Definition: trigger.h:58
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
Relation ri_RelationDesc
Definition: execnodes.h:374
#define RelationGetDescr(relation)
Definition: rel.h:429
Buffer tg_newtuplebuf
Definition: trigger.h:39
#define TRIGGER_TYPE_MATCHES(type, level, timing, event)
Definition: pg_trigger.h:146
Instrumentation * ri_TrigInstrument
Definition: execnodes.h:381
#define InvalidBuffer
Definition: buf.h:25
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_TYPE_INSTEAD
Definition: pg_trigger.h:104
#define TRIGGER_EVENT_INSTEAD
Definition: trigger.h:62
int16 tgtype
Definition: reltrigger.h:29
Trigger * triggers
Definition: reltrigger.h:48
Buffer tg_trigtuplebuf
Definition: trigger.h:38
#define TRIGGER_TYPE_ROW
Definition: pg_trigger.h:98
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:427
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:378
int numtriggers
Definition: reltrigger.h:49
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
Trigger * tg_trigger
Definition: trigger.h:37
HeapTuple tg_newtuple
Definition: trigger.h:36
#define TRIGGER_TYPE_UPDATE
Definition: pg_trigger.h:102
static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo, Trigger *trigger, TriggerEvent event, Bitmapset *modifiedCols, HeapTuple oldtup, HeapTuple newtup)
Definition: trigger.c:3021
#define NULL
Definition: c.h:229
TriggerEvent tg_event
Definition: trigger.h:33
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
#define TRIGGER_EVENT_UPDATE
Definition: trigger.h:54
Tuplestorestate * tg_oldtable
Definition: trigger.h:40
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:460
NodeTag type
Definition: trigger.h:32
int i
Tuplestorestate * tg_newtable
Definition: trigger.h:41
static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata, int tgindx, FmgrInfo *finfo, Instrumentation *instr, MemoryContext per_tuple_context)
Definition: trigger.c:2024
FmgrInfo * ri_TrigFunctions
Definition: execnodes.h:379
Relation tg_relation
Definition: trigger.h:34
void FreeTriggerDesc ( TriggerDesc trigdesc)

Definition at line 1888 of file trigger.c.

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

Referenced by RelationBuildTriggers(), and RelationDestroyRelation().

1889 {
1890  Trigger *trigger;
1891  int i;
1892 
1893  if (trigdesc == NULL)
1894  return;
1895 
1896  trigger = trigdesc->triggers;
1897  for (i = 0; i < trigdesc->numtriggers; i++)
1898  {
1899  pfree(trigger->tgname);
1900  if (trigger->tgnattr > 0)
1901  pfree(trigger->tgattr);
1902  if (trigger->tgnargs > 0)
1903  {
1904  while (--(trigger->tgnargs) >= 0)
1905  pfree(trigger->tgargs[trigger->tgnargs]);
1906  pfree(trigger->tgargs);
1907  }
1908  if (trigger->tgqual)
1909  pfree(trigger->tgqual);
1910  if (trigger->tgoldtable)
1911  pfree(trigger->tgoldtable);
1912  if (trigger->tgnewtable)
1913  pfree(trigger->tgnewtable);
1914  trigger++;
1915  }
1916  pfree(trigdesc->triggers);
1917  pfree(trigdesc);
1918 }
void pfree(void *pointer)
Definition: mcxt.c:950
char * tgqual
Definition: reltrigger.h:41
char * tgname
Definition: reltrigger.h:27
Trigger * triggers
Definition: reltrigger.h:48
int numtriggers
Definition: reltrigger.h:49
char ** tgargs
Definition: reltrigger.h:40
int16 * tgattr
Definition: reltrigger.h:39
char * tgnewtable
Definition: reltrigger.h:43
#define NULL
Definition: c.h:229
int16 tgnattr
Definition: reltrigger.h:38
int i
int16 tgnargs
Definition: reltrigger.h:37
char * tgoldtable
Definition: reltrigger.h:42
Oid get_trigger_oid ( Oid  relid,
const char *  name,
bool  missing_ok 
)

Definition at line 1275 of file trigger.c.

References AccessShareLock, Anum_pg_trigger_tgname, Anum_pg_trigger_tgrelid, BTEqualStrategyNumber, CStringGetDatum, ereport, errcode(), errmsg(), ERROR, get_rel_name(), heap_close, heap_open(), HeapTupleGetOid, HeapTupleIsValid, InvalidOid, NULL, ObjectIdGetDatum, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), TriggerRelationId, and TriggerRelidNameIndexId.

Referenced by get_object_address_relobject().

1276 {
1277  Relation tgrel;
1278  ScanKeyData skey[2];
1279  SysScanDesc tgscan;
1280  HeapTuple tup;
1281  Oid oid;
1282 
1283  /*
1284  * Find the trigger, verify permissions, set up object address
1285  */
1287 
1288  ScanKeyInit(&skey[0],
1290  BTEqualStrategyNumber, F_OIDEQ,
1291  ObjectIdGetDatum(relid));
1292  ScanKeyInit(&skey[1],
1294  BTEqualStrategyNumber, F_NAMEEQ,
1295  CStringGetDatum(trigname));
1296 
1297  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1298  NULL, 2, skey);
1299 
1300  tup = systable_getnext(tgscan);
1301 
1302  if (!HeapTupleIsValid(tup))
1303  {
1304  if (!missing_ok)
1305  ereport(ERROR,
1306  (errcode(ERRCODE_UNDEFINED_OBJECT),
1307  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1308  trigname, get_rel_name(relid))));
1309  oid = InvalidOid;
1310  }
1311  else
1312  {
1313  oid = HeapTupleGetOid(tup);
1314  }
1315 
1316  systable_endscan(tgscan);
1317  heap_close(tgrel, AccessShareLock);
1318  return oid;
1319 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:575
#define heap_close(r, l)
Definition: heapam.h:97
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:328
#define TriggerRelidNameIndexId
Definition: indexing.h:249
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define CStringGetDatum(X)
Definition: postgres.h:584
#define ereport(elevel, rest)
Definition: elog.h:122
#define Anum_pg_trigger_tgrelid
Definition: pg_trigger.h:79
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define InvalidOid
Definition: postgres_ext.h:36
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Anum_pg_trigger_tgname
Definition: pg_trigger.h:80
#define TriggerRelationId
Definition: pg_trigger.h:34
int errmsg(const char *fmt,...)
Definition: elog.c:797
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void RelationBuildTriggers ( Relation  relation)

Definition at line 1605 of file trigger.c.

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

Referenced by RelationBuildDesc(), and RelationCacheInitializePhase3().

1606 {
1607  TriggerDesc *trigdesc;
1608  int numtrigs;
1609  int maxtrigs;
1610  Trigger *triggers;
1611  Relation tgrel;
1612  ScanKeyData skey;
1613  SysScanDesc tgscan;
1614  HeapTuple htup;
1615  MemoryContext oldContext;
1616  int i;
1617 
1618  /*
1619  * Allocate a working array to hold the triggers (the array is extended if
1620  * necessary)
1621  */
1622  maxtrigs = 16;
1623  triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
1624  numtrigs = 0;
1625 
1626  /*
1627  * Note: since we scan the triggers using TriggerRelidNameIndexId, we will
1628  * be reading the triggers in name order, except possibly during
1629  * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
1630  * ensures that triggers will be fired in name order.
1631  */
1632  ScanKeyInit(&skey,
1634  BTEqualStrategyNumber, F_OIDEQ,
1635  ObjectIdGetDatum(RelationGetRelid(relation)));
1636 
1638  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1639  NULL, 1, &skey);
1640 
1641  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
1642  {
1643  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
1644  Trigger *build;
1645  Datum datum;
1646  bool isnull;
1647 
1648  if (numtrigs >= maxtrigs)
1649  {
1650  maxtrigs *= 2;
1651  triggers = (Trigger *) repalloc(triggers, maxtrigs * sizeof(Trigger));
1652  }
1653  build = &(triggers[numtrigs]);
1654 
1655  build->tgoid = HeapTupleGetOid(htup);
1657  NameGetDatum(&pg_trigger->tgname)));
1658  build->tgfoid = pg_trigger->tgfoid;
1659  build->tgtype = pg_trigger->tgtype;
1660  build->tgenabled = pg_trigger->tgenabled;
1661  build->tgisinternal = pg_trigger->tgisinternal;
1662  build->tgconstrrelid = pg_trigger->tgconstrrelid;
1663  build->tgconstrindid = pg_trigger->tgconstrindid;
1664  build->tgconstraint = pg_trigger->tgconstraint;
1665  build->tgdeferrable = pg_trigger->tgdeferrable;
1666  build->tginitdeferred = pg_trigger->tginitdeferred;
1667  build->tgnargs = pg_trigger->tgnargs;
1668  /* tgattr is first var-width field, so OK to access directly */
1669  build->tgnattr = pg_trigger->tgattr.dim1;
1670  if (build->tgnattr > 0)
1671  {
1672  build->tgattr = (int16 *) palloc(build->tgnattr * sizeof(int16));
1673  memcpy(build->tgattr, &(pg_trigger->tgattr.values),
1674  build->tgnattr * sizeof(int16));
1675  }
1676  else
1677  build->tgattr = NULL;
1678  if (build->tgnargs > 0)
1679  {
1680  bytea *val;
1681  char *p;
1682 
1683  val = DatumGetByteaPP(fastgetattr(htup,
1685  tgrel->rd_att, &isnull));
1686  if (isnull)
1687  elog(ERROR, "tgargs is null in trigger for relation \"%s\"",
1688  RelationGetRelationName(relation));
1689  p = (char *) VARDATA_ANY(val);
1690  build->tgargs = (char **) palloc(build->tgnargs * sizeof(char *));
1691  for (i = 0; i < build->tgnargs; i++)
1692  {
1693  build->tgargs[i] = pstrdup(p);
1694  p += strlen(p) + 1;
1695  }
1696  }
1697  else
1698  build->tgargs = NULL;
1699 
1701  tgrel->rd_att, &isnull);
1702  if (!isnull)
1703  build->tgoldtable =
1705  else
1706  build->tgoldtable = NULL;
1707 
1709  tgrel->rd_att, &isnull);
1710  if (!isnull)
1711  build->tgnewtable =
1713  else
1714  build->tgnewtable = NULL;
1715 
1716  datum = fastgetattr(htup, Anum_pg_trigger_tgqual,
1717  tgrel->rd_att, &isnull);
1718  if (!isnull)
1719  build->tgqual = TextDatumGetCString(datum);
1720  else
1721  build->tgqual = NULL;
1722 
1723  numtrigs++;
1724  }
1725 
1726  systable_endscan(tgscan);
1727  heap_close(tgrel, AccessShareLock);
1728 
1729  /* There might not be any triggers */
1730  if (numtrigs == 0)
1731  {
1732  pfree(triggers);
1733  return;
1734  }
1735 
1736  /* Build trigdesc */
1737  trigdesc = (TriggerDesc *) palloc0(sizeof(TriggerDesc));
1738  trigdesc->triggers = triggers;
1739  trigdesc->numtriggers = numtrigs;
1740  for (i = 0; i < numtrigs; i++)
1741  SetTriggerFlags(trigdesc, &(triggers[i]));
1742 
1743  /* Copy completed trigdesc into cache storage */
1745  relation->trigdesc = CopyTriggerDesc(trigdesc);
1746  MemoryContextSwitchTo(oldContext);