PostgreSQL Source Code  git master
trigger.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * trigger.c
4  * PostgreSQL TRIGGERs support code.
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/backend/commands/trigger.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15 
16 #include "access/genam.h"
17 #include "access/htup_details.h"
18 #include "access/relation.h"
19 #include "access/sysattr.h"
20 #include "access/table.h"
21 #include "access/tableam.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/dependency.h"
25 #include "catalog/index.h"
26 #include "catalog/indexing.h"
27 #include "catalog/objectaccess.h"
28 #include "catalog/partition.h"
29 #include "catalog/pg_constraint.h"
30 #include "catalog/pg_inherits.h"
31 #include "catalog/pg_proc.h"
32 #include "catalog/pg_trigger.h"
33 #include "catalog/pg_type.h"
34 #include "commands/dbcommands.h"
35 #include "commands/defrem.h"
36 #include "commands/trigger.h"
37 #include "executor/executor.h"
38 #include "executor/execPartition.h"
39 #include "miscadmin.h"
40 #include "nodes/bitmapset.h"
41 #include "nodes/makefuncs.h"
42 #include "optimizer/optimizer.h"
43 #include "parser/parse_clause.h"
44 #include "parser/parse_collate.h"
45 #include "parser/parse_func.h"
46 #include "parser/parse_relation.h"
47 #include "parser/parsetree.h"
48 #include "partitioning/partdesc.h"
49 #include "pgstat.h"
50 #include "rewrite/rewriteManip.h"
51 #include "storage/bufmgr.h"
52 #include "storage/lmgr.h"
53 #include "tcop/utility.h"
54 #include "utils/acl.h"
55 #include "utils/builtins.h"
56 #include "utils/bytea.h"
57 #include "utils/fmgroids.h"
58 #include "utils/inval.h"
59 #include "utils/lsyscache.h"
60 #include "utils/memutils.h"
61 #include "utils/rel.h"
62 #include "utils/snapmgr.h"
63 #include "utils/syscache.h"
64 #include "utils/tuplestore.h"
65 
66 
67 /* GUC variables */
69 
70 /* How many levels deep into trigger execution are we? */
71 static int MyTriggerDepth = 0;
72 
73 /* Local function prototypes */
74 static void renametrig_internal(Relation tgrel, Relation targetrel,
75  HeapTuple trigtup, const char *newname,
76  const char *expected_name);
77 static void renametrig_partition(Relation tgrel, Oid partitionId,
78  Oid parentTriggerOid, const char *newname,
79  const char *expected_name);
80 static void SetTriggerFlags(TriggerDesc *trigdesc, Trigger *trigger);
81 static bool GetTupleForTrigger(EState *estate,
82  EPQState *epqstate,
83  ResultRelInfo *relinfo,
84  ItemPointer tid,
85  LockTupleMode lockmode,
86  TupleTableSlot *oldslot,
87  TupleTableSlot **newSlot);
88 static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo,
89  Trigger *trigger, TriggerEvent event,
90  Bitmapset *modifiedCols,
91  TupleTableSlot *oldslot, TupleTableSlot *newslot);
93  int tgindx,
94  FmgrInfo *finfo,
95  Instrumentation *instr,
96  MemoryContext per_tuple_context);
97 static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
98  int event, bool row_trigger,
99  TupleTableSlot *oldtup, TupleTableSlot *newtup,
100  List *recheckIndexes, Bitmapset *modifiedCols,
101  TransitionCaptureState *transition_capture);
102 static void AfterTriggerEnlargeQueryState(void);
103 static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType);
104 
105 
106 /*
107  * Create a trigger. Returns the address of the created trigger.
108  *
109  * queryString is the source text of the CREATE TRIGGER command.
110  * This must be supplied if a whenClause is specified, else it can be NULL.
111  *
112  * relOid, if nonzero, is the relation on which the trigger should be
113  * created. If zero, the name provided in the statement will be looked up.
114  *
115  * refRelOid, if nonzero, is the relation to which the constraint trigger
116  * refers. If zero, the constraint relation name provided in the statement
117  * will be looked up as needed.
118  *
119  * constraintOid, if nonzero, says that this trigger is being created
120  * internally to implement that constraint. A suitable pg_depend entry will
121  * be made to link the trigger to that constraint. constraintOid is zero when
122  * executing a user-entered CREATE TRIGGER command. (For CREATE CONSTRAINT
123  * TRIGGER, we build a pg_constraint entry internally.)
124  *
125  * indexOid, if nonzero, is the OID of an index associated with the constraint.
126  * We do nothing with this except store it into pg_trigger.tgconstrindid;
127  * but when creating a trigger for a deferrable unique constraint on a
128  * partitioned table, its children are looked up. Note we don't cope with
129  * invalid indexes in that case.
130  *
131  * funcoid, if nonzero, is the OID of the function to invoke. When this is
132  * given, stmt->funcname is ignored.
133  *
134  * parentTriggerOid, if nonzero, is a trigger that begets this one; so that
135  * if that trigger is dropped, this one should be too. There are two cases
136  * when a nonzero value is passed for this: 1) when this function recurses to
137  * create the trigger on partitions, 2) when creating child foreign key
138  * triggers; see CreateFKCheckTrigger() and createForeignKeyActionTriggers().
139  *
140  * If whenClause is passed, it is an already-transformed expression for
141  * WHEN. In this case, we ignore any that may come in stmt->whenClause.
142  *
143  * If isInternal is true then this is an internally-generated trigger.
144  * This argument sets the tgisinternal field of the pg_trigger entry, and
145  * if true causes us to modify the given trigger name to ensure uniqueness.
146  *
147  * When isInternal is not true we require ACL_TRIGGER permissions on the
148  * relation, as well as ACL_EXECUTE on the trigger function. For internal
149  * triggers the caller must apply any required permission checks.
150  *
151  * When called on partitioned tables, this function recurses to create the
152  * trigger on all the partitions, except if isInternal is true, in which
153  * case caller is expected to execute recursion on its own. in_partition
154  * indicates such a recursive call; outside callers should pass "false"
155  * (but see CloneRowTriggersToPartition).
156  */
158 CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
159  Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid,
160  Oid funcoid, Oid parentTriggerOid, Node *whenClause,
161  bool isInternal, bool in_partition)
162 {
163  return
164  CreateTriggerFiringOn(stmt, queryString, relOid, refRelOid,
165  constraintOid, indexOid, funcoid,
166  parentTriggerOid, whenClause, isInternal,
167  in_partition, TRIGGER_FIRES_ON_ORIGIN);
168 }
169 
170 /*
171  * Like the above; additionally the firing condition
172  * (always/origin/replica/disabled) can be specified.
173  */
175 CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
176  Oid relOid, Oid refRelOid, Oid constraintOid,
177  Oid indexOid, Oid funcoid, Oid parentTriggerOid,
178  Node *whenClause, bool isInternal, bool in_partition,
179  char trigger_fires_when)
180 {
181  int16 tgtype;
182  int ncolumns;
183  int16 *columns;
184  int2vector *tgattr;
185  List *whenRtable;
186  char *qual;
187  Datum values[Natts_pg_trigger];
188  bool nulls[Natts_pg_trigger];
189  Relation rel;
190  AclResult aclresult;
191  Relation tgrel;
192  Relation pgrel;
193  HeapTuple tuple = NULL;
194  Oid funcrettype;
195  Oid trigoid = InvalidOid;
196  char internaltrigname[NAMEDATALEN];
197  char *trigname;
198  Oid constrrelid = InvalidOid;
199  ObjectAddress myself,
200  referenced;
201  char *oldtablename = NULL;
202  char *newtablename = NULL;
203  bool partition_recurse;
204  bool trigger_exists = false;
205  Oid existing_constraint_oid = InvalidOid;
206  bool existing_isInternal = false;
207  bool existing_isClone = false;
208 
209  if (OidIsValid(relOid))
210  rel = table_open(relOid, ShareRowExclusiveLock);
211  else
213 
214  /*
215  * Triggers must be on tables or views, and there are additional
216  * relation-type-specific restrictions.
217  */
218  if (rel->rd_rel->relkind == RELKIND_RELATION)
219  {
220  /* Tables can't have INSTEAD OF triggers */
221  if (stmt->timing != TRIGGER_TYPE_BEFORE &&
222  stmt->timing != TRIGGER_TYPE_AFTER)
223  ereport(ERROR,
224  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
225  errmsg("\"%s\" is a table",
227  errdetail("Tables cannot have INSTEAD OF triggers.")));
228  }
229  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
230  {
231  /* Partitioned tables can't have INSTEAD OF triggers */
232  if (stmt->timing != TRIGGER_TYPE_BEFORE &&
233  stmt->timing != TRIGGER_TYPE_AFTER)
234  ereport(ERROR,
235  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
236  errmsg("\"%s\" is a table",
238  errdetail("Tables cannot have INSTEAD OF triggers.")));
239 
240  /*
241  * FOR EACH ROW triggers have further restrictions
242  */
243  if (stmt->row)
244  {
245  /*
246  * Disallow use of transition tables.
247  *
248  * Note that we have another restriction about transition tables
249  * in partitions; search for 'has_superclass' below for an
250  * explanation. The check here is just to protect from the fact
251  * that if we allowed it here, the creation would succeed for a
252  * partitioned table with no partitions, but would be blocked by
253  * the other restriction when the first partition was created,
254  * which is very unfriendly behavior.
255  */
256  if (stmt->transitionRels != NIL)
257  ereport(ERROR,
258  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
259  errmsg("\"%s\" is a partitioned table",
261  errdetail("Triggers on partitioned tables cannot have transition tables.")));
262  }
263  }
264  else if (rel->rd_rel->relkind == RELKIND_VIEW)
265  {
266  /*
267  * Views can have INSTEAD OF triggers (which we check below are
268  * row-level), or statement-level BEFORE/AFTER triggers.
269  */
270  if (stmt->timing != TRIGGER_TYPE_INSTEAD && stmt->row)
271  ereport(ERROR,
272  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
273  errmsg("\"%s\" is a view",
275  errdetail("Views cannot have row-level BEFORE or AFTER triggers.")));
276  /* Disallow TRUNCATE triggers on VIEWs */
277  if (TRIGGER_FOR_TRUNCATE(stmt->events))
278  ereport(ERROR,
279  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
280  errmsg("\"%s\" is a view",
282  errdetail("Views cannot have TRUNCATE triggers.")));
283  }
284  else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
285  {
286  if (stmt->timing != TRIGGER_TYPE_BEFORE &&
287  stmt->timing != TRIGGER_TYPE_AFTER)
288  ereport(ERROR,
289  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
290  errmsg("\"%s\" is a foreign table",
292  errdetail("Foreign tables cannot have INSTEAD OF triggers.")));
293 
294  if (TRIGGER_FOR_TRUNCATE(stmt->events))
295  ereport(ERROR,
296  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
297  errmsg("\"%s\" is a foreign table",
299  errdetail("Foreign tables cannot have TRUNCATE triggers.")));
300 
301  /*
302  * We disallow constraint triggers to protect the assumption that
303  * triggers on FKs can't be deferred. See notes with AfterTriggers
304  * data structures, below.
305  */
306  if (stmt->isconstraint)
307  ereport(ERROR,
308  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
309  errmsg("\"%s\" is a foreign table",
311  errdetail("Foreign tables cannot have constraint triggers.")));
312  }
313  else
314  ereport(ERROR,
315  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
316  errmsg("relation \"%s\" cannot have triggers",
318  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
319 
321  ereport(ERROR,
322  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
323  errmsg("permission denied: \"%s\" is a system catalog",
324  RelationGetRelationName(rel))));
325 
326  if (stmt->isconstraint)
327  {
328  /*
329  * We must take a lock on the target relation to protect against
330  * concurrent drop. It's not clear that AccessShareLock is strong
331  * enough, but we certainly need at least that much... otherwise, we
332  * might end up creating a pg_constraint entry referencing a
333  * nonexistent table.
334  */
335  if (OidIsValid(refRelOid))
336  {
337  LockRelationOid(refRelOid, AccessShareLock);
338  constrrelid = refRelOid;
339  }
340  else if (stmt->constrrel != NULL)
341  constrrelid = RangeVarGetRelid(stmt->constrrel, AccessShareLock,
342  false);
343  }
344 
345  /* permission checks */
346  if (!isInternal)
347  {
348  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
349  ACL_TRIGGER);
350  if (aclresult != ACLCHECK_OK)
351  aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
353 
354  if (OidIsValid(constrrelid))
355  {
356  aclresult = pg_class_aclcheck(constrrelid, GetUserId(),
357  ACL_TRIGGER);
358  if (aclresult != ACLCHECK_OK)
359  aclcheck_error(aclresult, get_relkind_objtype(get_rel_relkind(constrrelid)),
360  get_rel_name(constrrelid));
361  }
362  }
363 
364  /*
365  * When called on a partitioned table to create a FOR EACH ROW trigger
366  * that's not internal, we create one trigger for each partition, too.
367  *
368  * For that, we'd better hold lock on all of them ahead of time.
369  */
370  partition_recurse = !isInternal && stmt->row &&
371  rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
372  if (partition_recurse)
374  ShareRowExclusiveLock, NULL));
375 
376  /* Compute tgtype */
377  TRIGGER_CLEAR_TYPE(tgtype);
378  if (stmt->row)
379  TRIGGER_SETT_ROW(tgtype);
380  tgtype |= stmt->timing;
381  tgtype |= stmt->events;
382 
383  /* Disallow ROW-level TRUNCATE triggers */
384  if (TRIGGER_FOR_ROW(tgtype) && TRIGGER_FOR_TRUNCATE(tgtype))
385  ereport(ERROR,
386  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
387  errmsg("TRUNCATE FOR EACH ROW triggers are not supported")));
388 
389  /* INSTEAD triggers must be row-level, and can't have WHEN or columns */
390  if (TRIGGER_FOR_INSTEAD(tgtype))
391  {
392  if (!TRIGGER_FOR_ROW(tgtype))
393  ereport(ERROR,
394  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
395  errmsg("INSTEAD OF triggers must be FOR EACH ROW")));
396  if (stmt->whenClause)
397  ereport(ERROR,
398  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
399  errmsg("INSTEAD OF triggers cannot have WHEN conditions")));
400  if (stmt->columns != NIL)
401  ereport(ERROR,
402  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
403  errmsg("INSTEAD OF triggers cannot have column lists")));
404  }
405 
406  /*
407  * We don't yet support naming ROW transition variables, but the parser
408  * recognizes the syntax so we can give a nicer message here.
409  *
410  * Per standard, REFERENCING TABLE names are only allowed on AFTER
411  * triggers. Per standard, REFERENCING ROW names are not allowed with FOR
412  * EACH STATEMENT. Per standard, each OLD/NEW, ROW/TABLE permutation is
413  * only allowed once. Per standard, OLD may not be specified when
414  * creating a trigger only for INSERT, and NEW may not be specified when
415  * creating a trigger only for DELETE.
416  *
417  * Notice that the standard allows an AFTER ... FOR EACH ROW trigger to
418  * reference both ROW and TABLE transition data.
419  */
420  if (stmt->transitionRels != NIL)
421  {
422  List *varList = stmt->transitionRels;
423  ListCell *lc;
424 
425  foreach(lc, varList)
426  {
428 
429  if (!(tt->isTable))
430  ereport(ERROR,
431  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
432  errmsg("ROW variable naming in the REFERENCING clause is not supported"),
433  errhint("Use OLD TABLE or NEW TABLE for naming transition tables.")));
434 
435  /*
436  * Because of the above test, we omit further ROW-related testing
437  * below. If we later allow naming OLD and NEW ROW variables,
438  * adjustments will be needed below.
439  */
440 
441  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
442  ereport(ERROR,
443  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
444  errmsg("\"%s\" is a foreign table",
446  errdetail("Triggers on foreign tables cannot have transition tables.")));
447 
448  if (rel->rd_rel->relkind == RELKIND_VIEW)
449  ereport(ERROR,
450  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
451  errmsg("\"%s\" is a view",
453  errdetail("Triggers on views cannot have transition tables.")));
454 
455  /*
456  * We currently don't allow row-level triggers with transition
457  * tables on partition or inheritance children. Such triggers
458  * would somehow need to see tuples converted to the format of the
459  * table they're attached to, and it's not clear which subset of
460  * tuples each child should see. See also the prohibitions in
461  * ATExecAttachPartition() and ATExecAddInherit().
462  */
463  if (TRIGGER_FOR_ROW(tgtype) && has_superclass(rel->rd_id))
464  {
465  /* Use appropriate error message. */
466  if (rel->rd_rel->relispartition)
467  ereport(ERROR,
468  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
469  errmsg("ROW triggers with transition tables are not supported on partitions")));
470  else
471  ereport(ERROR,
472  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
473  errmsg("ROW triggers with transition tables are not supported on inheritance children")));
474  }
475 
476  if (stmt->timing != TRIGGER_TYPE_AFTER)
477  ereport(ERROR,
478  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
479  errmsg("transition table name can only be specified for an AFTER trigger")));
480 
481  if (TRIGGER_FOR_TRUNCATE(tgtype))
482  ereport(ERROR,
483  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
484  errmsg("TRUNCATE triggers with transition tables are not supported")));
485 
486  /*
487  * We currently don't allow multi-event triggers ("INSERT OR
488  * UPDATE") with transition tables, because it's not clear how to
489  * handle INSERT ... ON CONFLICT statements which can fire both
490  * INSERT and UPDATE triggers. We show the inserted tuples to
491  * INSERT triggers and the updated tuples to UPDATE triggers, but
492  * it's not yet clear what INSERT OR UPDATE trigger should see.
493  * This restriction could be lifted if we can decide on the right
494  * semantics in a later release.
495  */
496  if (((TRIGGER_FOR_INSERT(tgtype) ? 1 : 0) +
497  (TRIGGER_FOR_UPDATE(tgtype) ? 1 : 0) +
498  (TRIGGER_FOR_DELETE(tgtype) ? 1 : 0)) != 1)
499  ereport(ERROR,
500  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
501  errmsg("transition tables cannot be specified for triggers with more than one event")));
502 
503  /*
504  * We currently don't allow column-specific triggers with
505  * transition tables. Per spec, that seems to require
506  * accumulating separate transition tables for each combination of
507  * columns, which is a lot of work for a rather marginal feature.
508  */
509  if (stmt->columns != NIL)
510  ereport(ERROR,
511  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
512  errmsg("transition tables cannot be specified for triggers with column lists")));
513 
514  /*
515  * We disallow constraint triggers with transition tables, to
516  * protect the assumption that such triggers can't be deferred.
517  * See notes with AfterTriggers data structures, below.
518  *
519  * Currently this is enforced by the grammar, so just Assert here.
520  */
521  Assert(!stmt->isconstraint);
522 
523  if (tt->isNew)
524  {
525  if (!(TRIGGER_FOR_INSERT(tgtype) ||
526  TRIGGER_FOR_UPDATE(tgtype)))
527  ereport(ERROR,
528  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
529  errmsg("NEW TABLE can only be specified for an INSERT or UPDATE trigger")));
530 
531  if (newtablename != NULL)
532  ereport(ERROR,
533  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
534  errmsg("NEW TABLE cannot be specified multiple times")));
535 
536  newtablename = tt->name;
537  }
538  else
539  {
540  if (!(TRIGGER_FOR_DELETE(tgtype) ||
541  TRIGGER_FOR_UPDATE(tgtype)))
542  ereport(ERROR,
543  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
544  errmsg("OLD TABLE can only be specified for a DELETE or UPDATE trigger")));
545 
546  if (oldtablename != NULL)
547  ereport(ERROR,
548  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
549  errmsg("OLD TABLE cannot be specified multiple times")));
550 
551  oldtablename = tt->name;
552  }
553  }
554 
555  if (newtablename != NULL && oldtablename != NULL &&
556  strcmp(newtablename, oldtablename) == 0)
557  ereport(ERROR,
558  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
559  errmsg("OLD TABLE name and NEW TABLE name cannot be the same")));
560  }
561 
562  /*
563  * Parse the WHEN clause, if any and we weren't passed an already
564  * transformed one.
565  *
566  * Note that as a side effect, we fill whenRtable when parsing. If we got
567  * an already parsed clause, this does not occur, which is what we want --
568  * no point in adding redundant dependencies below.
569  */
570  if (!whenClause && stmt->whenClause)
571  {
572  ParseState *pstate;
573  ParseNamespaceItem *nsitem;
574  List *varList;
575  ListCell *lc;
576 
577  /* Set up a pstate to parse with */
578  pstate = make_parsestate(NULL);
579  pstate->p_sourcetext = queryString;
580 
581  /*
582  * Set up nsitems for OLD and NEW references.
583  *
584  * 'OLD' must always have varno equal to 1 and 'NEW' equal to 2.
585  */
586  nsitem = addRangeTableEntryForRelation(pstate, rel,
588  makeAlias("old", NIL),
589  false, false);
590  addNSItemToQuery(pstate, nsitem, false, true, true);
591  nsitem = addRangeTableEntryForRelation(pstate, rel,
593  makeAlias("new", NIL),
594  false, false);
595  addNSItemToQuery(pstate, nsitem, false, true, true);
596 
597  /* Transform expression. Copy to be sure we don't modify original */
598  whenClause = transformWhereClause(pstate,
599  copyObject(stmt->whenClause),
601  "WHEN");
602  /* we have to fix its collations too */
603  assign_expr_collations(pstate, whenClause);
604 
605  /*
606  * Check for disallowed references to OLD/NEW.
607  *
608  * NB: pull_var_clause is okay here only because we don't allow
609  * subselects in WHEN clauses; it would fail to examine the contents
610  * of subselects.
611  */
612  varList = pull_var_clause(whenClause, 0);
613  foreach(lc, varList)
614  {
615  Var *var = (Var *) lfirst(lc);
616 
617  switch (var->varno)
618  {
619  case PRS2_OLD_VARNO:
620  if (!TRIGGER_FOR_ROW(tgtype))
621  ereport(ERROR,
622  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
623  errmsg("statement trigger's WHEN condition cannot reference column values"),
624  parser_errposition(pstate, var->location)));
625  if (TRIGGER_FOR_INSERT(tgtype))
626  ereport(ERROR,
627  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
628  errmsg("INSERT trigger's WHEN condition cannot reference OLD values"),
629  parser_errposition(pstate, var->location)));
630  /* system columns are okay here */
631  break;
632  case PRS2_NEW_VARNO:
633  if (!TRIGGER_FOR_ROW(tgtype))
634  ereport(ERROR,
635  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
636  errmsg("statement trigger's WHEN condition cannot reference column values"),
637  parser_errposition(pstate, var->location)));
638  if (TRIGGER_FOR_DELETE(tgtype))
639  ereport(ERROR,
640  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
641  errmsg("DELETE trigger's WHEN condition cannot reference NEW values"),
642  parser_errposition(pstate, var->location)));
643  if (var->varattno < 0 && TRIGGER_FOR_BEFORE(tgtype))
644  ereport(ERROR,
645  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
646  errmsg("BEFORE trigger's WHEN condition cannot reference NEW system columns"),
647  parser_errposition(pstate, var->location)));
648  if (TRIGGER_FOR_BEFORE(tgtype) &&
649  var->varattno == 0 &&
650  RelationGetDescr(rel)->constr &&
651  RelationGetDescr(rel)->constr->has_generated_stored)
652  ereport(ERROR,
653  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
654  errmsg("BEFORE trigger's WHEN condition cannot reference NEW generated columns"),
655  errdetail("A whole-row reference is used and the table contains generated columns."),
656  parser_errposition(pstate, var->location)));
657  if (TRIGGER_FOR_BEFORE(tgtype) &&
658  var->varattno > 0 &&
659  TupleDescAttr(RelationGetDescr(rel), var->varattno - 1)->attgenerated)
660  ereport(ERROR,
661  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
662  errmsg("BEFORE trigger's WHEN condition cannot reference NEW generated columns"),
663  errdetail("Column \"%s\" is a generated column.",
664  NameStr(TupleDescAttr(RelationGetDescr(rel), var->varattno - 1)->attname)),
665  parser_errposition(pstate, var->location)));
666  break;
667  default:
668  /* can't happen without add_missing_from, so just elog */
669  elog(ERROR, "trigger WHEN condition cannot contain references to other relations");
670  break;
671  }
672  }
673 
674  /* we'll need the rtable for recordDependencyOnExpr */
675  whenRtable = pstate->p_rtable;
676 
677  qual = nodeToString(whenClause);
678 
679  free_parsestate(pstate);
680  }
681  else if (!whenClause)
682  {
683  whenClause = NULL;
684  whenRtable = NIL;
685  qual = NULL;
686  }
687  else
688  {
689  qual = nodeToString(whenClause);
690  whenRtable = NIL;
691  }
692 
693  /*
694  * Find and validate the trigger function.
695  */
696  if (!OidIsValid(funcoid))
697  funcoid = LookupFuncName(stmt->funcname, 0, NULL, false);
698  if (!isInternal)
699  {
700  aclresult = pg_proc_aclcheck(funcoid, GetUserId(), ACL_EXECUTE);
701  if (aclresult != ACLCHECK_OK)
702  aclcheck_error(aclresult, OBJECT_FUNCTION,
703  NameListToString(stmt->funcname));
704  }
705  funcrettype = get_func_rettype(funcoid);
706  if (funcrettype != TRIGGEROID)
707  ereport(ERROR,
708  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
709  errmsg("function %s must return type %s",
710  NameListToString(stmt->funcname), "trigger")));
711 
712  /*
713  * Scan pg_trigger to see if there is already a trigger of the same name.
714  * Skip this for internally generated triggers, since we'll modify the
715  * name to be unique below.
716  *
717  * NOTE that this is cool only because we have ShareRowExclusiveLock on
718  * the relation, so the trigger set won't be changing underneath us.
719  */
720  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
721  if (!isInternal)
722  {
723  ScanKeyData skeys[2];
724  SysScanDesc tgscan;
725 
726  ScanKeyInit(&skeys[0],
727  Anum_pg_trigger_tgrelid,
728  BTEqualStrategyNumber, F_OIDEQ,
730 
731  ScanKeyInit(&skeys[1],
732  Anum_pg_trigger_tgname,
733  BTEqualStrategyNumber, F_NAMEEQ,
734  CStringGetDatum(stmt->trigname));
735 
736  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
737  NULL, 2, skeys);
738 
739  /* There should be at most one matching tuple */
740  if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
741  {
742  Form_pg_trigger oldtrigger = (Form_pg_trigger) GETSTRUCT(tuple);
743 
744  trigoid = oldtrigger->oid;
745  existing_constraint_oid = oldtrigger->tgconstraint;
746  existing_isInternal = oldtrigger->tgisinternal;
747  existing_isClone = OidIsValid(oldtrigger->tgparentid);
748  trigger_exists = true;
749  /* copy the tuple to use in CatalogTupleUpdate() */
750  tuple = heap_copytuple(tuple);
751  }
752  systable_endscan(tgscan);
753  }
754 
755  if (!trigger_exists)
756  {
757  /* Generate the OID for the new trigger. */
758  trigoid = GetNewOidWithIndex(tgrel, TriggerOidIndexId,
759  Anum_pg_trigger_oid);
760  }
761  else
762  {
763  /*
764  * If OR REPLACE was specified, we'll replace the old trigger;
765  * otherwise complain about the duplicate name.
766  */
767  if (!stmt->replace)
768  ereport(ERROR,
770  errmsg("trigger \"%s\" for relation \"%s\" already exists",
771  stmt->trigname, RelationGetRelationName(rel))));
772 
773  /*
774  * An internal trigger or a child trigger (isClone) cannot be replaced
775  * by a user-defined trigger. However, skip this test when
776  * in_partition, because then we're recursing from a partitioned table
777  * and the check was made at the parent level.
778  */
779  if ((existing_isInternal || existing_isClone) &&
780  !isInternal && !in_partition)
781  ereport(ERROR,
783  errmsg("trigger \"%s\" for relation \"%s\" is an internal or a child trigger",
784  stmt->trigname, RelationGetRelationName(rel))));
785 
786  /*
787  * It is not allowed to replace with a constraint trigger; gram.y
788  * should have enforced this already.
789  */
790  Assert(!stmt->isconstraint);
791 
792  /*
793  * It is not allowed to replace an existing constraint trigger,
794  * either. (The reason for these restrictions is partly that it seems
795  * difficult to deal with pending trigger events in such cases, and
796  * partly that the command might imply changing the constraint's
797  * properties as well, which doesn't seem nice.)
798  */
799  if (OidIsValid(existing_constraint_oid))
800  ereport(ERROR,
802  errmsg("trigger \"%s\" for relation \"%s\" is a constraint trigger",
803  stmt->trigname, RelationGetRelationName(rel))));
804  }
805 
806  /*
807  * If it's a user-entered CREATE CONSTRAINT TRIGGER command, make a
808  * corresponding pg_constraint entry.
809  */
810  if (stmt->isconstraint && !OidIsValid(constraintOid))
811  {
812  /* Internal callers should have made their own constraints */
813  Assert(!isInternal);
814  constraintOid = CreateConstraintEntry(stmt->trigname,
816  CONSTRAINT_TRIGGER,
817  stmt->deferrable,
818  stmt->initdeferred,
819  true,
820  InvalidOid, /* no parent */
821  RelationGetRelid(rel),
822  NULL, /* no conkey */
823  0,
824  0,
825  InvalidOid, /* no domain */
826  InvalidOid, /* no index */
827  InvalidOid, /* no foreign key */
828  NULL,
829  NULL,
830  NULL,
831  NULL,
832  0,
833  ' ',
834  ' ',
835  NULL,
836  0,
837  ' ',
838  NULL, /* no exclusion */
839  NULL, /* no check constraint */
840  NULL,
841  true, /* islocal */
842  0, /* inhcount */
843  true, /* noinherit */
844  isInternal); /* is_internal */
845  }
846 
847  /*
848  * If trigger is internally generated, modify the provided trigger name to
849  * ensure uniqueness by appending the trigger OID. (Callers will usually
850  * supply a simple constant trigger name in these cases.)
851  */
852  if (isInternal)
853  {
854  snprintf(internaltrigname, sizeof(internaltrigname),
855  "%s_%u", stmt->trigname, trigoid);
856  trigname = internaltrigname;
857  }
858  else
859  {
860  /* user-defined trigger; use the specified trigger name as-is */
861  trigname = stmt->trigname;
862  }
863 
864  /*
865  * Build the new pg_trigger tuple.
866  *
867  * When we're creating a trigger in a partition, we mark it as internal,
868  * even though we don't do the isInternal magic in this function. This
869  * makes the triggers in partitions identical to the ones in the
870  * partitioned tables, except that they are marked internal.
871  */
872  memset(nulls, false, sizeof(nulls));
873 
874  values[Anum_pg_trigger_oid - 1] = ObjectIdGetDatum(trigoid);
875  values[Anum_pg_trigger_tgrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
876  values[Anum_pg_trigger_tgparentid - 1] = ObjectIdGetDatum(parentTriggerOid);
877  values[Anum_pg_trigger_tgname - 1] = DirectFunctionCall1(namein,
878  CStringGetDatum(trigname));
879  values[Anum_pg_trigger_tgfoid - 1] = ObjectIdGetDatum(funcoid);
880  values[Anum_pg_trigger_tgtype - 1] = Int16GetDatum(tgtype);
881  values[Anum_pg_trigger_tgenabled - 1] = trigger_fires_when;
882  values[Anum_pg_trigger_tgisinternal - 1] = BoolGetDatum(isInternal);
883  values[Anum_pg_trigger_tgconstrrelid - 1] = ObjectIdGetDatum(constrrelid);
884  values[Anum_pg_trigger_tgconstrindid - 1] = ObjectIdGetDatum(indexOid);
885  values[Anum_pg_trigger_tgconstraint - 1] = ObjectIdGetDatum(constraintOid);
886  values[Anum_pg_trigger_tgdeferrable - 1] = BoolGetDatum(stmt->deferrable);
887  values[Anum_pg_trigger_tginitdeferred - 1] = BoolGetDatum(stmt->initdeferred);
888 
889  if (stmt->args)
890  {
891  ListCell *le;
892  char *args;
893  int16 nargs = list_length(stmt->args);
894  int len = 0;
895 
896  foreach(le, stmt->args)
897  {
898  char *ar = strVal(lfirst(le));
899 
900  len += strlen(ar) + 4;
901  for (; *ar; ar++)
902  {
903  if (*ar == '\\')
904  len++;
905  }
906  }
907  args = (char *) palloc(len + 1);
908  args[0] = '\0';
909  foreach(le, stmt->args)
910  {
911  char *s = strVal(lfirst(le));
912  char *d = args + strlen(args);
913 
914  while (*s)
915  {
916  if (*s == '\\')
917  *d++ = '\\';
918  *d++ = *s++;
919  }
920  strcpy(d, "\\000");
921  }
922  values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(nargs);
923  values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
925  }
926  else
927  {
928  values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(0);
929  values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
930  CStringGetDatum(""));
931  }
932 
933  /* build column number array if it's a column-specific trigger */
934  ncolumns = list_length(stmt->columns);
935  if (ncolumns == 0)
936  columns = NULL;
937  else
938  {
939  ListCell *cell;
940  int i = 0;
941 
942  columns = (int16 *) palloc(ncolumns * sizeof(int16));
943  foreach(cell, stmt->columns)
944  {
945  char *name = strVal(lfirst(cell));
946  int16 attnum;
947  int j;
948 
949  /* Lookup column name. System columns are not allowed */
950  attnum = attnameAttNum(rel, name, false);
951  if (attnum == InvalidAttrNumber)
952  ereport(ERROR,
953  (errcode(ERRCODE_UNDEFINED_COLUMN),
954  errmsg("column \"%s\" of relation \"%s\" does not exist",
955  name, RelationGetRelationName(rel))));
956 
957  /* Check for duplicates */
958  for (j = i - 1; j >= 0; j--)
959  {
960  if (columns[j] == attnum)
961  ereport(ERROR,
962  (errcode(ERRCODE_DUPLICATE_COLUMN),
963  errmsg("column \"%s\" specified more than once",
964  name)));
965  }
966 
967  columns[i++] = attnum;
968  }
969  }
970  tgattr = buildint2vector(columns, ncolumns);
971  values[Anum_pg_trigger_tgattr - 1] = PointerGetDatum(tgattr);
972 
973  /* set tgqual if trigger has WHEN clause */
974  if (qual)
975  values[Anum_pg_trigger_tgqual - 1] = CStringGetTextDatum(qual);
976  else
977  nulls[Anum_pg_trigger_tgqual - 1] = true;
978 
979  if (oldtablename)
980  values[Anum_pg_trigger_tgoldtable - 1] = DirectFunctionCall1(namein,
981  CStringGetDatum(oldtablename));
982  else
983  nulls[Anum_pg_trigger_tgoldtable - 1] = true;
984  if (newtablename)
985  values[Anum_pg_trigger_tgnewtable - 1] = DirectFunctionCall1(namein,
986  CStringGetDatum(newtablename));
987  else
988  nulls[Anum_pg_trigger_tgnewtable - 1] = true;
989 
990  /*
991  * Insert or replace tuple in pg_trigger.
992  */
993  if (!trigger_exists)
994  {
995  tuple = heap_form_tuple(tgrel->rd_att, values, nulls);
996  CatalogTupleInsert(tgrel, tuple);
997  }
998  else
999  {
1000  HeapTuple newtup;
1001 
1002  newtup = heap_form_tuple(tgrel->rd_att, values, nulls);
1003  CatalogTupleUpdate(tgrel, &tuple->t_self, newtup);
1004  heap_freetuple(newtup);
1005  }
1006 
1007  heap_freetuple(tuple); /* free either original or new tuple */
1008  table_close(tgrel, RowExclusiveLock);
1009 
1010  pfree(DatumGetPointer(values[Anum_pg_trigger_tgname - 1]));
1011  pfree(DatumGetPointer(values[Anum_pg_trigger_tgargs - 1]));
1012  pfree(DatumGetPointer(values[Anum_pg_trigger_tgattr - 1]));
1013  if (oldtablename)
1014  pfree(DatumGetPointer(values[Anum_pg_trigger_tgoldtable - 1]));
1015  if (newtablename)
1016  pfree(DatumGetPointer(values[Anum_pg_trigger_tgnewtable - 1]));
1017 
1018  /*
1019  * Update relation's pg_class entry; if necessary; and if not, send an SI
1020  * message to make other backends (and this one) rebuild relcache entries.
1021  */
1022  pgrel = table_open(RelationRelationId, RowExclusiveLock);
1023  tuple = SearchSysCacheCopy1(RELOID,
1025  if (!HeapTupleIsValid(tuple))
1026  elog(ERROR, "cache lookup failed for relation %u",
1027  RelationGetRelid(rel));
1028  if (!((Form_pg_class) GETSTRUCT(tuple))->relhastriggers)
1029  {
1030  ((Form_pg_class) GETSTRUCT(tuple))->relhastriggers = true;
1031 
1032  CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
1033 
1035  }
1036  else
1038 
1039  heap_freetuple(tuple);
1040  table_close(pgrel, RowExclusiveLock);
1041 
1042  /*
1043  * If we're replacing a trigger, flush all the old dependencies before
1044  * recording new ones.
1045  */
1046  if (trigger_exists)
1047  deleteDependencyRecordsFor(TriggerRelationId, trigoid, true);
1048 
1049  /*
1050  * Record dependencies for trigger. Always place a normal dependency on
1051  * the function.
1052  */
1053  myself.classId = TriggerRelationId;
1054  myself.objectId = trigoid;
1055  myself.objectSubId = 0;
1056 
1057  referenced.classId = ProcedureRelationId;
1058  referenced.objectId = funcoid;
1059  referenced.objectSubId = 0;
1060  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1061 
1062  if (isInternal && OidIsValid(constraintOid))
1063  {
1064  /*
1065  * Internally-generated trigger for a constraint, so make it an
1066  * internal dependency of the constraint. We can skip depending on
1067  * the relation(s), as there'll be an indirect dependency via the
1068  * constraint.
1069  */
1070  referenced.classId = ConstraintRelationId;
1071  referenced.objectId = constraintOid;
1072  referenced.objectSubId = 0;
1073  recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
1074  }
1075  else
1076  {
1077  /*
1078  * User CREATE TRIGGER, so place dependencies. We make trigger be
1079  * auto-dropped if its relation is dropped or if the FK relation is
1080  * dropped. (Auto drop is compatible with our pre-7.3 behavior.)
1081  */
1082  referenced.classId = RelationRelationId;
1083  referenced.objectId = RelationGetRelid(rel);
1084  referenced.objectSubId = 0;
1085  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
1086 
1087  if (OidIsValid(constrrelid))
1088  {
1089  referenced.classId = RelationRelationId;
1090  referenced.objectId = constrrelid;
1091  referenced.objectSubId = 0;
1092  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
1093  }
1094  /* Not possible to have an index dependency in this case */
1095  Assert(!OidIsValid(indexOid));
1096 
1097  /*
1098  * If it's a user-specified constraint trigger, make the constraint
1099  * internally dependent on the trigger instead of vice versa.
1100  */
1101  if (OidIsValid(constraintOid))
1102  {
1103  referenced.classId = ConstraintRelationId;
1104  referenced.objectId = constraintOid;
1105  referenced.objectSubId = 0;
1106  recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL);
1107  }
1108 
1109  /*
1110  * If it's a partition trigger, create the partition dependencies.
1111  */
1112  if (OidIsValid(parentTriggerOid))
1113  {
1114  ObjectAddressSet(referenced, TriggerRelationId, parentTriggerOid);
1115  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
1116  ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
1117  recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
1118  }
1119  }
1120 
1121  /* If column-specific trigger, add normal dependencies on columns */
1122  if (columns != NULL)
1123  {
1124  int i;
1125 
1126  referenced.classId = RelationRelationId;
1127  referenced.objectId = RelationGetRelid(rel);
1128  for (i = 0; i < ncolumns; i++)
1129  {
1130  referenced.objectSubId = columns[i];
1131  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1132  }
1133  }
1134 
1135  /*
1136  * If it has a WHEN clause, add dependencies on objects mentioned in the
1137  * expression (eg, functions, as well as any columns used).
1138  */
1139  if (whenRtable != NIL)
1140  recordDependencyOnExpr(&myself, whenClause, whenRtable,
1142 
1143  /* Post creation hook for new trigger */
1144  InvokeObjectPostCreateHookArg(TriggerRelationId, trigoid, 0,
1145  isInternal);
1146 
1147  /*
1148  * Lastly, create the trigger on child relations, if needed.
1149  */
1150  if (partition_recurse)
1151  {
1152  PartitionDesc partdesc = RelationGetPartitionDesc(rel, true);
1153  List *idxs = NIL;
1154  List *childTbls = NIL;
1155  ListCell *l;
1156  int i;
1157  MemoryContext oldcxt,
1158  perChildCxt;
1159 
1161  "part trig clone",
1163 
1164  /*
1165  * When a trigger is being created associated with an index, we'll
1166  * need to associate the trigger in each child partition with the
1167  * corresponding index on it.
1168  */
1169  if (OidIsValid(indexOid))
1170  {
1171  ListCell *l;
1172  List *idxs = NIL;
1173 
1175  foreach(l, idxs)
1176  childTbls = lappend_oid(childTbls,
1178  false));
1179  }
1180 
1181  oldcxt = MemoryContextSwitchTo(perChildCxt);
1182 
1183  /* Iterate to create the trigger on each existing partition */
1184  for (i = 0; i < partdesc->nparts; i++)
1185  {
1186  Oid indexOnChild = InvalidOid;
1187  ListCell *l2;
1188  CreateTrigStmt *childStmt;
1189  Relation childTbl;
1190  Node *qual;
1191 
1192  childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
1193 
1194  /* Find which of the child indexes is the one on this partition */
1195  if (OidIsValid(indexOid))
1196  {
1197  forboth(l, idxs, l2, childTbls)
1198  {
1199  if (lfirst_oid(l2) == partdesc->oids[i])
1200  {
1201  indexOnChild = lfirst_oid(l);
1202  break;
1203  }
1204  }
1205  if (!OidIsValid(indexOnChild))
1206  elog(ERROR, "failed to find index matching index \"%s\" in partition \"%s\"",
1207  get_rel_name(indexOid),
1208  get_rel_name(partdesc->oids[i]));
1209  }
1210 
1211  /*
1212  * Initialize our fabricated parse node by copying the original
1213  * one, then resetting fields that we pass separately.
1214  */
1215  childStmt = (CreateTrigStmt *) copyObject(stmt);
1216  childStmt->funcname = NIL;
1217  childStmt->whenClause = NULL;
1218 
1219  /* If there is a WHEN clause, create a modified copy of it */
1220  qual = copyObject(whenClause);
1221  qual = (Node *)
1223  childTbl, rel);
1224  qual = (Node *)
1226  childTbl, rel);
1227 
1228  CreateTriggerFiringOn(childStmt, queryString,
1229  partdesc->oids[i], refRelOid,
1230  InvalidOid, indexOnChild,
1231  funcoid, trigoid, qual,
1232  isInternal, true, trigger_fires_when);
1233 
1234  table_close(childTbl, NoLock);
1235 
1236  MemoryContextReset(perChildCxt);
1237  }
1238 
1239  MemoryContextSwitchTo(oldcxt);
1240  MemoryContextDelete(perChildCxt);
1241  list_free(idxs);
1242  list_free(childTbls);
1243  }
1244 
1245  /* Keep lock on target rel until end of xact */
1246  table_close(rel, NoLock);
1247 
1248  return myself;
1249 }
1250 
1251 /*
1252  * TriggerSetParentTrigger
1253  * Set a partition's trigger as child of its parent trigger,
1254  * or remove the linkage if parentTrigId is InvalidOid.
1255  *
1256  * This updates the constraint's pg_trigger row to show it as inherited, and
1257  * adds PARTITION dependencies to prevent the trigger from being deleted
1258  * on its own. Alternatively, reverse that.
1259  */
1260 void
1262  Oid childTrigId,
1263  Oid parentTrigId,
1264  Oid childTableId)
1265 {
1266  SysScanDesc tgscan;
1267  ScanKeyData skey[1];
1268  Form_pg_trigger trigForm;
1269  HeapTuple tuple,
1270  newtup;
1271  ObjectAddress depender;
1272  ObjectAddress referenced;
1273 
1274  /*
1275  * Find the trigger to delete.
1276  */
1277  ScanKeyInit(&skey[0],
1278  Anum_pg_trigger_oid,
1279  BTEqualStrategyNumber, F_OIDEQ,
1280  ObjectIdGetDatum(childTrigId));
1281 
1282  tgscan = systable_beginscan(trigRel, TriggerOidIndexId, true,
1283  NULL, 1, skey);
1284 
1285  tuple = systable_getnext(tgscan);
1286  if (!HeapTupleIsValid(tuple))
1287  elog(ERROR, "could not find tuple for trigger %u", childTrigId);
1288  newtup = heap_copytuple(tuple);
1289  trigForm = (Form_pg_trigger) GETSTRUCT(newtup);
1290  if (OidIsValid(parentTrigId))
1291  {
1292  /* don't allow setting parent for a constraint that already has one */
1293  if (OidIsValid(trigForm->tgparentid))
1294  elog(ERROR, "trigger %u already has a parent trigger",
1295  childTrigId);
1296 
1297  trigForm->tgparentid = parentTrigId;
1298 
1299  CatalogTupleUpdate(trigRel, &tuple->t_self, newtup);
1300 
1301  ObjectAddressSet(depender, TriggerRelationId, childTrigId);
1302 
1303  ObjectAddressSet(referenced, TriggerRelationId, parentTrigId);
1304  recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_PRI);
1305 
1306  ObjectAddressSet(referenced, RelationRelationId, childTableId);
1307  recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_SEC);
1308  }
1309  else
1310  {
1311  trigForm->tgparentid = InvalidOid;
1312 
1313  CatalogTupleUpdate(trigRel, &tuple->t_self, newtup);
1314 
1315  deleteDependencyRecordsForClass(TriggerRelationId, childTrigId,
1316  TriggerRelationId,
1318  deleteDependencyRecordsForClass(TriggerRelationId, childTrigId,
1319  RelationRelationId,
1321  }
1322 
1323  heap_freetuple(newtup);
1324  systable_endscan(tgscan);
1325 }
1326 
1327 
1328 /*
1329  * Guts of trigger deletion.
1330  */
1331 void
1333 {
1334  Relation tgrel;
1335  SysScanDesc tgscan;
1336  ScanKeyData skey[1];
1337  HeapTuple tup;
1338  Oid relid;
1339  Relation rel;
1340 
1341  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1342 
1343  /*
1344  * Find the trigger to delete.
1345  */
1346  ScanKeyInit(&skey[0],
1347  Anum_pg_trigger_oid,
1348  BTEqualStrategyNumber, F_OIDEQ,
1349  ObjectIdGetDatum(trigOid));
1350 
1351  tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
1352  NULL, 1, skey);
1353 
1354  tup = systable_getnext(tgscan);
1355  if (!HeapTupleIsValid(tup))
1356  elog(ERROR, "could not find tuple for trigger %u", trigOid);
1357 
1358  /*
1359  * Open and exclusive-lock the relation the trigger belongs to.
1360  */
1361  relid = ((Form_pg_trigger) GETSTRUCT(tup))->tgrelid;
1362 
1363  rel = table_open(relid, AccessExclusiveLock);
1364 
1365  if (rel->rd_rel->relkind != RELKIND_RELATION &&
1366  rel->rd_rel->relkind != RELKIND_VIEW &&
1367  rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
1368  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1369  ereport(ERROR,
1370  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1371  errmsg("relation \"%s\" cannot have triggers",
1373  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
1374 
1376  ereport(ERROR,
1377  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1378  errmsg("permission denied: \"%s\" is a system catalog",
1379  RelationGetRelationName(rel))));
1380 
1381  /*
1382  * Delete the pg_trigger tuple.
1383  */
1384  CatalogTupleDelete(tgrel, &tup->t_self);
1385 
1386  systable_endscan(tgscan);
1387  table_close(tgrel, RowExclusiveLock);
1388 
1389  /*
1390  * We do not bother to try to determine whether any other triggers remain,
1391  * which would be needed in order to decide whether it's safe to clear the
1392  * relation's relhastriggers. (In any case, there might be a concurrent
1393  * process adding new triggers.) Instead, just force a relcache inval to
1394  * make other backends (and this one too!) rebuild their relcache entries.
1395  * There's no great harm in leaving relhastriggers true even if there are
1396  * no triggers left.
1397  */
1399 
1400  /* Keep lock on trigger's rel until end of xact */
1401  table_close(rel, NoLock);
1402 }
1403 
1404 /*
1405  * get_trigger_oid - Look up a trigger by name to find its OID.
1406  *
1407  * If missing_ok is false, throw an error if trigger not found. If
1408  * true, just return InvalidOid.
1409  */
1410 Oid
1411 get_trigger_oid(Oid relid, const char *trigname, bool missing_ok)
1412 {
1413  Relation tgrel;
1414  ScanKeyData skey[2];
1415  SysScanDesc tgscan;
1416  HeapTuple tup;
1417  Oid oid;
1418 
1419  /*
1420  * Find the trigger, verify permissions, set up object address
1421  */
1422  tgrel = table_open(TriggerRelationId, AccessShareLock);
1423 
1424  ScanKeyInit(&skey[0],
1425  Anum_pg_trigger_tgrelid,
1426  BTEqualStrategyNumber, F_OIDEQ,
1427  ObjectIdGetDatum(relid));
1428  ScanKeyInit(&skey[1],
1429  Anum_pg_trigger_tgname,
1430  BTEqualStrategyNumber, F_NAMEEQ,
1431  CStringGetDatum(trigname));
1432 
1433  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1434  NULL, 2, skey);
1435 
1436  tup = systable_getnext(tgscan);
1437 
1438  if (!HeapTupleIsValid(tup))
1439  {
1440  if (!missing_ok)
1441  ereport(ERROR,
1442  (errcode(ERRCODE_UNDEFINED_OBJECT),
1443  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1444  trigname, get_rel_name(relid))));
1445  oid = InvalidOid;
1446  }
1447  else
1448  {
1449  oid = ((Form_pg_trigger) GETSTRUCT(tup))->oid;
1450  }
1451 
1452  systable_endscan(tgscan);
1453  table_close(tgrel, AccessShareLock);
1454  return oid;
1455 }
1456 
1457 /*
1458  * Perform permissions and integrity checks before acquiring a relation lock.
1459  */
1460 static void
1462  void *arg)
1463 {
1464  HeapTuple tuple;
1465  Form_pg_class form;
1466 
1467  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
1468  if (!HeapTupleIsValid(tuple))
1469  return; /* concurrently dropped */
1470  form = (Form_pg_class) GETSTRUCT(tuple);
1471 
1472  /* only tables and views can have triggers */
1473  if (form->relkind != RELKIND_RELATION && form->relkind != RELKIND_VIEW &&
1474  form->relkind != RELKIND_FOREIGN_TABLE &&
1475  form->relkind != RELKIND_PARTITIONED_TABLE)
1476  ereport(ERROR,
1477  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1478  errmsg("relation \"%s\" cannot have triggers",
1479  rv->relname),
1480  errdetail_relkind_not_supported(form->relkind)));
1481 
1482  /* you must own the table to rename one of its triggers */
1483  if (!pg_class_ownercheck(relid, GetUserId()))
1485  if (!allowSystemTableMods && IsSystemClass(relid, form))
1486  ereport(ERROR,
1487  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1488  errmsg("permission denied: \"%s\" is a system catalog",
1489  rv->relname)));
1490 
1491  ReleaseSysCache(tuple);
1492 }
1493 
1494 /*
1495  * renametrig - changes the name of a trigger on a relation
1496  *
1497  * trigger name is changed in trigger catalog.
1498  * No record of the previous name is kept.
1499  *
1500  * get proper relrelation from relation catalog (if not arg)
1501  * scan trigger catalog
1502  * for name conflict (within rel)
1503  * for original trigger (if not arg)
1504  * modify tgname in trigger tuple
1505  * update row in catalog
1506  */
1509 {
1510  Oid tgoid;
1511  Relation targetrel;
1512  Relation tgrel;
1513  HeapTuple tuple;
1514  SysScanDesc tgscan;
1515  ScanKeyData key[2];
1516  Oid relid;
1517  ObjectAddress address;
1518 
1519  /*
1520  * Look up name, check permissions, and acquire lock (which we will NOT
1521  * release until end of transaction).
1522  */
1524  0,
1526  NULL);
1527 
1528  /* Have lock already, so just need to build relcache entry. */
1529  targetrel = relation_open(relid, NoLock);
1530 
1531  /*
1532  * On partitioned tables, this operation recurses to partitions. Lock all
1533  * tables upfront.
1534  */
1535  if (targetrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1536  (void) find_all_inheritors(relid, AccessExclusiveLock, NULL);
1537 
1538  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1539 
1540  /*
1541  * Search for the trigger to modify.
1542  */
1543  ScanKeyInit(&key[0],
1544  Anum_pg_trigger_tgrelid,
1545  BTEqualStrategyNumber, F_OIDEQ,
1546  ObjectIdGetDatum(relid));
1547  ScanKeyInit(&key[1],
1548  Anum_pg_trigger_tgname,
1549  BTEqualStrategyNumber, F_NAMEEQ,
1550  PointerGetDatum(stmt->subname));
1551  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1552  NULL, 2, key);
1553  if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1554  {
1555  Form_pg_trigger trigform;
1556 
1557  trigform = (Form_pg_trigger) GETSTRUCT(tuple);
1558  tgoid = trigform->oid;
1559 
1560  /*
1561  * If the trigger descends from a trigger on a parent partitioned
1562  * table, reject the rename. We don't allow a trigger in a partition
1563  * to differ in name from that of its parent: that would lead to an
1564  * inconsistency that pg_dump would not reproduce.
1565  */
1566  if (OidIsValid(trigform->tgparentid))
1567  ereport(ERROR,
1568  errmsg("cannot rename trigger \"%s\" on table \"%s\"",
1569  stmt->subname, RelationGetRelationName(targetrel)),
1570  errhint("Rename trigger on partitioned table \"%s\" instead.",
1571  get_rel_name(get_partition_parent(relid, false))));
1572 
1573 
1574  /* Rename the trigger on this relation ... */
1575  renametrig_internal(tgrel, targetrel, tuple, stmt->newname,
1576  stmt->subname);
1577 
1578  /* ... and if it is partitioned, recurse to its partitions */
1579  if (targetrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1580  {
1581  PartitionDesc partdesc = RelationGetPartitionDesc(targetrel, true);
1582 
1583  for (int i = 0; i < partdesc->nparts; i++)
1584  {
1585  Oid partitionId = partdesc->oids[i];
1586 
1587  renametrig_partition(tgrel, partitionId, trigform->oid,
1588  stmt->newname, stmt->subname);
1589  }
1590  }
1591  }
1592  else
1593  {
1594  ereport(ERROR,
1595  (errcode(ERRCODE_UNDEFINED_OBJECT),
1596  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1597  stmt->subname, RelationGetRelationName(targetrel))));
1598  }
1599 
1600  ObjectAddressSet(address, TriggerRelationId, tgoid);
1601 
1602  systable_endscan(tgscan);
1603 
1604  table_close(tgrel, RowExclusiveLock);
1605 
1606  /*
1607  * Close rel, but keep exclusive lock!
1608  */
1609  relation_close(targetrel, NoLock);
1610 
1611  return address;
1612 }
1613 
1614 /*
1615  * Subroutine for renametrig -- perform the actual work of renaming one
1616  * trigger on one table.
1617  *
1618  * If the trigger has a name different from the expected one, raise a
1619  * NOTICE about it.
1620  */
1621 static void
1623  const char *newname, const char *expected_name)
1624 {
1625  HeapTuple tuple;
1626  Form_pg_trigger tgform;
1627  ScanKeyData key[2];
1628  SysScanDesc tgscan;
1629 
1630  /* If the trigger already has the new name, nothing to do. */
1631  tgform = (Form_pg_trigger) GETSTRUCT(trigtup);
1632  if (strcmp(NameStr(tgform->tgname), newname) == 0)
1633  return;
1634 
1635  /*
1636  * Before actually trying the rename, search for triggers with the same
1637  * name. The update would fail with an ugly message in that case, and it
1638  * is better to throw a nicer error.
1639  */
1640  ScanKeyInit(&key[0],
1641  Anum_pg_trigger_tgrelid,
1642  BTEqualStrategyNumber, F_OIDEQ,
1643  ObjectIdGetDatum(RelationGetRelid(targetrel)));
1644  ScanKeyInit(&key[1],
1645  Anum_pg_trigger_tgname,
1646  BTEqualStrategyNumber, F_NAMEEQ,
1647  PointerGetDatum(newname));
1648  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1649  NULL, 2, key);
1650  if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1651  ereport(ERROR,
1653  errmsg("trigger \"%s\" for relation \"%s\" already exists",
1654  newname, RelationGetRelationName(targetrel))));
1655  systable_endscan(tgscan);
1656 
1657  /*
1658  * The target name is free; update the existing pg_trigger tuple with it.
1659  */
1660  tuple = heap_copytuple(trigtup); /* need a modifiable copy */
1661  tgform = (Form_pg_trigger) GETSTRUCT(tuple);
1662 
1663  /*
1664  * If the trigger has a name different from what we expected, let the user
1665  * know. (We can proceed anyway, since we must have reached here following
1666  * a tgparentid link.)
1667  */
1668  if (strcmp(NameStr(tgform->tgname), expected_name) != 0)
1669  ereport(NOTICE,
1670  errmsg("renamed trigger \"%s\" on relation \"%s\"",
1671  NameStr(tgform->tgname),
1672  RelationGetRelationName(targetrel)));
1673 
1674  namestrcpy(&tgform->tgname, newname);
1675 
1676  CatalogTupleUpdate(tgrel, &tuple->t_self, tuple);
1677 
1678  InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
1679 
1680  /*
1681  * Invalidate relation's relcache entry so that other backends (and this
1682  * one too!) are sent SI message to make them rebuild relcache entries.
1683  * (Ideally this should happen automatically...)
1684  */
1685  CacheInvalidateRelcache(targetrel);
1686 }
1687 
1688 /*
1689  * Subroutine for renametrig -- Helper for recursing to partitions when
1690  * renaming triggers on a partitioned table.
1691  */
1692 static void
1693 renametrig_partition(Relation tgrel, Oid partitionId, Oid parentTriggerOid,
1694  const char *newname, const char *expected_name)
1695 {
1696  SysScanDesc tgscan;
1697  ScanKeyData key;
1698  HeapTuple tuple;
1699 
1700  /*
1701  * Given a relation and the OID of a trigger on parent relation, find the
1702  * corresponding trigger in the child and rename that trigger to the given
1703  * name.
1704  */
1705  ScanKeyInit(&key,
1706  Anum_pg_trigger_tgrelid,
1707  BTEqualStrategyNumber, F_OIDEQ,
1708  ObjectIdGetDatum(partitionId));
1709  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1710  NULL, 1, &key);
1711  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1712  {
1713  Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tuple);
1714  Relation partitionRel;
1715 
1716  if (tgform->tgparentid != parentTriggerOid)
1717  continue; /* not our trigger */
1718 
1719  partitionRel = table_open(partitionId, NoLock);
1720 
1721  /* Rename the trigger on this partition */
1722  renametrig_internal(tgrel, partitionRel, tuple, newname, expected_name);
1723 
1724  /* And if this relation is partitioned, recurse to its partitions */
1725  if (partitionRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1726  {
1727  PartitionDesc partdesc = RelationGetPartitionDesc(partitionRel,
1728  true);
1729 
1730  for (int i = 0; i < partdesc->nparts; i++)
1731  {
1732  Oid partitionId = partdesc->oids[i];
1733 
1734  renametrig_partition(tgrel, partitionId, tgform->oid, newname,
1735  NameStr(tgform->tgname));
1736  }
1737  }
1738  table_close(partitionRel, NoLock);
1739 
1740  /* There should be at most one matching tuple */
1741  break;
1742  }
1743  systable_endscan(tgscan);
1744 }
1745 
1746 /*
1747  * EnableDisableTrigger()
1748  *
1749  * Called by ALTER TABLE ENABLE/DISABLE [ REPLICA | ALWAYS ] TRIGGER
1750  * to change 'tgenabled' field for the specified trigger(s)
1751  *
1752  * rel: relation to process (caller must hold suitable lock on it)
1753  * tgname: trigger to process, or NULL to scan all triggers
1754  * fires_when: new value for tgenabled field. In addition to generic
1755  * enablement/disablement, this also defines when the trigger
1756  * should be fired in session replication roles.
1757  * skip_system: if true, skip "system" triggers (constraint triggers)
1758  *
1759  * Caller should have checked permissions for the table; here we also
1760  * enforce that superuser privilege is required to alter the state of
1761  * system triggers
1762  */
1763 void
1764 EnableDisableTrigger(Relation rel, const char *tgname,
1765  char fires_when, bool skip_system, LOCKMODE lockmode)
1766 {
1767  Relation tgrel;
1768  int nkeys;
1769  ScanKeyData keys[2];
1770  SysScanDesc tgscan;
1771  HeapTuple tuple;
1772  bool found;
1773  bool changed;
1774 
1775  /* Scan the relevant entries in pg_triggers */
1776  tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1777 
1778  ScanKeyInit(&keys[0],
1779  Anum_pg_trigger_tgrelid,
1780  BTEqualStrategyNumber, F_OIDEQ,
1782  if (tgname)
1783  {
1784  ScanKeyInit(&keys[1],
1785  Anum_pg_trigger_tgname,
1786  BTEqualStrategyNumber, F_NAMEEQ,
1787  CStringGetDatum(tgname));
1788  nkeys = 2;
1789  }
1790  else
1791  nkeys = 1;
1792 
1793  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1794  NULL, nkeys, keys);
1795 
1796  found = changed = false;
1797 
1798  while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1799  {
1800  Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1801 
1802  if (oldtrig->tgisinternal)
1803  {
1804  /* system trigger ... ok to process? */
1805  if (skip_system)
1806  continue;
1807  if (!superuser())
1808  ereport(ERROR,
1809  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1810  errmsg("permission denied: \"%s\" is a system trigger",
1811  NameStr(oldtrig->tgname))));
1812  }
1813 
1814  found = true;
1815 
1816  if (oldtrig->tgenabled != fires_when)
1817  {
1818  /* need to change this one ... make a copy to scribble on */
1819  HeapTuple newtup = heap_copytuple(tuple);
1820  Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1821 
1822  newtrig->tgenabled = fires_when;
1823 
1824  CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1825 
1826  heap_freetuple(newtup);
1827 
1828  changed = true;
1829  }
1830 
1831  InvokeObjectPostAlterHook(TriggerRelationId,
1832  oldtrig->oid, 0);
1833  }
1834 
1835  systable_endscan(tgscan);
1836 
1837  table_close(tgrel, RowExclusiveLock);
1838 
1839  if (tgname && !found)
1840  ereport(ERROR,
1841  (errcode(ERRCODE_UNDEFINED_OBJECT),
1842  errmsg("trigger \"%s\" for table \"%s\" does not exist",
1843  tgname, RelationGetRelationName(rel))));
1844 
1845  /*
1846  * If we changed anything, broadcast a SI inval message to force each
1847  * backend (including our own!) to rebuild relation's relcache entry.
1848  * Otherwise they will fail to apply the change promptly.
1849  */
1850  if (changed)
1852 }
1853 
1854 
1855 /*
1856  * Build trigger data to attach to the given relcache entry.
1857  *
1858  * Note that trigger data attached to a relcache entry must be stored in
1859  * CacheMemoryContext to ensure it survives as long as the relcache entry.
1860  * But we should be running in a less long-lived working context. To avoid
1861  * leaking cache memory if this routine fails partway through, we build a
1862  * temporary TriggerDesc in working memory and then copy the completed
1863  * structure into cache memory.
1864  */
1865 void
1867 {
1868  TriggerDesc *trigdesc;
1869  int numtrigs;
1870  int maxtrigs;
1871  Trigger *triggers;
1872  Relation tgrel;
1873  ScanKeyData skey;
1874  SysScanDesc tgscan;
1875  HeapTuple htup;
1876  MemoryContext oldContext;
1877  int i;
1878 
1879  /*
1880  * Allocate a working array to hold the triggers (the array is extended if
1881  * necessary)
1882  */
1883  maxtrigs = 16;
1884  triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
1885  numtrigs = 0;
1886 
1887  /*
1888  * Note: since we scan the triggers using TriggerRelidNameIndexId, we will
1889  * be reading the triggers in name order, except possibly during
1890  * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
1891  * ensures that triggers will be fired in name order.
1892  */
1893  ScanKeyInit(&skey,
1894  Anum_pg_trigger_tgrelid,
1895  BTEqualStrategyNumber, F_OIDEQ,
1896  ObjectIdGetDatum(RelationGetRelid(relation)));
1897 
1898  tgrel = table_open(TriggerRelationId, AccessShareLock);
1899  tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1900  NULL, 1, &skey);
1901 
1902  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
1903  {
1904  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
1905  Trigger *build;
1906  Datum datum;
1907  bool isnull;
1908 
1909  if (numtrigs >= maxtrigs)
1910  {
1911  maxtrigs *= 2;
1912  triggers = (Trigger *) repalloc(triggers, maxtrigs * sizeof(Trigger));
1913  }
1914  build = &(triggers[numtrigs]);
1915 
1916  build->tgoid = pg_trigger->oid;
1918  NameGetDatum(&pg_trigger->tgname)));
1919  build->tgfoid = pg_trigger->tgfoid;
1920  build->tgtype = pg_trigger->tgtype;
1921  build->tgenabled = pg_trigger->tgenabled;
1922  build->tgisinternal = pg_trigger->tgisinternal;
1923  build->tgisclone = OidIsValid(pg_trigger->tgparentid);
1924  build->tgconstrrelid = pg_trigger->tgconstrrelid;
1925  build->tgconstrindid = pg_trigger->tgconstrindid;
1926  build->tgconstraint = pg_trigger->tgconstraint;
1927  build->tgdeferrable = pg_trigger->tgdeferrable;
1928  build->tginitdeferred = pg_trigger->tginitdeferred;
1929  build->tgnargs = pg_trigger->tgnargs;
1930  /* tgattr is first var-width field, so OK to access directly */
1931  build->tgnattr = pg_trigger->tgattr.dim1;
1932  if (build->tgnattr > 0)
1933  {
1934  build->tgattr = (int16 *) palloc(build->tgnattr * sizeof(int16));
1935  memcpy(build->tgattr, &(pg_trigger->tgattr.values),
1936  build->tgnattr * sizeof(int16));
1937  }
1938  else
1939  build->tgattr = NULL;
1940  if (build->tgnargs > 0)
1941  {
1942  bytea *val;
1943  char *p;
1944 
1946  Anum_pg_trigger_tgargs,
1947  tgrel->rd_att, &isnull));
1948  if (isnull)
1949  elog(ERROR, "tgargs is null in trigger for relation \"%s\"",
1950  RelationGetRelationName(relation));
1951  p = (char *) VARDATA_ANY(val);
1952  build->tgargs = (char **) palloc(build->tgnargs * sizeof(char *));
1953  for (i = 0; i < build->tgnargs; i++)
1954  {
1955  build->tgargs[i] = pstrdup(p);
1956  p += strlen(p) + 1;
1957  }
1958  }
1959  else
1960  build->tgargs = NULL;
1961 
1962  datum = fastgetattr(htup, Anum_pg_trigger_tgoldtable,
1963  tgrel->rd_att, &isnull);
1964  if (!isnull)
1965  build->tgoldtable =
1967  else
1968  build->tgoldtable = NULL;
1969 
1970  datum = fastgetattr(htup, Anum_pg_trigger_tgnewtable,
1971  tgrel->rd_att, &isnull);
1972  if (!isnull)
1973  build->tgnewtable =
1975  else
1976  build->tgnewtable = NULL;
1977 
1978  datum = fastgetattr(htup, Anum_pg_trigger_tgqual,
1979  tgrel->rd_att, &isnull);
1980  if (!isnull)
1981  build->tgqual = TextDatumGetCString(datum);
1982  else
1983  build->tgqual = NULL;
1984 
1985  numtrigs++;
1986  }
1987 
1988  systable_endscan(tgscan);
1989  table_close(tgrel, AccessShareLock);
1990 
1991  /* There might not be any triggers */
1992  if (numtrigs == 0)
1993  {
1994  pfree(triggers);
1995  return;
1996  }
1997 
1998  /* Build trigdesc */
1999  trigdesc = (TriggerDesc *) palloc0(sizeof(TriggerDesc));
2000  trigdesc->triggers = triggers;
2001  trigdesc->numtriggers = numtrigs;
2002  for (i = 0; i < numtrigs; i++)
2003  SetTriggerFlags(trigdesc, &(triggers[i]));
2004 
2005  /* Copy completed trigdesc into cache storage */
2007  relation->trigdesc = CopyTriggerDesc(trigdesc);
2008  MemoryContextSwitchTo(oldContext);
2009 
2010  /* Release working memory */
2011  FreeTriggerDesc(trigdesc);
2012 }
2013 
2014 /*
2015  * Update the TriggerDesc's hint flags to include the specified trigger
2016  */
2017 static void
2019 {
2020  int16 tgtype = trigger->tgtype;
2021 
2022  trigdesc->trig_insert_before_row |=
2023  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2024  TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT);
2025  trigdesc->trig_insert_after_row |=
2026  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2027  TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT);
2028  trigdesc->trig_insert_instead_row |=
2029  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2030  TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_INSERT);
2031  trigdesc->trig_insert_before_statement |=
2032  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2033  TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT);
2034  trigdesc->trig_insert_after_statement |=
2035  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2036  TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT);
2037  trigdesc->trig_update_before_row |=
2038  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2039  TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_UPDATE);
2040  trigdesc->trig_update_after_row |=
2041  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2042  TRIGGER_TYPE_AFTER, TRIGGER_TYPE_UPDATE);
2043  trigdesc->trig_update_instead_row |=
2044  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2045  TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_UPDATE);
2046  trigdesc->trig_update_before_statement |=
2047  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2048  TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_UPDATE);
2049  trigdesc->trig_update_after_statement |=
2050  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2051  TRIGGER_TYPE_AFTER, TRIGGER_TYPE_UPDATE);
2052  trigdesc->trig_delete_before_row |=
2053  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2054  TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE);
2055  trigdesc->trig_delete_after_row |=
2056  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2057  TRIGGER_TYPE_AFTER, TRIGGER_TYPE_DELETE);
2058  trigdesc->trig_delete_instead_row |=
2059  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2060  TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_DELETE);
2061  trigdesc->trig_delete_before_statement |=
2062  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2063  TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE);
2064  trigdesc->trig_delete_after_statement |=
2065  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2066  TRIGGER_TYPE_AFTER, TRIGGER_TYPE_DELETE);
2067  /* there are no row-level truncate triggers */
2068  trigdesc->trig_truncate_before_statement |=
2069  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2070  TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_TRUNCATE);
2071  trigdesc->trig_truncate_after_statement |=
2072  TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2073  TRIGGER_TYPE_AFTER, TRIGGER_TYPE_TRUNCATE);
2074 
2075  trigdesc->trig_insert_new_table |=
2076  (TRIGGER_FOR_INSERT(tgtype) &&
2077  TRIGGER_USES_TRANSITION_TABLE(trigger->tgnewtable));
2078  trigdesc->trig_update_old_table |=
2079  (TRIGGER_FOR_UPDATE(tgtype) &&
2080  TRIGGER_USES_TRANSITION_TABLE(trigger->tgoldtable));
2081  trigdesc->trig_update_new_table |=
2082  (TRIGGER_FOR_UPDATE(tgtype) &&
2083  TRIGGER_USES_TRANSITION_TABLE(trigger->tgnewtable));
2084  trigdesc->trig_delete_old_table |=
2085  (TRIGGER_FOR_DELETE(tgtype) &&
2086  TRIGGER_USES_TRANSITION_TABLE(trigger->tgoldtable));
2087 }
2088 
2089 /*
2090  * Copy a TriggerDesc data structure.
2091  *
2092  * The copy is allocated in the current memory context.
2093  */
2094 TriggerDesc *
2096 {
2097  TriggerDesc *newdesc;
2098  Trigger *trigger;
2099  int i;
2100 
2101  if (trigdesc == NULL || trigdesc->numtriggers <= 0)
2102  return NULL;
2103 
2104  newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
2105  memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
2106 
2107  trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
2108  memcpy(trigger, trigdesc->triggers,
2109  trigdesc->numtriggers * sizeof(Trigger));
2110  newdesc->triggers = trigger;
2111 
2112  for (i = 0; i < trigdesc->numtriggers; i++)
2113  {
2114  trigger->tgname = pstrdup(trigger->tgname);
2115  if (trigger->tgnattr > 0)
2116  {
2117  int16 *newattr;
2118 
2119  newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
2120  memcpy(newattr, trigger->tgattr,
2121  trigger->tgnattr * sizeof(int16));
2122  trigger->tgattr = newattr;
2123  }
2124  if (trigger->tgnargs > 0)
2125  {
2126  char **newargs;
2127  int16 j;
2128 
2129  newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
2130  for (j = 0; j < trigger->tgnargs; j++)
2131  newargs[j] = pstrdup(trigger->tgargs[j]);
2132  trigger->tgargs = newargs;
2133  }
2134  if (trigger->tgqual)
2135  trigger->tgqual = pstrdup(trigger->tgqual);
2136  if (trigger->tgoldtable)
2137  trigger->tgoldtable = pstrdup(trigger->tgoldtable);
2138  if (trigger->tgnewtable)
2139  trigger->tgnewtable = pstrdup(trigger->tgnewtable);
2140  trigger++;
2141  }
2142 
2143  return newdesc;
2144 }
2145 
2146 /*
2147  * Free a TriggerDesc data structure.
2148  */
2149 void
2151 {
2152  Trigger *trigger;
2153  int i;
2154 
2155  if (trigdesc == NULL)
2156  return;
2157 
2158  trigger = trigdesc->triggers;
2159  for (i = 0; i < trigdesc->numtriggers; i++)
2160  {
2161  pfree(trigger->tgname);
2162  if (trigger->tgnattr > 0)
2163  pfree(trigger->tgattr);
2164  if (trigger->tgnargs > 0)
2165  {
2166  while (--(trigger->tgnargs) >= 0)
2167  pfree(trigger->tgargs[trigger->tgnargs]);
2168  pfree(trigger->tgargs);
2169  }
2170  if (trigger->tgqual)
2171  pfree(trigger->tgqual);
2172  if (trigger->tgoldtable)
2173  pfree(trigger->tgoldtable);
2174  if (trigger->tgnewtable)
2175  pfree(trigger->tgnewtable);
2176  trigger++;
2177  }
2178  pfree(trigdesc->triggers);
2179  pfree(trigdesc);
2180 }
2181 
2182 /*
2183  * Compare two TriggerDesc structures for logical equality.
2184  */
2185 #ifdef NOT_USED
2186 bool
2187 equalTriggerDescs(TriggerDesc *trigdesc1, TriggerDesc *trigdesc2)
2188 {
2189  int i,
2190  j;
2191 
2192  /*
2193  * We need not examine the hint flags, just the trigger array itself; if
2194  * we have the same triggers with the same types, the flags should match.
2195  *
2196  * As of 7.3 we assume trigger set ordering is significant in the
2197  * comparison; so we just compare corresponding slots of the two sets.
2198  *
2199  * Note: comparing the stringToNode forms of the WHEN clauses means that
2200  * parse column locations will affect the result. This is okay as long as
2201  * this function is only used for detecting exact equality, as for example
2202  * in checking for staleness of a cache entry.
2203  */
2204  if (trigdesc1 != NULL)
2205  {
2206  if (trigdesc2 == NULL)
2207  return false;
2208  if (trigdesc1->numtriggers != trigdesc2->numtriggers)
2209  return false;
2210  for (i = 0; i < trigdesc1->numtriggers; i++)
2211  {
2212  Trigger *trig1 = trigdesc1->triggers + i;
2213  Trigger *trig2 = trigdesc2->triggers + i;
2214 
2215  if (trig1->tgoid != trig2->tgoid)
2216  return false;
2217  if (strcmp(trig1->tgname, trig2->tgname) != 0)
2218  return false;
2219  if (trig1->tgfoid != trig2->tgfoid)
2220  return false;
2221  if (trig1->tgtype != trig2->tgtype)
2222  return false;
2223  if (trig1->tgenabled != trig2->tgenabled)
2224  return false;
2225  if (trig1->tgisinternal != trig2->tgisinternal)
2226  return false;
2227  if (trig1->tgisclone != trig2->tgisclone)
2228  return false;
2229  if (trig1->tgconstrrelid != trig2->tgconstrrelid)
2230  return false;
2231  if (trig1->tgconstrindid != trig2->tgconstrindid)
2232  return false;
2233  if (trig1->tgconstraint != trig2->tgconstraint)
2234  return false;
2235  if (trig1->tgdeferrable != trig2->tgdeferrable)
2236  return false;
2237  if (trig1->tginitdeferred != trig2->tginitdeferred)
2238  return false;
2239  if (trig1->tgnargs != trig2->tgnargs)
2240  return false;
2241  if (trig1->tgnattr != trig2->tgnattr)
2242  return false;
2243  if (trig1->tgnattr > 0 &&
2244  memcmp(trig1->tgattr, trig2->tgattr,
2245  trig1->tgnattr * sizeof(int16)) != 0)
2246  return false;
2247  for (j = 0; j < trig1->tgnargs; j++)
2248  if (strcmp(trig1->tgargs[j], trig2->tgargs[j]) != 0)
2249  return false;
2250  if (trig1->tgqual == NULL && trig2->tgqual == NULL)
2251  /* ok */ ;
2252  else if (trig1->tgqual == NULL || trig2->tgqual == NULL)
2253  return false;
2254  else if (strcmp(trig1->tgqual, trig2->tgqual) != 0)
2255  return false;
2256  if (trig1->tgoldtable == NULL && trig2->tgoldtable == NULL)
2257  /* ok */ ;
2258  else if (trig1->tgoldtable == NULL || trig2->tgoldtable == NULL)
2259  return false;
2260  else if (strcmp(trig1->tgoldtable, trig2->tgoldtable) != 0)
2261  return false;
2262  if (trig1->tgnewtable == NULL && trig2->tgnewtable == NULL)
2263  /* ok */ ;
2264  else if (trig1->tgnewtable == NULL || trig2->tgnewtable == NULL)
2265  return false;
2266  else if (strcmp(trig1->tgnewtable, trig2->tgnewtable) != 0)
2267  return false;
2268  }
2269  }
2270  else if (trigdesc2 != NULL)
2271  return false;
2272  return true;
2273 }
2274 #endif /* NOT_USED */
2275 
2276 /*
2277  * Check if there is a row-level trigger with transition tables that prevents
2278  * a table from becoming an inheritance child or partition. Return the name
2279  * of the first such incompatible trigger, or NULL if there is none.
2280  */
2281 const char *
2283 {
2284  if (trigdesc != NULL)
2285  {
2286  int i;
2287 
2288  for (i = 0; i < trigdesc->numtriggers; ++i)
2289  {
2290  Trigger *trigger = &trigdesc->triggers[i];
2291 
2292  if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
2293  return trigger->tgname;
2294  }
2295  }
2296 
2297  return NULL;
2298 }
2299 
2300 /*
2301  * Call a trigger function.
2302  *
2303  * trigdata: trigger descriptor.
2304  * tgindx: trigger's index in finfo and instr arrays.
2305  * finfo: array of cached trigger function call information.
2306  * instr: optional array of EXPLAIN ANALYZE instrumentation state.
2307  * per_tuple_context: memory context to execute the function in.
2308  *
2309  * Returns the tuple (or NULL) as returned by the function.
2310  */
2311 static HeapTuple
2313  int tgindx,
2314  FmgrInfo *finfo,
2315  Instrumentation *instr,
2316  MemoryContext per_tuple_context)
2317 {
2318  LOCAL_FCINFO(fcinfo, 0);
2319  PgStat_FunctionCallUsage fcusage;
2320  Datum result;
2321  MemoryContext oldContext;
2322 
2323  /*
2324  * Protect against code paths that may fail to initialize transition table
2325  * info.
2326  */
2327  Assert(((TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||
2328  TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event) ||
2329  TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) &&
2330  TRIGGER_FIRED_AFTER(trigdata->tg_event) &&
2331  !(trigdata->tg_event & AFTER_TRIGGER_DEFERRABLE) &&
2332  !(trigdata->tg_event & AFTER_TRIGGER_INITDEFERRED)) ||
2333  (trigdata->tg_oldtable == NULL && trigdata->tg_newtable == NULL));
2334 
2335  finfo += tgindx;
2336 
2337  /*
2338  * We cache fmgr lookup info, to avoid making the lookup again on each
2339  * call.
2340  */
2341  if (finfo->fn_oid == InvalidOid)
2342  fmgr_info(trigdata->tg_trigger->tgfoid, finfo);
2343 
2344  Assert(finfo->fn_oid == trigdata->tg_trigger->tgfoid);
2345 
2346  /*
2347  * If doing EXPLAIN ANALYZE, start charging time to this trigger.
2348  */
2349  if (instr)
2350  InstrStartNode(instr + tgindx);
2351 
2352  /*
2353  * Do the function evaluation in the per-tuple memory context, so that
2354  * leaked memory will be reclaimed once per tuple. Note in particular that
2355  * any new tuple created by the trigger function will live till the end of
2356  * the tuple cycle.
2357  */
2358  oldContext = MemoryContextSwitchTo(per_tuple_context);
2359 
2360  /*
2361  * Call the function, passing no arguments but setting a context.
2362  */
2363  InitFunctionCallInfoData(*fcinfo, finfo, 0,
2364  InvalidOid, (Node *) trigdata, NULL);
2365 
2366  pgstat_init_function_usage(fcinfo, &fcusage);
2367 
2368  MyTriggerDepth++;
2369  PG_TRY();
2370  {
2371  result = FunctionCallInvoke(fcinfo);
2372  }
2373  PG_FINALLY();
2374  {
2375  MyTriggerDepth--;
2376  }
2377  PG_END_TRY();
2378 
2379  pgstat_end_function_usage(&fcusage, true);
2380 
2381  MemoryContextSwitchTo(oldContext);
2382 
2383  /*
2384  * Trigger protocol allows function to return a null pointer, but NOT to
2385  * set the isnull result flag.
2386  */
2387  if (fcinfo->isnull)
2388  ereport(ERROR,
2389  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2390  errmsg("trigger function %u returned null value",
2391  fcinfo->flinfo->fn_oid)));
2392 
2393  /*
2394  * If doing EXPLAIN ANALYZE, stop charging time to this trigger, and count
2395  * one "tuple returned" (really the number of firings).
2396  */
2397  if (instr)
2398  InstrStopNode(instr + tgindx, 1);
2399 
2400  return (HeapTuple) DatumGetPointer(result);
2401 }
2402 
2403 void
2405 {
2406  TriggerDesc *trigdesc;
2407  int i;
2408  TriggerData LocTriggerData = {0};
2409 
2410  trigdesc = relinfo->ri_TrigDesc;
2411 
2412  if (trigdesc == NULL)
2413  return;
2414  if (!trigdesc->trig_insert_before_statement)
2415  return;
2416 
2417  /* no-op if we already fired BS triggers in this context */
2419  CMD_INSERT))
2420  return;
2421 
2422  LocTriggerData.type = T_TriggerData;
2423  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2425  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2426  for (i = 0; i < trigdesc->numtriggers; i++)
2427  {
2428  Trigger *trigger = &trigdesc->triggers[i];
2429  HeapTuple newtuple;
2430 
2431  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2432  TRIGGER_TYPE_STATEMENT,
2433  TRIGGER_TYPE_BEFORE,
2434  TRIGGER_TYPE_INSERT))
2435  continue;
2436  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2437  NULL, NULL, NULL))
2438  continue;
2439 
2440  LocTriggerData.tg_trigger = trigger;
2441  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2442  i,
2443  relinfo->ri_TrigFunctions,
2444  relinfo->ri_TrigInstrument,
2445  GetPerTupleMemoryContext(estate));
2446 
2447  if (newtuple)
2448  ereport(ERROR,
2449  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2450  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2451  }
2452 }
2453 
2454 void
2456  TransitionCaptureState *transition_capture)
2457 {
2458  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2459 
2460  if (trigdesc && trigdesc->trig_insert_after_statement)
2462  false, NULL, NULL, NIL, NULL, transition_capture);
2463 }
2464 
2465 bool
2467  TupleTableSlot *slot)
2468 {
2469  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2470  HeapTuple newtuple = NULL;
2471  bool should_free;
2472  TriggerData LocTriggerData = {0};
2473  int i;
2474 
2475  LocTriggerData.type = T_TriggerData;
2476  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2479  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2480  for (i = 0; i < trigdesc->numtriggers; i++)
2481  {
2482  Trigger *trigger = &trigdesc->triggers[i];
2483  HeapTuple oldtuple;
2484 
2485  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2486  TRIGGER_TYPE_ROW,
2487  TRIGGER_TYPE_BEFORE,
2488  TRIGGER_TYPE_INSERT))
2489  continue;
2490  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2491  NULL, NULL, slot))
2492  continue;
2493 
2494  if (!newtuple)
2495  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2496 
2497  LocTriggerData.tg_trigslot = slot;
2498  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2499  LocTriggerData.tg_trigger = trigger;
2500  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2501  i,
2502  relinfo->ri_TrigFunctions,
2503  relinfo->ri_TrigInstrument,
2504  GetPerTupleMemoryContext(estate));
2505  if (newtuple == NULL)
2506  {
2507  if (should_free)
2508  heap_freetuple(oldtuple);
2509  return false; /* "do nothing" */
2510  }
2511  else if (newtuple != oldtuple)
2512  {
2513  ExecForceStoreHeapTuple(newtuple, slot, false);
2514 
2515  /*
2516  * After a tuple in a partition goes through a trigger, the user
2517  * could have changed the partition key enough that the tuple no
2518  * longer fits the partition. Verify that.
2519  */
2520  if (trigger->tgisclone &&
2521  !ExecPartitionCheck(relinfo, slot, estate, false))
2522  ereport(ERROR,
2523  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2524  errmsg("moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported"),
2525  errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2526  trigger->tgname,
2529 
2530  if (should_free)
2531  heap_freetuple(oldtuple);
2532 
2533  /* signal tuple should be re-fetched if used */
2534  newtuple = NULL;
2535  }
2536  }
2537 
2538  return true;
2539 }
2540 
2541 void
2543  TupleTableSlot *slot, List *recheckIndexes,
2544  TransitionCaptureState *transition_capture)
2545 {
2546  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2547 
2548  if ((trigdesc && trigdesc->trig_insert_after_row) ||
2549  (transition_capture && transition_capture->tcs_insert_new_table))
2551  true, NULL, slot,
2552  recheckIndexes, NULL,
2553  transition_capture);
2554 }
2555 
2556 bool
2558  TupleTableSlot *slot)
2559 {
2560  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2561  HeapTuple newtuple = NULL;
2562  bool should_free;
2563  TriggerData LocTriggerData = {0};
2564  int i;
2565 
2566  LocTriggerData.type = T_TriggerData;
2567  LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2570  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2571  for (i = 0; i < trigdesc->numtriggers; i++)
2572  {
2573  Trigger *trigger = &trigdesc->triggers[i];
2574  HeapTuple oldtuple;
2575 
2576  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2577  TRIGGER_TYPE_ROW,
2578  TRIGGER_TYPE_INSTEAD,
2579  TRIGGER_TYPE_INSERT))
2580  continue;
2581  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2582  NULL, NULL, slot))
2583  continue;
2584 
2585  if (!newtuple)
2586  newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2587 
2588  LocTriggerData.tg_trigslot = slot;
2589  LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2590  LocTriggerData.tg_trigger = trigger;
2591  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2592  i,
2593  relinfo->ri_TrigFunctions,
2594  relinfo->ri_TrigInstrument,
2595  GetPerTupleMemoryContext(estate));
2596  if (newtuple == NULL)
2597  {
2598  if (should_free)
2599  heap_freetuple(oldtuple);
2600  return false; /* "do nothing" */
2601  }
2602  else if (newtuple != oldtuple)
2603  {
2604  ExecForceStoreHeapTuple(newtuple, slot, false);
2605 
2606  if (should_free)
2607  heap_freetuple(oldtuple);
2608 
2609  /* signal tuple should be re-fetched if used */
2610  newtuple = NULL;
2611  }
2612  }
2613 
2614  return true;
2615 }
2616 
2617 void
2619 {
2620  TriggerDesc *trigdesc;
2621  int i;
2622  TriggerData LocTriggerData = {0};
2623 
2624  trigdesc = relinfo->ri_TrigDesc;
2625 
2626  if (trigdesc == NULL)
2627  return;
2628  if (!trigdesc->trig_delete_before_statement)
2629  return;
2630 
2631  /* no-op if we already fired BS triggers in this context */
2633  CMD_DELETE))
2634  return;
2635 
2636  LocTriggerData.type = T_TriggerData;
2637  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2639  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2640  for (i = 0; i < trigdesc->numtriggers; i++)
2641  {
2642  Trigger *trigger = &trigdesc->triggers[i];
2643  HeapTuple newtuple;
2644 
2645  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2646  TRIGGER_TYPE_STATEMENT,
2647  TRIGGER_TYPE_BEFORE,
2648  TRIGGER_TYPE_DELETE))
2649  continue;
2650  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2651  NULL, NULL, NULL))
2652  continue;
2653 
2654  LocTriggerData.tg_trigger = trigger;
2655  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2656  i,
2657  relinfo->ri_TrigFunctions,
2658  relinfo->ri_TrigInstrument,
2659  GetPerTupleMemoryContext(estate));
2660 
2661  if (newtuple)
2662  ereport(ERROR,
2663  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2664  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2665  }
2666 }
2667 
2668 void
2670  TransitionCaptureState *transition_capture)
2671 {
2672  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2673 
2674  if (trigdesc && trigdesc->trig_delete_after_statement)
2676  false, NULL, NULL, NIL, NULL, transition_capture);
2677 }
2678 
2679 /*
2680  * Execute BEFORE ROW DELETE triggers.
2681  *
2682  * True indicates caller can proceed with the delete. False indicates caller
2683  * need to suppress the delete and additionally if requested, we need to pass
2684  * back the concurrently updated tuple if any.
2685  */
2686 bool
2688  ResultRelInfo *relinfo,
2689  ItemPointer tupleid,
2690  HeapTuple fdw_trigtuple,
2691  TupleTableSlot **epqslot)
2692 {
2693  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2694  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2695  bool result = true;
2696  TriggerData LocTriggerData = {0};
2697  HeapTuple trigtuple;
2698  bool should_free = false;
2699  int i;
2700 
2701  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2702  if (fdw_trigtuple == NULL)
2703  {
2704  TupleTableSlot *epqslot_candidate = NULL;
2705 
2706  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2707  LockTupleExclusive, slot, &epqslot_candidate))
2708  return false;
2709 
2710  /*
2711  * If the tuple was concurrently updated and the caller of this
2712  * function requested for the updated tuple, skip the trigger
2713  * execution.
2714  */
2715  if (epqslot_candidate != NULL && epqslot != NULL)
2716  {
2717  *epqslot = epqslot_candidate;
2718  return false;
2719  }
2720 
2721  trigtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2722 
2723  }
2724  else
2725  {
2726  trigtuple = fdw_trigtuple;
2727  ExecForceStoreHeapTuple(trigtuple, slot, false);
2728  }
2729 
2730  LocTriggerData.type = T_TriggerData;
2731  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2734  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2735  for (i = 0; i < trigdesc->numtriggers; i++)
2736  {
2737  HeapTuple newtuple;
2738  Trigger *trigger = &trigdesc->triggers[i];
2739 
2740  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2741  TRIGGER_TYPE_ROW,
2742  TRIGGER_TYPE_BEFORE,
2743  TRIGGER_TYPE_DELETE))
2744  continue;
2745  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2746  NULL, slot, NULL))
2747  continue;
2748 
2749  LocTriggerData.tg_trigslot = slot;
2750  LocTriggerData.tg_trigtuple = trigtuple;
2751  LocTriggerData.tg_trigger = trigger;
2752  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2753  i,
2754  relinfo->ri_TrigFunctions,
2755  relinfo->ri_TrigInstrument,
2756  GetPerTupleMemoryContext(estate));
2757  if (newtuple == NULL)
2758  {
2759  result = false; /* tell caller to suppress delete */
2760  break;
2761  }
2762  if (newtuple != trigtuple)
2763  heap_freetuple(newtuple);
2764  }
2765  if (should_free)
2766  heap_freetuple(trigtuple);
2767 
2768  return result;
2769 }
2770 
2771 void
2773  ItemPointer tupleid,
2774  HeapTuple fdw_trigtuple,
2775  TransitionCaptureState *transition_capture)
2776 {
2777  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2778 
2779  if ((trigdesc && trigdesc->trig_delete_after_row) ||
2780  (transition_capture && transition_capture->tcs_delete_old_table))
2781  {
2782  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2783 
2784  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2785  if (fdw_trigtuple == NULL)
2786  GetTupleForTrigger(estate,
2787  NULL,
2788  relinfo,
2789  tupleid,
2791  slot,
2792  NULL);
2793  else
2794  ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2795 
2797  true, slot, NULL, NIL, NULL,
2798  transition_capture);
2799  }
2800 }
2801 
2802 bool
2804  HeapTuple trigtuple)
2805 {
2806  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2807  TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2808  TriggerData LocTriggerData = {0};
2809  int i;
2810 
2811  LocTriggerData.type = T_TriggerData;
2812  LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2815  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2816 
2817  ExecForceStoreHeapTuple(trigtuple, slot, false);
2818 
2819  for (i = 0; i < trigdesc->numtriggers; i++)
2820  {
2821  HeapTuple rettuple;
2822  Trigger *trigger = &trigdesc->triggers[i];
2823 
2824  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2825  TRIGGER_TYPE_ROW,
2826  TRIGGER_TYPE_INSTEAD,
2827  TRIGGER_TYPE_DELETE))
2828  continue;
2829  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2830  NULL, slot, NULL))
2831  continue;
2832 
2833  LocTriggerData.tg_trigslot = slot;
2834  LocTriggerData.tg_trigtuple = trigtuple;
2835  LocTriggerData.tg_trigger = trigger;
2836  rettuple = ExecCallTriggerFunc(&LocTriggerData,
2837  i,
2838  relinfo->ri_TrigFunctions,
2839  relinfo->ri_TrigInstrument,
2840  GetPerTupleMemoryContext(estate));
2841  if (rettuple == NULL)
2842  return false; /* Delete was suppressed */
2843  if (rettuple != trigtuple)
2844  heap_freetuple(rettuple);
2845  }
2846  return true;
2847 }
2848 
2849 void
2851 {
2852  TriggerDesc *trigdesc;
2853  int i;
2854  TriggerData LocTriggerData = {0};
2855  Bitmapset *updatedCols;
2856 
2857  trigdesc = relinfo->ri_TrigDesc;
2858 
2859  if (trigdesc == NULL)
2860  return;
2861  if (!trigdesc->trig_update_before_statement)
2862  return;
2863 
2864  /* no-op if we already fired BS triggers in this context */
2866  CMD_UPDATE))
2867  return;
2868 
2869  /* statement-level triggers operate on the parent table */
2870  Assert(relinfo->ri_RootResultRelInfo == NULL);
2871 
2872  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2873 
2874  LocTriggerData.type = T_TriggerData;
2875  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2877  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2878  LocTriggerData.tg_updatedcols = updatedCols;
2879  for (i = 0; i < trigdesc->numtriggers; i++)
2880  {
2881  Trigger *trigger = &trigdesc->triggers[i];
2882  HeapTuple newtuple;
2883 
2884  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2885  TRIGGER_TYPE_STATEMENT,
2886  TRIGGER_TYPE_BEFORE,
2887  TRIGGER_TYPE_UPDATE))
2888  continue;
2889  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2890  updatedCols, NULL, NULL))
2891  continue;
2892 
2893  LocTriggerData.tg_trigger = trigger;
2894  newtuple = ExecCallTriggerFunc(&LocTriggerData,
2895  i,
2896  relinfo->ri_TrigFunctions,
2897  relinfo->ri_TrigInstrument,
2898  GetPerTupleMemoryContext(estate));
2899 
2900  if (newtuple)
2901  ereport(ERROR,
2902  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2903  errmsg("BEFORE STATEMENT trigger cannot return a value")));
2904  }
2905 }
2906 
2907 void
2909  TransitionCaptureState *transition_capture)
2910 {
2911  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2912 
2913  /* statement-level triggers operate on the parent table */
2914  Assert(relinfo->ri_RootResultRelInfo == NULL);
2915 
2916  if (trigdesc && trigdesc->trig_update_after_statement)
2918  false, NULL, NULL, NIL,
2919  ExecGetAllUpdatedCols(relinfo, estate),
2920  transition_capture);
2921 }
2922 
2923 bool
2925  ResultRelInfo *relinfo,
2926  ItemPointer tupleid,
2927  HeapTuple fdw_trigtuple,
2928  TupleTableSlot *newslot)
2929 {
2930  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2931  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2932  HeapTuple newtuple = NULL;
2933  HeapTuple trigtuple;
2934  bool should_free_trig = false;
2935  bool should_free_new = false;
2936  TriggerData LocTriggerData = {0};
2937  int i;
2938  Bitmapset *updatedCols;
2939  LockTupleMode lockmode;
2940 
2941  /* Determine lock mode to use */
2942  lockmode = ExecUpdateLockMode(estate, relinfo);
2943 
2944  Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2945  if (fdw_trigtuple == NULL)
2946  {
2947  TupleTableSlot *epqslot_candidate = NULL;
2948 
2949  /* get a copy of the on-disk tuple we are planning to update */
2950  if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2951  lockmode, oldslot, &epqslot_candidate))
2952  return false; /* cancel the update action */
2953 
2954  /*
2955  * In READ COMMITTED isolation level it's possible that target tuple
2956  * was changed due to concurrent update. In that case we have a raw
2957  * subplan output tuple in epqslot_candidate, and need to form a new
2958  * insertable tuple using ExecGetUpdateNewTuple to replace the one we
2959  * received in newslot. Neither we nor our callers have any further
2960  * interest in the passed-in tuple, so it's okay to overwrite newslot
2961  * with the newer data.
2962  *
2963  * (Typically, newslot was also generated by ExecGetUpdateNewTuple, so
2964  * that epqslot_clean will be that same slot and the copy step below
2965  * is not needed.)
2966  */
2967  if (epqslot_candidate != NULL)
2968  {
2969  TupleTableSlot *epqslot_clean;
2970 
2971  epqslot_clean = ExecGetUpdateNewTuple(relinfo, epqslot_candidate,
2972  oldslot);
2973 
2974  if (newslot != epqslot_clean)
2975  ExecCopySlot(newslot, epqslot_clean);
2976  }
2977 
2978  trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
2979  }
2980  else
2981  {
2982  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
2983  trigtuple = fdw_trigtuple;
2984  }
2985 
2986  LocTriggerData.type = T_TriggerData;
2987  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2990  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2991  updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2992  LocTriggerData.tg_updatedcols = updatedCols;
2993  for (i = 0; i < trigdesc->numtriggers; i++)
2994  {
2995  Trigger *trigger = &trigdesc->triggers[i];
2996  HeapTuple oldtuple;
2997 
2998  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2999  TRIGGER_TYPE_ROW,
3000  TRIGGER_TYPE_BEFORE,
3001  TRIGGER_TYPE_UPDATE))
3002  continue;
3003  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3004  updatedCols, oldslot, newslot))
3005  continue;
3006 
3007  if (!newtuple)
3008  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
3009 
3010  LocTriggerData.tg_trigslot = oldslot;
3011  LocTriggerData.tg_trigtuple = trigtuple;
3012  LocTriggerData.tg_newtuple = oldtuple = newtuple;
3013  LocTriggerData.tg_newslot = newslot;
3014  LocTriggerData.tg_trigger = trigger;
3015  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3016  i,
3017  relinfo->ri_TrigFunctions,
3018  relinfo->ri_TrigInstrument,
3019  GetPerTupleMemoryContext(estate));
3020 
3021  if (newtuple == NULL)
3022  {
3023  if (should_free_trig)
3024  heap_freetuple(trigtuple);
3025  if (should_free_new)
3026  heap_freetuple(oldtuple);
3027  return false; /* "do nothing" */
3028  }
3029  else if (newtuple != oldtuple)
3030  {
3031  ExecForceStoreHeapTuple(newtuple, newslot, false);
3032 
3033  /*
3034  * If the tuple returned by the trigger / being stored, is the old
3035  * row version, and the heap tuple passed to the trigger was
3036  * allocated locally, materialize the slot. Otherwise we might
3037  * free it while still referenced by the slot.
3038  */
3039  if (should_free_trig && newtuple == trigtuple)
3040  ExecMaterializeSlot(newslot);
3041 
3042  if (should_free_new)
3043  heap_freetuple(oldtuple);
3044 
3045  /* signal tuple should be re-fetched if used */
3046  newtuple = NULL;
3047  }
3048  }
3049  if (should_free_trig)
3050  heap_freetuple(trigtuple);
3051 
3052  return true;
3053 }
3054 
3055 void
3057  ItemPointer tupleid,
3058  HeapTuple fdw_trigtuple,
3059  TupleTableSlot *newslot,
3060  List *recheckIndexes,
3061  TransitionCaptureState *transition_capture)
3062 {
3063  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3064 
3065  if ((trigdesc && trigdesc->trig_update_after_row) ||
3066  (transition_capture &&
3067  (transition_capture->tcs_update_old_table ||
3068  transition_capture->tcs_update_new_table)))
3069  {
3070  /*
3071  * Note: if the UPDATE is converted into a DELETE+INSERT as part of
3072  * update-partition-key operation, then this function is also called
3073  * separately for DELETE and INSERT to capture transition table rows.
3074  * In such case, either old tuple or new tuple can be NULL.
3075  */
3076  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
3077 
3078  if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
3079  GetTupleForTrigger(estate,
3080  NULL,
3081  relinfo,
3082  tupleid,
3084  oldslot,
3085  NULL);
3086  else if (fdw_trigtuple != NULL)
3087  ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
3088  else
3089  ExecClearTuple(oldslot);
3090 
3092  true, oldslot, newslot, recheckIndexes,
3093  ExecGetAllUpdatedCols(relinfo, estate),
3094  transition_capture);
3095  }
3096 }
3097 
3098 bool
3100  HeapTuple trigtuple, TupleTableSlot *newslot)
3101 {
3102  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3103  TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
3104  HeapTuple newtuple = NULL;
3105  bool should_free;
3106  TriggerData LocTriggerData = {0};
3107  int i;
3108 
3109  LocTriggerData.type = T_TriggerData;
3110  LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
3113  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3114 
3115  ExecForceStoreHeapTuple(trigtuple, oldslot, false);
3116 
3117  for (i = 0; i < trigdesc->numtriggers; i++)
3118  {
3119  Trigger *trigger = &trigdesc->triggers[i];
3120  HeapTuple oldtuple;
3121 
3122  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3123  TRIGGER_TYPE_ROW,
3124  TRIGGER_TYPE_INSTEAD,
3125  TRIGGER_TYPE_UPDATE))
3126  continue;
3127  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3128  NULL, oldslot, newslot))
3129  continue;
3130 
3131  if (!newtuple)
3132  newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
3133 
3134  LocTriggerData.tg_trigslot = oldslot;
3135  LocTriggerData.tg_trigtuple = trigtuple;
3136  LocTriggerData.tg_newslot = newslot;
3137  LocTriggerData.tg_newtuple = oldtuple = newtuple;
3138 
3139  LocTriggerData.tg_trigger = trigger;
3140  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3141  i,
3142  relinfo->ri_TrigFunctions,
3143  relinfo->ri_TrigInstrument,
3144  GetPerTupleMemoryContext(estate));
3145  if (newtuple == NULL)
3146  {
3147  return false; /* "do nothing" */
3148  }
3149  else if (newtuple != oldtuple)
3150  {
3151  ExecForceStoreHeapTuple(newtuple, newslot, false);
3152 
3153  if (should_free)
3154  heap_freetuple(oldtuple);
3155 
3156  /* signal tuple should be re-fetched if used */
3157  newtuple = NULL;
3158  }
3159  }
3160 
3161  return true;
3162 }
3163 
3164 void
3166 {
3167  TriggerDesc *trigdesc;
3168  int i;
3169  TriggerData LocTriggerData = {0};
3170 
3171  trigdesc = relinfo->ri_TrigDesc;
3172 
3173  if (trigdesc == NULL)
3174  return;
3175  if (!trigdesc->trig_truncate_before_statement)
3176  return;
3177 
3178  LocTriggerData.type = T_TriggerData;
3179  LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
3181  LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3182 
3183  for (i = 0; i < trigdesc->numtriggers; i++)
3184  {
3185  Trigger *trigger = &trigdesc->triggers[i];
3186  HeapTuple newtuple;
3187 
3188  if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3189  TRIGGER_TYPE_STATEMENT,
3190  TRIGGER_TYPE_BEFORE,
3191  TRIGGER_TYPE_TRUNCATE))
3192  continue;
3193  if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3194  NULL, NULL, NULL))
3195  continue;
3196 
3197  LocTriggerData.tg_trigger = trigger;
3198  newtuple = ExecCallTriggerFunc(&LocTriggerData,
3199  i,
3200  relinfo->ri_TrigFunctions,
3201  relinfo->ri_TrigInstrument,
3202  GetPerTupleMemoryContext(estate));
3203 
3204  if (newtuple)
3205  ereport(ERROR,
3206  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
3207  errmsg("BEFORE STATEMENT trigger cannot return a value")));
3208  }
3209 }
3210 
3211 void
3213 {
3214  TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3215 
3216  if (trigdesc && trigdesc->trig_truncate_after_statement)
3218  false, NULL, NULL, NIL, NULL, NULL);
3219 }
3220 
3221 
3222 /*
3223  * Fetch tuple into "oldslot", dealing with locking and EPQ if necessary
3224  */
3225 static bool
3227  EPQState *epqstate,
3228  ResultRelInfo *relinfo,
3229  ItemPointer tid,
3230  LockTupleMode lockmode,
3231  TupleTableSlot *oldslot,
3232  TupleTableSlot **epqslot)
3233 {
3234  Relation relation = relinfo->ri_RelationDesc;
3235 
3236  if (epqslot != NULL)
3237  {
3238  TM_Result test;
3239  TM_FailureData tmfd;
3240  int lockflags = 0;
3241 
3242  *epqslot = NULL;
3243 
3244  /* caller must pass an epqstate if EvalPlanQual is possible */
3245  Assert(epqstate != NULL);
3246 
3247  /*
3248  * lock tuple for update
3249  */
3251  lockflags |= TUPLE_LOCK_FLAG_FIND_LAST_VERSION;
3252  test = table_tuple_lock(relation, tid, estate->es_snapshot, oldslot,
3253  estate->es_output_cid,
3254  lockmode, LockWaitBlock,
3255  lockflags,
3256  &tmfd);
3257 
3258  switch (test)
3259  {
3260  case TM_SelfModified:
3261 
3262  /*
3263  * The target tuple was already updated or deleted by the
3264  * current command, or by a later command in the current
3265  * transaction. We ignore the tuple in the former case, and
3266  * throw error in the latter case, for the same reasons
3267  * enumerated in ExecUpdate and ExecDelete in
3268  * nodeModifyTable.c.
3269  */
3270  if (tmfd.cmax != estate->es_output_cid)
3271  ereport(ERROR,
3272  (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
3273  errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
3274  errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
3275 
3276  /* treat it as deleted; do not process */
3277  return false;
3278 
3279  case TM_Ok:
3280  if (tmfd.traversed)
3281  {
3282  *epqslot = EvalPlanQual(epqstate,
3283  relation,
3284  relinfo->ri_RangeTableIndex,
3285  oldslot);
3286 
3287  /*
3288  * If PlanQual failed for updated tuple - we must not
3289  * process this tuple!
3290  */
3291  if (TupIsNull(*epqslot))
3292  {
3293  *epqslot = NULL;
3294  return false;
3295  }
3296  }
3297  break;
3298 
3299  case TM_Updated:
3301  ereport(ERROR,
3302  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3303  errmsg("could not serialize access due to concurrent update")));
3304  elog(ERROR, "unexpected table_tuple_lock status: %u", test);
3305  break;
3306 
3307  case TM_Deleted:
3309  ereport(ERROR,
3310  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3311  errmsg("could not serialize access due to concurrent delete")));
3312  /* tuple was deleted */
3313  return false;
3314 
3315  case TM_Invisible:
3316  elog(ERROR, "attempted to lock invisible tuple");
3317  break;
3318 
3319  default:
3320  elog(ERROR, "unrecognized table_tuple_lock status: %u", test);
3321  return false; /* keep compiler quiet */
3322  }
3323  }
3324  else
3325  {
3326  /*
3327  * We expect the tuple to be present, thus very simple error handling
3328  * suffices.
3329  */
3330  if (!table_tuple_fetch_row_version(relation, tid, SnapshotAny,
3331  oldslot))
3332  elog(ERROR, "failed to fetch tuple for trigger");
3333  }
3334 
3335  return true;
3336 }
3337 
3338 /*
3339  * Is trigger enabled to fire?
3340  */
3341 static bool
3343  Trigger *trigger, TriggerEvent event,
3344  Bitmapset *modifiedCols,
3345  TupleTableSlot *oldslot, TupleTableSlot *newslot)
3346 {
3347  /* Check replication-role-dependent enable state */
3349  {
3350  if (trigger->tgenabled == TRIGGER_FIRES_ON_ORIGIN ||
3351  trigger->tgenabled == TRIGGER_DISABLED)
3352  return false;
3353  }
3354  else /* ORIGIN or LOCAL role */
3355  {
3356  if (trigger->tgenabled == TRIGGER_FIRES_ON_REPLICA ||
3357  trigger->tgenabled == TRIGGER_DISABLED)
3358  return false;
3359  }
3360 
3361  /*
3362  * Check for column-specific trigger (only possible for UPDATE, and in
3363  * fact we *must* ignore tgattr for other event types)
3364  */
3365  if (trigger->tgnattr > 0 && TRIGGER_FIRED_BY_UPDATE(event))
3366  {
3367  int i;
3368  bool modified;
3369 
3370  modified = false;
3371  for (i = 0; i < trigger->tgnattr; i++)
3372  {
3374  modifiedCols))
3375  {
3376  modified = true;
3377  break;
3378  }
3379  }
3380  if (!modified)
3381  return false;
3382  }
3383 
3384  /* Check for WHEN clause */
3385  if (trigger->tgqual)
3386  {
3387  ExprState **predicate;
3388  ExprContext *econtext;
3389  MemoryContext oldContext;
3390  int i;
3391 
3392  Assert(estate != NULL);
3393 
3394  /*
3395  * trigger is an element of relinfo->ri_TrigDesc->triggers[]; find the
3396  * matching element of relinfo->ri_TrigWhenExprs[]
3397  */
3398  i = trigger - relinfo->ri_TrigDesc->triggers;
3399  predicate = &relinfo->ri_TrigWhenExprs[i];
3400 
3401  /*
3402  * If first time through for this WHEN expression, build expression
3403  * nodetrees for it. Keep them in the per-query memory context so
3404  * they'll survive throughout the query.
3405  */
3406  if (*predicate == NULL)
3407  {
3408  Node *tgqual;
3409 
3410  oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
3411  tgqual = stringToNode(trigger->tgqual);
3412  /* Change references to OLD and NEW to INNER_VAR and OUTER_VAR */
3415  /* ExecPrepareQual wants implicit-AND form */
3416  tgqual = (Node *) make_ands_implicit((Expr *) tgqual);
3417  *predicate = ExecPrepareQual((List *) tgqual, estate);
3418  MemoryContextSwitchTo(oldContext);
3419  }
3420 
3421  /*
3422  * We will use the EState's per-tuple context for evaluating WHEN
3423  * expressions (creating it if it's not already there).
3424  */
3425  econtext = GetPerTupleExprContext(estate);
3426 
3427  /*
3428  * Finally evaluate the expression, making the old and/or new tuples
3429  * available as INNER_VAR/OUTER_VAR respectively.
3430  */
3431  econtext->ecxt_innertuple = oldslot;
3432  econtext->ecxt_outertuple = newslot;
3433  if (!ExecQual(*predicate, econtext))
3434  return false;
3435  }
3436 
3437  return true;
3438 }
3439 
3440 
3441 /* ----------
3442  * After-trigger stuff
3443  *
3444  * The AfterTriggersData struct holds data about pending AFTER trigger events
3445  * during the current transaction tree. (BEFORE triggers are fired
3446  * immediately so we don't need any persistent state about them.) The struct
3447  * and most of its subsidiary data are kept in TopTransactionContext; however
3448  * some data that can be discarded sooner appears in the CurTransactionContext
3449  * of the relevant subtransaction. Also, the individual event records are
3450  * kept in a separate sub-context of TopTransactionContext. This is done
3451  * mainly so that it's easy to tell from a memory context dump how much space
3452  * is being eaten by trigger events.
3453  *
3454  * Because the list of pending events can grow large, we go to some
3455  * considerable effort to minimize per-event memory consumption. The event
3456  * records are grouped into chunks and common data for similar events in the
3457  * same chunk is only stored once.
3458  *
3459  * XXX We need to be able to save the per-event data in a file if it grows too
3460  * large.
3461  * ----------
3462  */
3463 
3464 /* Per-trigger SET CONSTRAINT status */
3466 {
3470 
3472 
3473 /*
3474  * SET CONSTRAINT intra-transaction status.
3475  *
3476  * We make this a single palloc'd object so it can be copied and freed easily.
3477  *
3478  * all_isset and all_isdeferred are used to keep track
3479  * of SET CONSTRAINTS ALL {DEFERRED, IMMEDIATE}.
3480  *
3481  * trigstates[] stores per-trigger tgisdeferred settings.
3482  */
3484 {
3487  int numstates; /* number of trigstates[] entries in use */
3488  int numalloc; /* allocated size of trigstates[] */
3491 
3493 
3494 
3495 /*
3496  * Per-trigger-event data
3497  *
3498  * The actual per-event data, AfterTriggerEventData, includes DONE/IN_PROGRESS
3499  * status bits and up to two tuple CTIDs. Each event record also has an
3500  * associated AfterTriggerSharedData that is shared across all instances of
3501  * similar events within a "chunk".
3502  *
3503  * For row-level triggers, we arrange not to waste storage on unneeded ctid
3504  * fields. Updates of regular tables use two; inserts and deletes of regular
3505  * tables use one; foreign tables always use zero and save the tuple(s) to a
3506  * tuplestore. AFTER_TRIGGER_FDW_FETCH directs AfterTriggerExecute() to
3507  * retrieve a fresh tuple or pair of tuples from that tuplestore, while
3508  * AFTER_TRIGGER_FDW_REUSE directs it to use the most-recently-retrieved
3509  * tuple(s). This permits storing tuples once regardless of the number of
3510  * row-level triggers on a foreign table.
3511  *
3512  * Note that we need triggers on foreign tables to be fired in exactly the
3513  * order they were queued, so that the tuples come out of the tuplestore in
3514  * the right order. To ensure that, we forbid deferrable (constraint)
3515  * triggers on foreign tables. This also ensures that such triggers do not
3516  * get deferred into outer trigger query levels, meaning that it's okay to
3517  * destroy the tuplestore at the end of the query level.
3518  *
3519  * Statement-level triggers always bear AFTER_TRIGGER_1CTID, though they
3520  * require no ctid field. We lack the flag bit space to neatly represent that
3521  * distinct case, and it seems unlikely to be worth much trouble.
3522  *
3523  * Note: ats_firing_id is initially zero and is set to something else when
3524  * AFTER_TRIGGER_IN_PROGRESS is set. It indicates which trigger firing
3525  * cycle the trigger will be fired in (or was fired in, if DONE is set).
3526  * Although this is mutable state, we can keep it in AfterTriggerSharedData
3527  * because all instances of the same type of event in a given event list will
3528  * be fired at the same time, if they were queued between the same firing
3529  * cycles. So we need only ensure that ats_firing_id is zero when attaching
3530  * a new event to an existing AfterTriggerSharedData record.
3531  */
3533 
3534 #define AFTER_TRIGGER_OFFSET 0x0FFFFFFF /* must be low-order bits */
3535 #define AFTER_TRIGGER_DONE 0x10000000
3536 #define AFTER_TRIGGER_IN_PROGRESS 0x20000000
3537 /* bits describing the size and tuple sources of this event */
3538 #define AFTER_TRIGGER_FDW_REUSE 0x00000000
3539 #define AFTER_TRIGGER_FDW_FETCH 0x80000000
3540 #define AFTER_TRIGGER_1CTID 0x40000000
3541 #define AFTER_TRIGGER_2CTID 0xC0000000
3542 #define AFTER_TRIGGER_TUP_BITS 0xC0000000
3543 
3545 
3547 {
3548  TriggerEvent ats_event; /* event type indicator, see trigger.h */
3549  Oid ats_tgoid; /* the trigger's ID */
3550  Oid ats_relid; /* the relation it's on */
3551  CommandId ats_firing_id; /* ID for firing cycle */
3552  struct AfterTriggersTableData *ats_table; /* transition table access */
3553  Bitmapset *ats_modifiedcols; /* modified columns */
3555 
3557 
3559 {
3560  TriggerFlags ate_flags; /* status bits and offset to shared data */
3561  ItemPointerData ate_ctid1; /* inserted, deleted, or old updated tuple */
3562  ItemPointerData ate_ctid2; /* new updated tuple */
3564 
3565 /* AfterTriggerEventData, minus ate_ctid2 */
3567 {
3568  TriggerFlags ate_flags; /* status bits and offset to shared data */
3569  ItemPointerData ate_ctid1; /* inserted, deleted, or old updated tuple */
3571 
3572 /* AfterTriggerEventData, minus ate_ctid1 and ate_ctid2 */
3574 {
3575  TriggerFlags ate_flags; /* status bits and offset to shared data */
3577 
3578 #define SizeofTriggerEvent(evt) \
3579  (((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_2CTID ? \
3580  sizeof(AfterTriggerEventData) : \
3581  ((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_1CTID ? \
3582  sizeof(AfterTriggerEventDataOneCtid) : \
3583  sizeof(AfterTriggerEventDataZeroCtids))
3584 
3585 #define GetTriggerSharedData(evt) \
3586  ((AfterTriggerShared) ((char *) (evt) + ((evt)->ate_flags & AFTER_TRIGGER_OFFSET)))
3587 
3588 /*
3589  * To avoid palloc overhead, we keep trigger events in arrays in successively-
3590  * larger chunks (a slightly more sophisticated version of an expansible
3591  * array). The space between CHUNK_DATA_START and freeptr is occupied by
3592  * AfterTriggerEventData records; the space between endfree and endptr is
3593  * occupied by AfterTriggerSharedData records.
3594  */
3596 {
3597  struct AfterTriggerEventChunk *next; /* list link */
3598  char *freeptr; /* start of free space in chunk */
3599  char *endfree; /* end of free space in chunk */
3600  char *endptr; /* end of chunk */
3601  /* event data follows here */
3603 
3604 #define CHUNK_DATA_START(cptr) ((char *) (cptr) + MAXALIGN(sizeof(AfterTriggerEventChunk)))
3605 
3606 /* A list of events */
3608 {
3611  char *tailfree; /* freeptr of tail chunk */
3613 
3614 /* Macros to help in iterating over a list of events */
3615 #define for_each_chunk(cptr, evtlist) \
3616  for (cptr = (evtlist).head; cptr != NULL; cptr = cptr->next)
3617 #define for_each_event(eptr, cptr) \
3618  for (eptr = (AfterTriggerEvent) CHUNK_DATA_START(cptr); \
3619  (char *) eptr < (cptr)->freeptr; \
3620  eptr = (AfterTriggerEvent) (((char *) eptr) + SizeofTriggerEvent(eptr)))
3621 /* Use this if no special per-chunk processing is needed */
3622 #define for_each_event_chunk(eptr, cptr, evtlist) \
3623  for_each_chunk(cptr, evtlist) for_each_event(eptr, cptr)
3624 
3625 /* Macros for iterating from a start point that might not be list start */
3626 #define for_each_chunk_from(cptr) \
3627  for (; cptr != NULL; cptr = cptr->next)
3628 #define for_each_event_from(eptr, cptr) \
3629  for (; \
3630  (char *) eptr < (cptr)->freeptr; \
3631  eptr = (AfterTriggerEvent) (((char *) eptr) + SizeofTriggerEvent(eptr)))
3632 
3633 
3634 /*
3635  * All per-transaction data for the AFTER TRIGGERS module.
3636  *
3637  * AfterTriggersData has the following fields:
3638  *
3639  * firing_counter is incremented for each call of afterTriggerInvokeEvents.
3640  * We mark firable events with the current firing cycle's ID so that we can
3641  * tell which ones to work on. This ensures sane behavior if a trigger
3642  * function chooses to do SET CONSTRAINTS: the inner SET CONSTRAINTS will
3643  * only fire those events that weren't already scheduled for firing.
3644  *
3645  * state keeps track of the transaction-local effects of SET CONSTRAINTS.
3646  * This is saved and restored across failed subtransactions.
3647  *
3648  * events is the current list of deferred events. This is global across
3649  * all subtransactions of the current transaction. In a subtransaction
3650  * abort, we know that the events added by the subtransaction are at the
3651  * end of the list, so it is relatively easy to discard them. The event
3652  * list chunks themselves are stored in event_cxt.
3653  *
3654  * query_depth is the current depth of nested AfterTriggerBeginQuery calls
3655  * (-1 when the stack is empty).
3656  *
3657  * query_stack[query_depth] is the per-query-level data, including these fields:
3658  *
3659  * events is a list of AFTER trigger events queued by the current query.
3660  * None of these are valid until the matching AfterTriggerEndQuery call
3661  * occurs. At that point we fire immediate-mode triggers, and append any
3662  * deferred events to the main events list.
3663  *
3664  * fdw_tuplestore is a tuplestore containing the foreign-table tuples
3665  * needed by events queued by the current query. (Note: we use just one
3666  * tuplestore even though more than one foreign table might be involved.
3667  * This is okay because tuplestores don't really care what's in the tuples
3668  * they store; but it's possible that someday it'd break.)
3669  *
3670  * tables is a List of AfterTriggersTableData structs for target tables
3671  * of the current query (see below).
3672  *
3673  * maxquerydepth is just the allocated length of query_stack.
3674  *
3675  * trans_stack holds per-subtransaction data, including these fields:
3676  *
3677  * state is NULL or a pointer to a saved copy of the SET CONSTRAINTS
3678  * state data. Each subtransaction level that modifies that state first
3679  * saves a copy, which we use to restore the state if we abort.
3680  *
3681  * events is a copy of the events head/tail pointers,
3682  * which we use to restore those values during subtransaction abort.
3683  *
3684  * query_depth is the subtransaction-start-time value of query_depth,
3685  * which we similarly use to clean up at subtransaction abort.
3686  *
3687  * firing_counter is the subtransaction-start-time value of firing_counter.
3688  * We use this to recognize which deferred triggers were fired (or marked
3689  * for firing) within an aborted subtransaction.
3690  *
3691  * We use GetCurrentTransactionNestLevel() to determine the correct array
3692  * index in trans_stack. maxtransdepth is the number of allocated entries in
3693  * trans_stack. (By not keeping our own stack pointer, we can avoid trouble
3694  * in cases where errors during subxact abort cause multiple invocations
3695  * of AfterTriggerEndSubXact() at the same nesting depth.)
3696  *
3697  * We create an AfterTriggersTableData struct for each target table of the
3698  * current query, and each operation mode (INSERT/UPDATE/DELETE), that has
3699  * either transition tables or statement-level triggers. This is used to
3700  * hold the relevant transition tables, as well as info tracking whether
3701  * we already queued the statement triggers. (We use that info to prevent
3702  * firing the same statement triggers more than once per statement, or really
3703  * once per transition table set.) These structs, along with the transition
3704  * table tuplestores, live in the (sub)transaction's CurTransactionContext.
3705  * That's sufficient lifespan because we don't allow transition tables to be
3706  * used by deferrable triggers, so they only need to survive until
3707  * AfterTriggerEndQuery.
3708  */
3712 
3713 typedef struct AfterTriggersData
3714 {
3715  CommandId firing_counter; /* next firing ID to assign */
3716  SetConstraintState state; /* the active S C state */
3717  AfterTriggerEventList events; /* deferred-event list */
3718  MemoryContext event_cxt; /* memory context for events, if any */
3719 
3720  /* per-query-level data: */
3721  AfterTriggersQueryData *query_stack; /* array of structs shown below */
3722  int query_depth; /* current index in above array */
3723  int maxquerydepth; /* allocated len of above array */
3724 
3725  /* per-subtransaction-level data: */
3726  AfterTriggersTransData *trans_stack; /* array of structs shown below */
3727  int maxtransdepth; /* allocated len of above array */
3729 
3731 {
3732  AfterTriggerEventList events; /* events pending from this query */
3733  Tuplestorestate *fdw_tuplestore; /* foreign tuples for said events */
3734  List *tables; /* list of AfterTriggersTableData, see below */
3735 };
3736 
3738 {
3739  /* these fields are just for resetting at subtrans abort: */
3740  SetConstraintState state; /* saved S C state, or NULL if not yet saved */
3741  AfterTriggerEventList events; /* saved list pointer */
3742  int query_depth; /* saved query_depth */
3743  CommandId firing_counter; /* saved firing_counter */
3744 };
3745 
3747 {
3748  /* relid + cmdType form the lookup key for these structs: */
3749  Oid relid; /* target table's OID */
3750  CmdType cmdType; /* event type, CMD_INSERT/UPDATE/DELETE */
3751  bool closed; /* true when no longer OK to add tuples */
3752  bool before_trig_done; /* did we already queue BS triggers? */
3753  bool after_trig_done; /* did we already queue AS triggers? */
3754  AfterTriggerEventList after_trig_events; /* if so, saved list pointer */
3755  Tuplestorestate *old_tuplestore; /* "old" transition table, if any */
3756  Tuplestorestate *new_tuplestore; /* "new" transition table, if any */
3757  TupleTableSlot *storeslot; /* for converting to tuplestore's format */
3758 };
3759 
3761 
3762 static void AfterTriggerExecute(EState *estate,
3763  AfterTriggerEvent event,
3764  ResultRelInfo *relInfo,
3765  TriggerDesc *trigdesc,
3766  FmgrInfo *finfo,
3767  Instrumentation *instr,
3768  MemoryContext per_tuple_context,
3769  TupleTableSlot *trig_tuple_slot1,
3770  TupleTableSlot *trig_tuple_slot2);
3772  CmdType cmdType);
3774  TupleDesc tupdesc);
3776 static SetConstraintState SetConstraintStateCreate(int numalloc);
3779  Oid tgoid, bool tgisdeferred);
3780 static void cancel_prior_stmt_triggers(Oid relid, CmdType cmdType, int tgevent);
3781 
3782 
3783 /*
3784  * Get the FDW tuplestore for the current trigger query level, creating it
3785  * if necessary.
3786  */
3787 static Tuplestorestate *
3789 {
3790  Tuplestorestate *ret;
3791 
3793  if (ret == NULL)
3794  {
3795  MemoryContext oldcxt;
3796  ResourceOwner saveResourceOwner;
3797 
3798  /*
3799  * Make the tuplestore valid until end of subtransaction. We really
3800  * only need it until AfterTriggerEndQuery().
3801  */
3803  saveResourceOwner = CurrentResourceOwner;
3805 
3806  ret = tuplestore_begin_heap(false, false, work_mem);
3807 
3808  CurrentResourceOwner = saveResourceOwner;
3809  MemoryContextSwitchTo(oldcxt);
3810 
3812  }
3813 
3814  return ret;
3815 }
3816 
3817 /* ----------
3818  * afterTriggerCheckState()
3819  *
3820  * Returns true if the trigger event is actually in state DEFERRED.
3821  * ----------
3822  */
3823 static bool
3825 {
3826  Oid tgoid = evtshared->ats_tgoid;
3828  int i;
3829 
3830  /*
3831  * For not-deferrable triggers (i.e. normal AFTER ROW triggers and
3832  * constraints declared NOT DEFERRABLE), the state is always false.
3833  */
3834  if ((evtshared->ats_event & AFTER_TRIGGER_DEFERRABLE) == 0)
3835  return false;
3836 
3837  /*
3838  * If constraint state exists, SET CONSTRAINTS might have been executed
3839  * either for this trigger or for all triggers.
3840  */
3841  if (state != NULL)
3842  {
3843  /* Check for SET CONSTRAINTS for this specific trigger. */
3844  for (i = 0; i < state->numstates; i++)
3845  {
3846  if (state->trigstates[i].sct_tgoid == tgoid)
3847  return state->trigstates[i].sct_tgisdeferred;
3848  }
3849 
3850  /* Check for SET CONSTRAINTS ALL. */
3851  if (state->all_isset)
3852  return state->all_isdeferred;
3853  }
3854 
3855  /*
3856  * Otherwise return the default state for the trigger.
3857  */
3858  return ((evtshared->ats_event & AFTER_TRIGGER_INITDEFERRED) != 0);
3859 }
3860 
3861 
3862 /* ----------
3863  * afterTriggerAddEvent()
3864  *
3865  * Add a new trigger event to the specified queue.
3866  * The passed-in event data is copied.
3867  * ----------
3868  */
3869 static void
3871  AfterTriggerEvent event, AfterTriggerShared evtshared)
3872 {
3873  Size eventsize = SizeofTriggerEvent(event);
3874  Size needed = eventsize + sizeof(AfterTriggerSharedData);
3875  AfterTriggerEventChunk *chunk;
3876  AfterTriggerShared newshared;
3877  AfterTriggerEvent newevent;
3878 
3879  /*
3880  * If empty list or not enough room in the tail chunk, make a new chunk.
3881  * We assume here that a new shared record will always be needed.
3882  */
3883  chunk = events->tail;
3884  if (chunk == NULL ||
3885  chunk->endfree - chunk->freeptr < needed)
3886  {
3887  Size chunksize;
3888 
3889  /* Create event context if we didn't already */
3890  if (afterTriggers.event_cxt == NULL)
3893  "AfterTriggerEvents",
3895 
3896  /*
3897  * Chunk size starts at 1KB and is allowed to increase up to 1MB.
3898  * These numbers are fairly arbitrary, though there is a hard limit at
3899  * AFTER_TRIGGER_OFFSET; else we couldn't link event records to their
3900  * shared records using the available space in ate_flags. Another
3901  * constraint is that if the chunk size gets too huge, the search loop
3902  * below would get slow given a (not too common) usage pattern with
3903  * many distinct event types in a chunk. Therefore, we double the
3904  * preceding chunk size only if there weren't too many shared records
3905  * in the preceding chunk; otherwise we halve it. This gives us some
3906  * ability to adapt to the actual usage pattern of the current query
3907  * while still having large chunk sizes in typical usage. All chunk
3908  * sizes used should be MAXALIGN multiples, to ensure that the shared
3909  * records will be aligned safely.
3910  */
3911 #define MIN_CHUNK_SIZE 1024
3912 #define MAX_CHUNK_SIZE (1024*1024)
3913 
3914 #if MAX_CHUNK_SIZE > (AFTER_TRIGGER_OFFSET+1)
3915 #error MAX_CHUNK_SIZE must not exceed AFTER_TRIGGER_OFFSET
3916 #endif
3917 
3918  if (chunk == NULL)
3919  chunksize = MIN_CHUNK_SIZE;
3920  else
3921  {
3922  /* preceding chunk size... */
3923  chunksize = chunk->endptr - (char *) chunk;
3924  /* check number of shared records in preceding chunk */
3925  if ((chunk->endptr - chunk->endfree) <=
3926  (100 * sizeof(AfterTriggerSharedData)))
3927  chunksize *= 2; /* okay, double it */
3928  else
3929  chunksize /= 2; /* too many shared records */
3930  chunksize = Min(chunksize, MAX_CHUNK_SIZE);
3931  }
3932  chunk = MemoryContextAlloc(afterTriggers.event_cxt, chunksize);
3933  chunk->next = NULL;
3934  chunk->freeptr = CHUNK_DATA_START(chunk);
3935  chunk->endptr = chunk->endfree = (char *) chunk + chunksize;
3936  Assert(chunk->endfree - chunk->freeptr >= needed);
3937 
3938  if (events->head == NULL)
3939  events->head = chunk;
3940  else
3941  events->tail->next = chunk;
3942  events->tail = chunk;
3943  /* events->tailfree is now out of sync, but we'll fix it below */
3944  }
3945 
3946  /*
3947  * Try to locate a matching shared-data record already in the chunk. If
3948  * none, make a new one.
3949  */
3950  for (newshared = ((AfterTriggerShared) chunk->endptr) - 1;
3951  (char *) newshared >= chunk->endfree;
3952  newshared--)
3953  {
3954  if (newshared->ats_tgoid == evtshared->ats_tgoid &&
3955  newshared->ats_relid == evtshared->ats_relid &&
3956  newshared->ats_event == evtshared->ats_event &&
3957  newshared->ats_table == evtshared->ats_table &&
3958  newshared->ats_firing_id == 0)
3959  break;
3960  }
3961  if ((char *) newshared < chunk->endfree)
3962  {
3963  *newshared = *evtshared;
3964  newshared->ats_firing_id = 0; /* just to be sure */
3965  chunk->endfree = (char *) newshared;
3966  }
3967 
3968  /* Insert the data */
3969  newevent = (AfterTriggerEvent) chunk->freeptr;
3970  memcpy(newevent, event, eventsize);
3971  /* ... and link the new event to its shared record */
3972  newevent->ate_flags &= ~AFTER_TRIGGER_OFFSET;
3973  newevent->ate_flags |= (char *) newshared - (char *) newevent;
3974 
3975  chunk->freeptr += eventsize;
3976  events->tailfree = chunk->freeptr;
3977 }
3978 
3979 /* ----------
3980  * afterTriggerFreeEventList()
3981  *
3982  * Free all the event storage in the given list.
3983  * ----------
3984  */
3985 static void
3987 {
3988  AfterTriggerEventChunk *chunk;
3989 
3990  while ((chunk = events->head) != NULL)
3991  {
3992  events->head = chunk->next;
3993  pfree(chunk);
3994  }
3995  events->tail = NULL;
3996  events->tailfree = NULL;
3997 }
3998 
3999 /* ----------
4000  * afterTriggerRestoreEventList()
4001  *
4002  * Restore an event list to its prior length, removing all the events
4003  * added since it had the value old_events.
4004  * ----------
4005  */
4006 static void
4008  const AfterTriggerEventList *old_events)
4009 {
4010  AfterTriggerEventChunk *chunk;
4011  AfterTriggerEventChunk *next_chunk;
4012 
4013  if (old_events->tail == NULL)
4014  {
4015  /* restoring to a completely empty state, so free everything */
4016  afterTriggerFreeEventList(events);
4017  }
4018  else
4019  {
4020  *events = *old_events;
4021  /* free any chunks after the last one we want to keep */
4022  for (chunk = events->tail->next; chunk != NULL; chunk = next_chunk)
4023  {
4024  next_chunk = chunk->next;
4025  pfree(chunk);
4026  }
4027  /* and clean up the tail chunk to be the right length */
4028  events->tail->next = NULL;
4029  events->tail->freeptr = events->tailfree;
4030 
4031  /*
4032  * We don't make any effort to remove now-unused shared data records.
4033  * They might still be useful, anyway.
4034  */
4035  }
4036 }
4037 
4038 /* ----------
4039  * afterTriggerDeleteHeadEventChunk()
4040  *
4041  * Remove the first chunk of events from the query level's event list.
4042  * Keep any event list pointers elsewhere in the query level's data
4043  * structures in sync.
4044  * ----------
4045  */
4046 static void
4048 {
4049  AfterTriggerEventChunk *target = qs->events.head;
4050  ListCell *lc;
4051 
4052  Assert(target && target->next);
4053 
4054  /*
4055  * First, update any pointers in the per-table data, so that they won't be
4056  * dangling. Resetting obsoleted pointers to NULL will make
4057  * cancel_prior_stmt_triggers start from the list head, which is fine.
4058  */
4059  foreach(lc, qs->tables)
4060  {
4062 
4063  if (table->after_trig_done &&
4064  table->after_trig_events.tail == target)
4065  {
4066  table->after_trig_events.head = NULL;
4067  table->after_trig_events.tail = NULL;
4068  table->after_trig_events.tailfree = NULL;
4069  }
4070  }
4071 
4072  /* Now we can flush the head chunk */
4073  qs->events.head = target->next;
4074  pfree(target);
4075 }
4076 
4077 
4078 /* ----------
4079  * AfterTriggerExecute()
4080  *
4081  * Fetch the required tuples back from the heap and fire one
4082  * single trigger function.
4083  *
4084  * Frequently, this will be fired many times in a row for triggers of
4085  * a single relation. Therefore, we cache the open relation and provide
4086  * fmgr lookup cache space at the caller level. (For triggers fired at
4087  * the end of a query, we can even piggyback on the executor's state.)
4088  *
4089  * event: event currently being fired.
4090  * rel: open relation for event.
4091  * trigdesc: working copy of rel's trigger info.
4092  * finfo: array of fmgr lookup cache entries (one per trigger in trigdesc).
4093  * instr: array of EXPLAIN ANALYZE instrumentation nodes (one per trigger),
4094  * or NULL if no instrumentation is wanted.
4095  * per_tuple_context: memory context to call trigger function in.
4096  * trig_tuple_slot1: scratch slot for tg_trigtuple (foreign tables only)
4097  * trig_tuple_slot2: scratch slot for tg_newtuple (foreign tables only)
4098  * ----------
4099  */
4100 static void
4102  AfterTriggerEvent event,
4103  ResultRelInfo *relInfo,
4104  TriggerDesc *trigdesc,
4105  FmgrInfo *finfo, Instrumentation *instr,
4106  MemoryContext per_tuple_context,
4107  TupleTableSlot *trig_tuple_slot1,
4108  TupleTableSlot *trig_tuple_slot2)
4109 {
4110  Relation rel = relInfo->ri_RelationDesc;
4111  AfterTriggerShared evtshared = GetTriggerSharedData(event);
4112  Oid tgoid = evtshared->ats_tgoid;
4113  TriggerData LocTriggerData = {0};
4114  HeapTuple rettuple;
4115  int tgindx;
4116  bool should_free_trig = false;
4117  bool should_free_new = false;
4118 
4119  /*
4120  * Locate trigger in trigdesc.
4121  */
4122  for (tgindx = 0; tgindx < trigdesc->numtriggers; tgindx++)
4123  {
4124  if (trigdesc->triggers[tgindx].tgoid == tgoid)
4125  {
4126  LocTriggerData.tg_trigger = &(trigdesc->triggers[tgindx]);
4127  break;
4128  }
4129  }
4130  if (LocTriggerData.tg_trigger == NULL)
4131  elog(ERROR, "could not find trigger %u", tgoid);
4132 
4133  /*
4134  * If doing EXPLAIN ANALYZE, start charging time to this trigger. We want
4135  * to include time spent re-fetching tuples in the trigger cost.
4136  */
4137  if (instr)
4138  InstrStartNode(instr + tgindx);
4139 
4140  /*
4141  * Fetch the required tuple(s).
4142  */
4143  switch (event->ate_flags & AFTER_TRIGGER_TUP_BITS)
4144  {
4146  {
4147  Tuplestorestate *fdw_tuplestore = GetCurrentFDWTuplestore();
4148 
4149  if (!tuplestore_gettupleslot(fdw_tuplestore, true, false,
4150  trig_tuple_slot1))
4151  elog(ERROR, "failed to fetch tuple1 for AFTER trigger");
4152 
4153  if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) ==
4155  !tuplestore_gettupleslot(fdw_tuplestore, true, false,
4156  trig_tuple_slot2))
4157  elog(ERROR, "failed to fetch tuple2 for AFTER trigger");
4158  }
4159  /* fall through */
4161 
4162  /*
4163  * Store tuple in the slot so that tg_trigtuple does not reference
4164  * tuplestore memory. (It is formally possible for the trigger
4165  * function to queue trigger events that add to the same
4166  * tuplestore, which can push other tuples out of memory.) The
4167  * distinction is academic, because we start with a minimal tuple
4168  * that is stored as a heap tuple, constructed in different memory
4169  * context, in the slot anyway.
4170  */
4171  LocTriggerData.tg_trigslot = trig_tuple_slot1;
4172  LocTriggerData.tg_trigtuple =
4173  ExecFetchSlotHeapTuple(trig_tuple_slot1, true, &should_free_trig);
4174 
4175  if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) ==
4177  {
4178  LocTriggerData.tg_newslot = trig_tuple_slot2;
4179  LocTriggerData.tg_newtuple =
4180  ExecFetchSlotHeapTuple(trig_tuple_slot2, true, &should_free_new);
4181  }
4182  else
4183  {
4184  LocTriggerData.tg_newtuple = NULL;
4185  }
4186  break;
4187 
4188  default:
4189  if (ItemPointerIsValid(&(event->ate_ctid1)))
4190  {
4191  LocTriggerData.tg_trigslot = ExecGetTriggerOldSlot(estate, relInfo);
4192 
4193  if (!table_tuple_fetch_row_version(rel, &(event->ate_ctid1),
4194  SnapshotAny,
4195  LocTriggerData.tg_trigslot))
4196  elog(ERROR, "failed to fetch tuple1 for AFTER trigger");
4197  LocTriggerData.tg_trigtuple =
4198  ExecFetchSlotHeapTuple(LocTriggerData.tg_trigslot, false, &should_free_trig);
4199  }
4200  else
4201  {
4202  LocTriggerData.tg_trigtuple = NULL;
4203  }
4204 
4205  /* don't touch ctid2 if not there */
4206  if ((event->ate_flags & AFTER_TRIGGER_TUP_BITS) ==
4208  ItemPointerIsValid(&(event->ate_ctid2)))
4209  {
4210  LocTriggerData.tg_newslot = ExecGetTriggerNewSlot(estate, relInfo);
4211 
4212  if (!table_tuple_fetch_row_version(rel, &(event->ate_ctid2),
4213  SnapshotAny,
4214  LocTriggerData.tg_newslot))
4215  elog(ERROR, "failed to fetch tuple2 for AFTER trigger");
4216  LocTriggerData.tg_newtuple =
4217  ExecFetchSlotHeapTuple(LocTriggerData.tg_newslot, false, &should_free_new);
4218  }
4219  else
4220  {
4221  LocTriggerData.tg_newtuple = NULL;
4222  }
4223  }
4224 
4225  /*
4226  * Set up the tuplestore information to let the trigger have access to
4227  * transition tables. When we first make a transition table available to
4228  * a trigger, mark it "closed" so that it cannot change anymore. If any
4229  * additional events of the same type get queued in the current trigger
4230  * query level, they'll go into new transition tables.
4231  */
4232  LocTriggerData.tg_oldtable = LocTriggerData.tg_newtable = NULL;
4233  if (evtshared->ats_table)
4234  {
4235  if (LocTriggerData.tg_trigger->tgoldtable)
4236  {
4237  LocTriggerData.tg_oldtable = evtshared->ats_table->old_tuplestore;
4238  evtshared->ats_table->closed = true;
4239  }
4240 
4241  if (LocTriggerData.tg_trigger->tgnewtable)
4242  {
4243  LocTriggerData.tg_newtable = evtshared->ats_table->new_tuplestore;
4244  evtshared->ats_table->closed = true;
4245  }
4246  }
4247 
4248  /*
4249  * Setup the remaining trigger information
4250  */
4251  LocTriggerData.type = T_TriggerData;
4252  LocTriggerData.tg_event =
4254  LocTriggerData.tg_relation = rel;
4255  if (TRIGGER_FOR_UPDATE(LocTriggerData.tg_trigger->tgtype))
4256  LocTriggerData.tg_updatedcols = evtshared->ats_modifiedcols;
4257 
4258  MemoryContextReset(per_tuple_context);
4259 
4260  /*
4261  * Call the trigger and throw away any possibly returned updated tuple.
4262  * (Don't let ExecCallTriggerFunc measure EXPLAIN time.)
4263  */
4264  rettuple = ExecCallTriggerFunc(&LocTriggerData,
4265  tgindx,
4266  finfo,
4267  NULL,
4268  per_tuple_context);
4269  if (rettuple != NULL &&
4270  rettuple != LocTriggerData.tg_trigtuple &&
4271  rettuple != LocTriggerData.tg_newtuple)
4272  heap_freetuple(rettuple);
4273 
4274  /*
4275  * Release resources
4276  */
4277  if (should_free_trig)
4278  heap_freetuple(LocTriggerData.tg_trigtuple);
4279  if (should_free_new)
4280  heap_freetuple(LocTriggerData.tg_newtuple);
4281 
4282  /* don't clear slots' contents if foreign table */
4283  if (trig_tuple_slot1 == NULL)
4284  {
4285  if (LocTriggerData.tg_trigslot)
4286  ExecClearTuple(LocTriggerData.tg_trigslot);
4287  if (LocTriggerData.tg_newslot)
4288  ExecClearTuple(LocTriggerData.tg_newslot);
4289  }
4290 
4291  /*
4292  * If doing EXPLAIN ANALYZE, stop charging time to this trigger, and count
4293  * one "tuple returned" (really the number of firings).
4294  */
4295  if (instr)
4296  InstrStopNode(instr + tgindx, 1);
4297 }
4298 
4299 
4300 /*
4301  * afterTriggerMarkEvents()
4302  *
4303  * Scan the given event list for not yet invoked events. Mark the ones
4304  * that can be invoked now with the current firing ID.
4305  *
4306  * If move_list isn't NULL, events that are not to be invoked now are
4307  * transferred to move_list.
4308  *
4309  * When immediate_only is true, do not invoke currently-deferred triggers.
4310  * (This will be false only at main transaction exit.)
4311  *
4312  * Returns true if any invokable events were found.
4313  */
4314 static bool
4316  AfterTriggerEventList *move_list,
4317  bool immediate_only)
4318 {
4319  bool found = false;
4320  bool deferred_found = false;
4321  AfterTriggerEvent event;
4322  AfterTriggerEventChunk *chunk;
4323 
4324  for_each_event_chunk(event, chunk, *events)
4325  {
4326  AfterTriggerShared evtshared = GetTriggerSharedData(event);
4327  bool defer_it = false;
4328 
4329  if (!(event->ate_flags &
4331  {
4332  /*
4333  * This trigger hasn't been called or scheduled yet. Check if we
4334  * should call it now.
4335  */
4336  if (immediate_only && afterTriggerCheckState(evtshared))
4337  {
4338  defer_it = true;
4339  }
4340  else
4341  {
4342  /*
4343  * Mark it as to be fired in this firing cycle.
4344  */
4346  event->ate_flags |= AFTER_TRIGGER_IN_PROGRESS;
4347  found = true;
4348  }
4349  }
4350 
4351  /*
4352  * If it's deferred, move it to move_list, if requested.
4353  */
4354  if (defer_it && move_list != NULL)
4355  {
4356  deferred_found = true;
4357  /* add it to move_list */
4358  afterTriggerAddEvent(move_list, event, evtshared);
4359  /* mark original copy "done" so we don't do it again */
4360  event->ate_flags |= AFTER_TRIGGER_DONE;
4361  }
4362  }
4363 
4364  /*
4365  * We could allow deferred triggers if, before the end of the
4366  * security-restricted operation, we were to verify that a SET CONSTRAINTS
4367  * ... IMMEDIATE has fired all such triggers. For now, don't bother.
4368  */
4369  if (deferred_found && InSecurityRestrictedOperation())
4370  ereport(ERROR,
4371  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4372  errmsg("cannot fire deferred trigger within security-restricted operation")));
4373 
4374  return found;
4375 }
4376 
4377 /*
4378  * afterTriggerInvokeEvents()
4379  *
4380  * Scan the given event list for events that are marked as to be fired
4381  * in the current firing cycle, and fire them.
4382  *
4383  * If estate isn't NULL, we use its result relation info to avoid repeated
4384  * openings and closing of trigger target relations. If it is NULL, we
4385  * make one locally to cache the info in case there are multiple trigger
4386  * events per rel.
4387  *
4388  * When delete_ok is true, it's safe to delete fully-processed events.
4389  * (We are not very tense about that: we simply reset a chunk to be empty
4390  * if all its events got fired. The objective here is just to avoid useless
4391  * rescanning of events when a trigger queues new events during transaction
4392  * end, so it's not necessary to worry much about the case where only
4393  * some events are fired.)
4394  *
4395  * Returns true if no unfired events remain in the list (this allows us
4396  * to avoid repeating afterTriggerMarkEvents).
4397  */
4398 static bool
4400  CommandId firing_id,
4401  EState *estate,
4402  bool delete_ok)
4403 {
4404  bool all_fired = true;
4405  AfterTriggerEventChunk *chunk;
4406  MemoryContext per_tuple_context;
4407  bool local_estate = false;
4408  ResultRelInfo *rInfo = NULL;
4409  Relation rel = NULL;
4410  TriggerDesc *trigdesc = NULL;
4411  FmgrInfo *finfo = NULL;
4412  Instrumentation *instr = NULL;
4413  TupleTableSlot *slot1 = NULL,
4414  *slot2 = NULL;
4415 
4416  /* Make a local EState if need be */
4417  if (estate == NULL)
4418  {
4419  estate = CreateExecutorState();
4420  local_estate = true;
4421  }
4422 
4423  /* Make a per-tuple memory context for trigger function calls */
4424  per_tuple_context =
4426  "AfterTriggerTupleContext",
4428 
4429  for_each_chunk(chunk, *events)
4430  {
4431  AfterTriggerEvent event;
4432  bool all_fired_in_chunk = true;
4433 
4434  for_each_event(event, chunk)
4435  {
4436  AfterTriggerShared evtshared = GetTriggerSharedData(event);
4437 
4438  /*
4439  * Is it one for me to fire?
4440  */
4441  if ((event->ate_flags & AFTER_TRIGGER_IN_PROGRESS) &&
4442  evtshared->ats_firing_id == firing_id)
4443  {
4444  /*
4445  * So let's fire it... but first, find the correct relation if
4446  * this is not the same relation as before.
4447  */
4448  if (rel == NULL || RelationGetRelid(rel) != evtshared->ats_relid)
4449  {
4450  rInfo = ExecGetTriggerResultRel(estate, evtshared->ats_relid);
4451  rel = rInfo->ri_RelationDesc;
4452  /* Catch calls with insufficient relcache refcounting */
4454  trigdesc = rInfo->ri_TrigDesc;
4455  finfo = rInfo->ri_TrigFunctions;
4456  instr = rInfo->ri_TrigInstrument;
4457  if (slot1 != NULL)
4458  {
4461  slot1 = slot2 = NULL;
4462  }
4463  if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
4464  {
4465  slot1 = MakeSingleTupleTableSlot(rel->rd_att,
4467  slot2 = MakeSingleTupleTableSlot(rel->rd_att,
4469  }
4470  if (trigdesc == NULL) /* should not happen */
4471  elog(ERROR, "relation %u has no triggers",
4472  evtshared->ats_relid);
4473  }
4474 
4475  /*
4476  * Fire it. Note that the AFTER_TRIGGER_IN_PROGRESS flag is
4477  * still set, so recursive examinations of the event list
4478  * won't try to re-fire it.
4479  */
4480  AfterTriggerExecute(estate, event, rInfo, trigdesc, finfo, instr,
4481  per_tuple_context, slot1, slot2);
4482 
4483  /*
4484  * Mark the event as done.
4485  */
4486  event->ate_flags &= ~AFTER_TRIGGER_IN_PROGRESS;
4487  event->ate_flags |= AFTER_TRIGGER_DONE;
4488  }
4489  else if (!(event->ate_flags & AFTER_TRIGGER_DONE))
4490  {
4491  /* something remains to be done */
4492  all_fired = all_fired_in_chunk = false;
4493  }
4494  }
4495 
4496  /* Clear the chunk if delete_ok and nothing left of interest */
4497  if (delete_ok && all_fired_in_chunk)
4498  {
4499  chunk->freeptr = CHUNK_DATA_START(chunk);
4500  chunk->endfree = chunk->endptr;
4501 
4502  /*
4503  * If it's last chunk, must sync event list's tailfree too. Note
4504  * that delete_ok must NOT be passed as true if there could be
4505  * additional AfterTriggerEventList values pointing at this event
4506  * list, since we'd fail to fix their copies of tailfree.
4507  */
4508  if (chunk == events->tail)
4509  events->tailfree = chunk->freeptr;
4510  }
4511  }
4512  if (slot1 != NULL)
4513  {
4516  }
4517 
4518  /* Release working resources */
4519  MemoryContextDelete(per_tuple_context);
4520 
4521  if (local_estate)
4522  {
4523  ExecCloseResultRelations(estate);
4524  ExecResetTupleTable(estate->es_tupleTable, false);
4525  FreeExecutorState(estate);
4526  }
4527 
4528  return all_fired;
4529 }
4530 
4531 
4532 /*
4533  * GetAfterTriggersTableData
4534  *
4535  * Find or create an AfterTriggersTableData struct for the specified
4536  * trigger event (relation + operation type). Ignore existing structs
4537  * marked "closed"; we don't want to put any additional tuples into them,
4538  * nor change their stmt-triggers-fired state.
4539  *
4540  * Note: the AfterTriggersTableData list is allocated in the current
4541  * (sub)transaction's CurTransactionContext. This is OK because
4542  * we don't need it to live past AfterTriggerEndQuery.
4543  */
4544 static AfterTriggersTableData *
4546 {
4547  AfterTriggersTableData *table;
4549  MemoryContext oldcxt;
4550  ListCell *lc;
4551 
4552  /* Caller should have ensured query_depth is OK. */
4556 
4557  foreach(lc, qs->tables)
4558  {
4559  table = (AfterTriggersTableData *) lfirst(lc);
4560  if (table->relid == relid && table->cmdType == cmdType &&
4561  !table->closed)
4562  return table;
4563  }
4564 
4566 
4568  table->relid = relid;
4569  table->cmdType = cmdType;
4570  qs->tables = lappend(qs->tables, table);
4571 
4572  MemoryContextSwitchTo(oldcxt);
4573 
4574  return table;
4575 }
4576 
4577 /*
4578  * Returns a TupleTableSlot suitable for holding the tuples to be put
4579  * into AfterTriggersTableData's transition table tuplestores.
4580  */
4581 static TupleTableSlot *
4583  TupleDesc tupdesc)
4584 {
4585  /* Create it if not already done. */
4586  if (!table->storeslot)
4587  {
4588  MemoryContext oldcxt;
4589 
4590  /*
4591  * We only need this slot only until AfterTriggerEndQuery, but making
4592  * it last till end-of-subxact is good enough. It'll be freed by
4593  * AfterTriggerFreeQuery().
4594  */
4596  table->storeslot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
4597  MemoryContextSwitchTo(oldcxt);
4598  }
4599 
4600  return table->storeslot;
4601 }
4602 
4603 /*
4604  * MakeTransitionCaptureState
4605  *
4606  * Make a TransitionCaptureState object for the given TriggerDesc, target
4607  * relation, and operation type. The TCS object holds all the state needed
4608  * to decide whether to capture tuples in transition tables.
4609  *
4610  * If there are no triggers in 'trigdesc' that request relevant transition
4611  * tables, then return NULL.
4612  *
4613  * The resulting object can be passed to the ExecAR* functions. When
4614  * dealing with child tables, the caller can set tcs_original_insert_tuple
4615  * to avoid having to reconstruct the original tuple in the root table's
4616  * format.
4617  *
4618  * Note that we copy the flags from a parent table into this struct (rather
4619  * than subsequently using the relation's TriggerDesc directly) so that we can
4620  * use it to control collection of transition tuples from child tables.
4621  *
4622  * Per SQL spec, all operations of the same kind (INSERT/UPDATE/DELETE)
4623  * on the same table during one query should share one transition table.
4624  * Therefore, the Tuplestores are owned by an AfterTriggersTableData struct
4625  * looked up using the table OID + CmdType, and are merely referenced by
4626  * the TransitionCaptureState objects we hand out to callers.
4627  */
4630 {
4632  bool need_old,
4633  need_new;
4634  AfterTriggersTableData *table;
4635  MemoryContext oldcxt;
4636  ResourceOwner saveResourceOwner;
4637 
4638  if (trigdesc == NULL)
4639  return NULL;
4640 
4641  /* Detect which table(s) we need. */
4642  switch (cmdType)
4643  {
4644  case CMD_INSERT:
4645  need_old = false;
4646  need_new = trigdesc->trig_insert_new_table;
4647  break;
4648  case CMD_UPDATE:
4649  need_old = trigdesc->trig_update_old_table;
4650  need_new = trigdesc->trig_update_new_table;
4651  break;
4652  case CMD_DELETE:
4653  need_old = trigdesc->trig_delete_old_table;
4654  need_new = false;
4655  break;
4656  default:
4657  elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4658  need_old = need_new = false; /* keep compiler quiet */
4659  break;
4660  }
4661  if (!need_old && !need_new)
4662  return NULL;
4663 
4664  /* Check state, like AfterTriggerSaveEvent. */
4665  if (afterTriggers.query_depth < 0)
4666  elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4667 
4668  /* Be sure we have enough space to record events at this query depth. */
4671 
4672  /*
4673  * Find or create an AfterTriggersTableData struct to hold the
4674  * tuplestore(s). If there's a matching struct but it's marked closed,
4675  * ignore it; we need a newer one.
4676  *
4677  * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4678  * allocated in the current (sub)transaction's CurTransactionContext, and
4679  * the tuplestores are managed by the (sub)transaction's resource owner.
4680  * This is sufficient lifespan because we do not allow triggers using
4681  * transition tables to be deferrable; they will be fired during
4682  * AfterTriggerEndQuery, after which it's okay to delete the data.
4683  */
4684  table = GetAfterTriggersTableData(relid, cmdType);
4685 
4686  /* Now create required tuplestore(s), if we don't have them already. */
4688  saveResourceOwner = CurrentResourceOwner;
4690 
4691  if (need_old && table->old_tuplestore == NULL)
4692  table->old_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4693  if (need_new && table->new_tuplestore == NULL)
4694  table->new_tuplestore = tuplestore_begin_heap(false, false, work_mem);
4695 
4696  CurrentResourceOwner = saveResourceOwner;
4697  MemoryContextSwitchTo(oldcxt);
4698 
4699  /* Now build the TransitionCaptureState struct, in caller's context */
4701  state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
4702  state->tcs_update_old_table = trigdesc->trig_update_old_table;
4703  state->tcs_update_new_table = trigdesc->trig_update_new_table;
4704  state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
4705  state->tcs_private = table;
4706 
4707  return state;
4708 }
4709 
4710 
4711 /* ----------
4712  * AfterTriggerBeginXact()
4713  *
4714  * Called at transaction start (either BEGIN or implicit for single
4715  * statement outside of transaction block).
4716  * ----------
4717  */
4718 void
4720 {
4721  /*
4722  * Initialize after-trigger state structure to empty
4723  */
4724  afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
4726 
4727  /*
4728  * Verify that there is no leftover state remaining. If these assertions
4729  * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
4730  * up properly.
4731  */
4732  Assert(afterTriggers.state == NULL);
4733  Assert(afterTriggers.query_stack == NULL);
4735  Assert(afterTriggers.event_cxt == NULL);
4736  Assert(afterTriggers.events.head == NULL);
4737  Assert(afterTriggers.trans_stack == NULL);
4739 }
4740 
4741 
4742 /* ----------
4743  * AfterTriggerBeginQuery()
4744  *
4745  * Called just before we start processing a single query within a
4746  * transaction (or subtransaction). Most of the real work gets deferred
4747  * until somebody actually tries to queue a trigger event.
4748  * ----------
4749  */
4750 void
4752 {
4753  /* Increase the query stack depth */
4755 }
4756 
4757 
4758 /* ----------
4759  * AfterTriggerEndQuery()
4760  *
4761  * Called after one query has been completely processed. At this time
4762  * we invoke all AFTER IMMEDIATE trigger events queued by the query, and
4763  * transfer deferred trigger events to the global deferred-trigger list.
4764  *
4765  * Note that this must be called BEFORE closing down the executor
4766  * with ExecutorEnd, because we make use of the EState's info about
4767  * target relations. Normally it is called from ExecutorFinish.
4768  * ----------
4769  */
4770 void
4772 {
4774 
4775  /* Must be inside a query, too */
4777 
4778  /*
4779  * If we never even got as far as initializing the event stack, there
4780  * certainly won't be any events, so exit quickly.
4781  */
4783  {
4785  return;
4786  }
4787 
4788  /*
4789  * Process all immediate-mode triggers queued by the query, and move the
4790  * deferred ones to the main list of deferred events.
4791  *
4792  * Notice that we decide which ones will be fired, and put the deferred
4793  * ones on the main list, before anything is actually fired. This ensures
4794  * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
4795  * IMMEDIATE: all events we have decided to defer will be available for it
4796  * to fire.
4797  *
4798  * We loop in case a trigger queues more events at the same query level.
4799  * Ordinary trigger functions, including all PL/pgSQL trigger functions,
4800  * will instead fire any triggers in a dedicated query level. Foreign key
4801  * enforcement triggers do add to the current query level, thanks to their
4802  * passing fire_triggers = false to SPI_execute_snapshot(). Other
4803  * C-language triggers might do likewise.
4804  *
4805  * If we find no firable events, we don't have to increment
4806  * firing_counter.
4807  */
4809 
4810  for (;;)
4811  {
4813  {
4814  CommandId firing_id = afterTriggers.firing_counter++;
4815  AfterTriggerEventChunk *oldtail = qs->events.tail;
4816 
4817  if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
4818  break; /* all fired */
4819 
4820  /*
4821  * Firing a trigger could result in query_stack being repalloc'd,
4822  * so we must recalculate qs after each afterTriggerInvokeEvents
4823  * call. Furthermore, it's unsafe to pass delete_ok = true here,
4824  * because that could cause afterTriggerInvokeEvents to try to
4825  * access qs->events after the stack has been repalloc'd.
4826  */
4828 
4829  /*
4830  * We'll need to scan the events list again. To reduce the cost
4831  * of doing so, get rid of completely-fired chunks. We know that
4832  * all events were marked IN_PROGRESS or DONE at the conclusion of
4833  * afterTriggerMarkEvents, so any still-interesting events must
4834  * have been added after that, and so must be in the chunk that
4835  * was then the tail chunk, or in later chunks. So, zap all
4836  * chunks before oldtail. This is approximately the same set of
4837  * events we would have gotten rid of by passing delete_ok = true.
4838  */
4839  Assert(oldtail != NULL);
4840  while (qs->events.head != oldtail)
4842  }
4843  else
4844  break;
4845  }
4846 
4847  /* Release query-level-local storage, including tuplestores if any */
4849 
4851 }
4852 
4853 
4854 /*
4855  * AfterTriggerFreeQuery
4856  * Release subsidiary storage for a trigger query level.
4857  * This includes closing down tuplestores.
4858  * Note: it's important for this to be safe if interrupted by an error
4859  * and then called again for the same query level.
4860  */
4861 static void
4863 {
4864  Tuplestorestate *ts;
4865  List *tables;
4866  ListCell *lc;
4867 
4868  /* Drop the trigger events */
4870 
4871  /* Drop FDW tuplestore if any */
4872  ts = qs->fdw_tuplestore;
4873  qs->fdw_tuplestore = NULL;
4874  if (ts)
4875  tuplestore_end(ts);
4876 
4877  /* Release per-table subsidiary storage */
4878  tables = qs->tables;
4879  foreach(lc, tables)
4880  {
4882 
4883  ts = table->old_tuplestore;
4884  table->old_tuplestore = NULL;
4885  if (ts)
4886  tuplestore_end(ts);
4887  ts = table->new_tuplestore;
4888  table->new_tuplestore = NULL;
4889  if (ts)
4890  tuplestore_end(ts);
4891  if (table->storeslot)
4893  }
4894 
4895  /*
4896  * Now free the AfterTriggersTableData structs and list cells. Reset list
4897  * pointer first; if list_free_deep somehow gets an error, better to leak
4898  * that storage than have an infinite loop.
4899  */
4900  qs->tables = NIL;
4901  list_free_deep(tables);
4902 }
4903 
4904 
4905 /* ----------
4906  * AfterTriggerFireDeferred()
4907  *
4908  * Called just before the current transaction is committed. At this
4909  * time we invoke all pending DEFERRED triggers.
4910  *
4911  * It is possible for other modules to queue additional deferred triggers
4912  * during pre-commit processing; therefore xact.c may have to call this
4913  * multiple times.
4914  * ----------
4915  */
4916 void
4918 {
4919  AfterTriggerEventList *events;
4920  bool snap_pushed = false;
4921 
4922  /* Must not be inside a query */
4924 
4925  /*
4926  * If there are any triggers to fire, make sure we have set a snapshot for
4927  * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
4928  * can't assume ActiveSnapshot is valid on entry.)
4929  */
4930  events = &afterTriggers.events;
4931  if (events->head != NULL)
4932  {
4934  snap_pushed = true;
4935  }
4936 
4937  /*
4938  * Run all the remaining triggers. Loop until they are all gone, in case
4939  * some trigger queues more for us to do.
4940  */
4941  while (afterTriggerMarkEvents(events, NULL, false))
4942  {
4943  CommandId firing_id = afterTriggers.firing_counter++;
4944 
4945  if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
4946  break; /* all fired */
4947  }
4948 
4949  /*
4950  * We don't bother freeing the event list, since it will go away anyway
4951  * (and more efficiently than via pfree) in AfterTriggerEndXact.
4952  */
4953 
4954  if (snap_pushed)
4956 }
4957 
4958 
4959 /* ----------
4960  * AfterTriggerEndXact()
4961  *
4962  * The current transaction is finishing.
4963  *
4964  * Any unfired triggers are canceled so we simply throw
4965  * away anything we know.
4966  *
4967  * Note: it is possible for this to be called repeatedly in case of
4968  * error during transaction abort; therefore, do not complain if
4969  * already closed down.
4970  * ----------
4971  */
4972 void
4973 AfterTriggerEndXact(bool isCommit)
4974 {
4975  /*
4976  * Forget the pending-events list.
4977  *
4978  * Since all the info is in TopTransactionContext or children thereof, we
4979  * don't really need to do anything to reclaim memory. However, the
4980  * pending-events list could be large, and so it's useful to discard it as
4981  * soon as possible --- especially if we are aborting because we ran out
4982  * of memory for the list!
4983  */
4985  {
4987  afterTriggers.event_cxt = NULL;
4988  afterTriggers.events.head = NULL;
4989  afterTriggers.events.tail = NULL;
4990  afterTriggers.events.tailfree = NULL;
4991  }
4992 
4993  /*
4994  * Forget any subtransaction state as well. Since this can't be very
4995  * large, we let the eventual reset of TopTransactionContext free the
4996  * memory instead of doing it here.
4997  */
4998  afterTriggers.trans_stack = NULL;
5000 
5001 
5002  /*
5003  * Forget the query stack and constraint-related state information. As
5004  * with the subtransaction state information, we don't bother freeing the
5005  * memory here.
5006  */
5007  afterTriggers.query_stack = NULL;
5009  afterTriggers.state = NULL;
5010 
5011  /* No more afterTriggers manipulation until next transaction starts. */
5013 }
5014 
5015 /*
5016  * AfterTriggerBeginSubXact()
5017  *
5018  * Start a subtransaction.
5019  */
5020 void
5022 {
5023  int my_level = GetCurrentTransactionNestLevel();
5024 
5025  /*
5026  * Allocate more space in the trans_stack if needed. (Note: because the
5027  * minimum nest level of a subtransaction is 2, we waste the first couple
5028  * entries of the array; not worth the notational effort to avoid it.)
5029  */
5030  while (my_level >= afterTriggers.maxtransdepth)
5031  {
5032  if (afterTriggers.maxtransdepth == 0)
5033  {
5034  /* Arbitrarily initialize for max of 8 subtransaction levels */
5037  8 * sizeof(AfterTriggersTransData));
5039  }
5040  else
5041  {
5042  /* repalloc will keep the stack in the same context */
5043  int new_alloc = afterTriggers.maxtransdepth * 2;
5044 
5047  new_alloc * sizeof(AfterTriggersTransData));
5048  afterTriggers.maxtransdepth = new_alloc;
5049  }
5050  }
5051 
5052  /*
5053  * Push the current information into the stack. The SET CONSTRAINTS state
5054  * is not saved until/unless changed. Likewise, we don't make a
5055  * per-subtransaction event context until needed.
5056  */
5057  afterTriggers.trans_stack[my_level].state = NULL;
5061 }
5062 
5063 /*
5064  * AfterTriggerEndSubXact()
5065  *
5066  * The current subtransaction is ending.
5067  */
5068 void
5070 {
5071  int my_level = GetCurrentTransactionNestLevel();
5073  AfterTriggerEvent event;
5074  AfterTriggerEventChunk *chunk;
5075  CommandId subxact_firing_id;
5076 
5077  /*
5078  * Pop the prior state if needed.
5079  */
5080  if (isCommit)
5081  {
5082  Assert(my_level < afterTriggers.maxtransdepth);
5083  /* If we saved a prior state, we don't need it anymore */
5084  state = afterTriggers.trans_stack[my_level].state;
5085  if (state != NULL)
5086  pfree(state);
5087  /* this avoids double pfree if error later: */
5088  afterTriggers.trans_stack[my_level].state = NULL;
5091  }
5092  else
5093  {
5094  /*
5095  * Aborting. It is possible subxact start failed before calling
5096  * AfterTriggerBeginSubXact, in which case we mustn't risk touching
5097  * trans_stack levels that aren't there.
5098  */
5099  if (my_level >= afterTriggers.maxtransdepth)
5100  return;
5101 
5102  /*
5103  * Release query-level storage for queries being aborted, and restore
5104  * query_depth to its pre-subxact value. This assumes that a
5105  * subtransaction will not add events to query levels started in a
5106  * earlier transaction state.
5107  */
5109  {
5113  }
5116 
5117  /*
5118  * Restore the global deferred-event list to its former length,
5119  * discarding any events queued by the subxact.
5120  */
5122  &afterTriggers.trans_stack[my_level].events);
5123 
5124  /*
5125  * Restore the trigger state. If the saved state is NULL, then this
5126  * subxact didn't save it, so it doesn't need restoring.
5127  */
5128  state = afterTriggers.trans_stack[my_level].state;
5129  if (state != NULL)
5130  {
5133  }
5134  /* this avoids double pfree if error later: */
5135  afterTriggers.trans_stack[my_level].state = NULL;
5136 
5137  /*
5138  * Scan for any remaining deferred events that were marked DONE or IN
5139  * PROGRESS by this subxact or a child, and un-mark them. We can
5140  * recognize such events because they have a firing ID greater than or
5141  * equal to the firing_counter value we saved at subtransaction start.
5142  * (This essentially assumes that the current subxact includes all
5143  * subxacts started after it.)
5144  */
5145  subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
5147  {
5148  AfterTriggerShared evtshared = GetTriggerSharedData(event);
5149 
5150  if (event->ate_flags &
5152  {
5153  if (evtshared->ats_firing_id >= subxact_firing_id)
5154  event->ate_flags &=
5156  }
5157  }
5158  }
5159 }
5160 
5161 /* ----------
5162  * AfterTriggerEnlargeQueryState()
5163  *
5164  * Prepare the necessary state so that we can record AFTER trigger events
5165  * queued by a query. It is allowed to have nested queries within a
5166  * (sub)transaction, so we need to have separate state for each query
5167  * nesting level.
5168  * ----------
5169  */
5170 static void
5172 {
5173  int init_depth = afterTriggers.maxquerydepth;
5174 
5176 
5177  if (afterTriggers.maxquerydepth == 0)
5178  {
5179  int new_alloc = Max(afterTriggers.query_depth + 1, 8);
5180 
5183  new_alloc * sizeof(AfterTriggersQueryData));
5184  afterTriggers.maxquerydepth = new_alloc;
5185  }
5186  else
5187  {
5188  /* repalloc will keep the stack in the same context */
5189  int old_alloc = afterTriggers.maxquerydepth;
5190  int new_alloc = Max(afterTriggers.query_depth + 1,
5191  old_alloc * 2);
5192 
5195  new_alloc * sizeof(AfterTriggersQueryData));
5196  afterTriggers.maxquerydepth = new_alloc;
5197  }
5198 
5199  /* Initialize new array entries to empty */
5200  while (init_depth < afterTriggers.maxquerydepth)
5201  {
5203 
5204  qs->events.head = NULL;
5205  qs->events.tail = NULL;
5206  qs->events.tailfree = NULL;
5207  qs->fdw_tuplestore = NULL;
5208  qs->tables = NIL;
5209 
5210  ++init_depth;
5211  }
5212 }
5213 
5214 /*
5215  * Create an empty SetConstraintState with room for numalloc trigstates
5216  */
5217 static SetConstraintState
5219 {
5221 
5222  /* Behave sanely with numalloc == 0 */
5223  if (numalloc <= 0)
5224  numalloc = 1;
5225 
5226  /*
5227  * We assume that zeroing will correctly initialize the state values.
5228  */
5231  offsetof(SetConstraintStateData, trigstates) +
5232  numalloc * sizeof(SetConstraintTriggerData));
5233 
5234  state->numalloc = numalloc;
5235 
5236  return state;
5237 }
5238 
5239 /*
5240  * Copy a SetConstraintState
5241  */
5242 static SetConstraintState
5244 {
5246 
5248 
5249  state->all_isset = origstate->all_isset;
5250  state->all_isdeferred = origstate->all_isdeferred;
5251  state->numstates = origstate->numstates;
5252  memcpy(state->trigstates, origstate->trigstates,
5253  origstate->numstates * sizeof(SetConstraintTriggerData));
5254 
5255  return state;
5256 }
5257 
5258 /*
5259  * Add a per-trigger item to a SetConstraintState. Returns possibly-changed
5260  * pointer to the state object (it will change if we have to repalloc).
5261  */
5262 static SetConstraintState
5264  Oid tgoid, bool tgisdeferred)
5265 {
5266  if (state->numstates >= state->numalloc)
5267  {
5268  int newalloc = state->numalloc * 2;
5269 
5270  newalloc = Max(newalloc, 8); /* in case original has size 0 */
5272  repalloc(state,
5273  offsetof(SetConstraintStateData, trigstates) +
5274  newalloc * sizeof(SetConstraintTriggerData));
5275  state->numalloc = newalloc;
5276  Assert(state->numstates < state->numalloc);
5277  }
5278 
5279  state->trigstates[state->numstates].sct_tgoid = tgoid;
5280  state->trigstates[state->numstates].sct_tgisdeferred = tgisdeferred;
5281  state->numstates++;
5282 
5283  return state;
5284 }
5285 
5286 /* ----------
5287  * AfterTriggerSetState()
5288  *
5289  * Execute the SET CONSTRAINTS ... utility command.
5290  * ----------
5291  */
5292 void
5294 {
5295  int my_level = GetCurrentTransactionNestLevel();
5296 
5297  /* If we haven't already done so, initialize our state. */
5298  if (afterTriggers.state == NULL)
5300 
5301  /*
5302  * If in a subtransaction, and we didn't save the current state already,
5303  * save it so it can be restored if the subtransaction aborts.
5304  */
5305  if (my_level > 1 &&
5306  afterTriggers.trans_stack[my_level].state == NULL)
5307  {
5308  afterTriggers.trans_stack[my_level].state =
5310  }
5311 
5312  /*
5313  * Handle SET CONSTRAINTS ALL ...
5314  */
5315  if (stmt->constraints == NIL)
5316  {
5317  /*
5318  * Forget any previous SET CONSTRAINTS commands in this transaction.
5319  */
5321 
5322  /*
5323  * Set the per-transaction ALL state to known.
5324  */
5325  afterTriggers.state->all_isset = true;
5327  }
5328  else
5329  {
5330  Relation conrel;
5331  Relation tgrel;
5332  List *conoidlist = NIL;
5333  List *tgoidlist = NIL;
5334  ListCell *lc;
5335 
5336  /*
5337  * Handle SET CONSTRAINTS constraint-name [, ...]
5338  *
5339  * First, identify all the named constraints and make a list of their
5340  * OIDs. Since, unlike the SQL spec, we allow multiple constraints of
5341  * the same name within a schema, the specifications are not
5342  * necessarily unique. Our strategy is to target all matching
5343  * constraints within the first search-path schema that has any
5344  * matches, but disregard matches in schemas beyond the first match.
5345  * (This is a bit odd but it's the historical behavior.)
5346  *
5347  * A constraint in a partitioned table may have corresponding
5348  * constraints in the partitions. Grab those too.
5349  */
5350  conrel = table_open(ConstraintRelationId, AccessShareLock);
5351 
5352  foreach(lc, stmt->constraints)
5353  {
5354  RangeVar *constraint = lfirst(lc);
5355  bool found;
5356  List *namespacelist;
5357  ListCell *nslc;
5358 
5359  if (constraint->catalogname)
5360  {
5361  if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
5362  ereport(ERROR,
5363  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5364  errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
5365  constraint->catalogname, constraint->schemaname,
5366  constraint->relname)));
5367  }
5368 
5369  /*
5370  * If we're given the schema name with the constraint, look only
5371  * in that schema. If given a bare constraint name, use the
5372  * search path to find the first matching constraint.
5373  */
5374  if (constraint->schemaname)
5375  {
5376  Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
5377  false);
5378 
5379  namespacelist = list_make1_oid(namespaceId);
5380  }
5381  else
5382  {
5383  namespacelist = fetch_search_path(true);
5384  }
5385 
5386  found = false;
5387  foreach(nslc, namespacelist)
5388  {
5389  Oid namespaceId = lfirst_oid(nslc);
5390  SysScanDesc conscan;
5391  ScanKeyData skey[2];
5392  HeapTuple tup;
5393 
5394  ScanKeyInit(&skey[0],
5395  Anum_pg_constraint_conname,
5396  BTEqualStrategyNumber, F_NAMEEQ,
5397  CStringGetDatum(constraint->relname));
5398  ScanKeyInit(&skey[1],
5399  Anum_pg_constraint_connamespace,
5400  BTEqualStrategyNumber, F_OIDEQ,
5401  ObjectIdGetDatum(namespaceId));
5402 
5403  conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
5404  true, NULL, 2, skey);
5405 
5406  while (HeapTupleIsValid(tup = systable_getnext(conscan)))
5407  {
5409 
5410  if (con->condeferrable)
5411  conoidlist = lappend_oid(conoidlist, con->oid);
5412  else if (stmt->deferred)
5413  ereport(ERROR,
5414  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5415  errmsg("constraint \"%s\" is not deferrable",
5416  constraint->relname)));
5417  found = true;
5418  }
5419 
5420  systable_endscan(conscan);
5421 
5422  /*
5423  * Once we've found a matching constraint we do not search
5424  * later parts of the search path.
5425  */
5426  if (found)
5427  break;
5428  }
5429 
5430  list_free(namespacelist);
5431 
5432  /*
5433  * Not found ?
5434  */
5435  if (!found)
5436  ereport(ERROR,
5437  (errcode(ERRCODE_UNDEFINED_OBJECT),
5438  errmsg("constraint \"%s\" does not exist",
5439  constraint->relname)));
5440  }
5441 
5442  /*
5443  * Scan for any possible descendants of the constraints. We append
5444  * whatever we find to the same list that we're scanning; this has the
5445  * effect that we create new scans for those, too, so if there are
5446  * further descendents, we'll also catch them.
5447  */
5448  foreach(lc, conoidlist)
5449  {
5450  Oid parent = lfirst_oid(lc);
5451  ScanKeyData key;
5452  SysScanDesc scan;
5453  HeapTuple tuple;
5454 
5455  ScanKeyInit(&key,
5456  Anum_pg_constraint_conparentid,
5457  BTEqualStrategyNumber, F_OIDEQ,
5458  ObjectIdGetDatum(parent));
5459 
5460  scan = systable_beginscan(conrel, ConstraintParentIndexId, true, NULL, 1, &key);
5461 
5462  while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5463  {
5465 
5466  conoidlist = lappend_oid(conoidlist, con->oid);
5467  }
5468 
5469  systable_endscan(scan);
5470  }
5471 
5472  table_close(conrel, AccessShareLock);
5473 
5474  /*
5475  * Now, locate the trigger(s) implementing each of these constraints,
5476  * and make a list of their OIDs.
5477  */
5478  tgrel = table_open(TriggerRelationId, AccessShareLock);
5479 
5480  foreach(lc, conoidlist)
5481  {
5482  Oid conoid = lfirst_oid(lc);
5483  ScanKeyData skey;
5484  SysScanDesc tgscan;
5485  HeapTuple htup;
5486 
5487  ScanKeyInit(&skey,
5488  Anum_pg_trigger_tgconstraint,
5489  BTEqualStrategyNumber, F_OIDEQ,
5490  ObjectIdGetDatum(conoid));
5491 
5492  tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
5493  NULL, 1, &skey);
5494 
5495  while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
5496  {
5497  Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
5498 
5499  /*
5500  * Silently skip triggers that are marked as non-deferrable in
5501  * pg_trigger. This is not an error condition, since a
5502  * deferrable RI constraint may have some non-deferrable
5503  * actions.
5504  */
5505  if (pg_trigger->tgdeferrable)
5506  tgoidlist = lappend_oid(tgoidlist, pg_trigger->oid);
5507  }
5508 
5509  systable_endscan(tgscan);
5510  }
5511 
5512  table_close(tgrel, AccessShareLock);
5513 
5514  /*
5515  * Now we can set the trigger states of individual triggers for this
5516  * xact.
5517  */
5518  foreach(lc, tgoidlist)
5519  {
5520  Oid tgoid = lfirst_oid(lc);
5522  bool found = false;
5523  int i;
5524 
5525  for (i = 0; i < state->numstates; i++)
5526  {
5527  if (state->trigstates[i].sct_tgoid == tgoid)
5528  {
5529  state->trigstates[i].sct_tgisdeferred = stmt->deferred;
5530  found = true;
5531  break;
5532  }
5533  }
5534  if (!found)
5535  {
5537  SetConstraintStateAddItem(state, tgoid, stmt->deferred);
5538  }
5539  }
5540  }
5541 
5542  /*
5543  * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
5544  * checks against that constraint must be made when the SET CONSTRAINTS
5545  * command is executed -- i.e. the effects of the SET CONSTRAINTS command
5546  * apply retroactively. We've updated the constraints state, so scan the
5547  * list of previously deferred events to fire any that have now become
5548  * immediate.
5549  *
5550  * Obviously, if this was SET ... DEFERRED then it can't have converted
5551  * any unfired events to immediate, so we need do nothing in that case.
5552  */
5553  if (!stmt->deferred)
5554  {
5556  bool snapshot_set = false;
5557 
5558  while (afterTriggerMarkEvents(events, NULL, true))
5559  {
5560  CommandId firing_id = afterTriggers.firing_counter++;
5561 
5562  /*
5563  * Make sure a snapshot has been established in case trigger
5564  * functions need one. Note that we avoid setting a snapshot if
5565  * we don't find at least one trigger that has to be fired now.
5566  * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
5567  * ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
5568  * at the start of a transaction it's not possible for any trigger
5569  * events to be queued yet.)
5570  */
5571  if (!snapshot_set)
5572  {
5574  snapshot_set = true;
5575  }
5576 
5577  /*
5578  * We can delete fired events if we are at top transaction level,
5579  * but we'd better not if inside a subtransaction, since the
5580  * subtransaction could later get rolled back.
5581  */
5582  if (afterTriggerInvokeEvents(events, firing_id, NULL,
5583  !IsSubTransaction()))
5584  break; /* all fired */
5585  }
5586 
5587  if (snapshot_set)
5588