LCOV - code coverage report
Current view: top level - src/backend/commands - trigger.c (source / functions) Hit Total Coverage
Test: PostgreSQL 16beta1 Lines: 1875 2002 93.7 %
Date: 2023-05-30 18:12:27 Functions: 67 68 98.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * trigger.c
       4             :  *    PostgreSQL TRIGGERs support code.
       5             :  *
       6             :  * Portions Copyright (c) 1996-2023, 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/guc_hooks.h"
      59             : #include "utils/inval.h"
      60             : #include "utils/lsyscache.h"
      61             : #include "utils/memutils.h"
      62             : #include "utils/plancache.h"
      63             : #include "utils/rel.h"
      64             : #include "utils/snapmgr.h"
      65             : #include "utils/syscache.h"
      66             : #include "utils/tuplestore.h"
      67             : 
      68             : 
      69             : /* GUC variables */
      70             : int         SessionReplicationRole = SESSION_REPLICATION_ROLE_ORIGIN;
      71             : 
      72             : /* How many levels deep into trigger execution are we? */
      73             : static int  MyTriggerDepth = 0;
      74             : 
      75             : /* Local function prototypes */
      76             : static void renametrig_internal(Relation tgrel, Relation targetrel,
      77             :                                 HeapTuple trigtup, const char *newname,
      78             :                                 const char *expected_name);
      79             : static void renametrig_partition(Relation tgrel, Oid partitionId,
      80             :                                  Oid parentTriggerOid, const char *newname,
      81             :                                  const char *expected_name);
      82             : static void SetTriggerFlags(TriggerDesc *trigdesc, Trigger *trigger);
      83             : static bool GetTupleForTrigger(EState *estate,
      84             :                                EPQState *epqstate,
      85             :                                ResultRelInfo *relinfo,
      86             :                                ItemPointer tid,
      87             :                                LockTupleMode lockmode,
      88             :                                TupleTableSlot *oldslot,
      89             :                                TupleTableSlot **epqslot,
      90             :                                TM_Result *tmresultp,
      91             :                                TM_FailureData *tmfdp);
      92             : static bool TriggerEnabled(EState *estate, ResultRelInfo *relinfo,
      93             :                            Trigger *trigger, TriggerEvent event,
      94             :                            Bitmapset *modifiedCols,
      95             :                            TupleTableSlot *oldslot, TupleTableSlot *newslot);
      96             : static HeapTuple ExecCallTriggerFunc(TriggerData *trigdata,
      97             :                                      int tgindx,
      98             :                                      FmgrInfo *finfo,
      99             :                                      Instrumentation *instr,
     100             :                                      MemoryContext per_tuple_context);
     101             : static void AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
     102             :                                   ResultRelInfo *src_partinfo,
     103             :                                   ResultRelInfo *dst_partinfo,
     104             :                                   int event, bool row_trigger,
     105             :                                   TupleTableSlot *oldslot, TupleTableSlot *newslot,
     106             :                                   List *recheckIndexes, Bitmapset *modifiedCols,
     107             :                                   TransitionCaptureState *transition_capture,
     108             :                                   bool is_crosspart_update);
     109             : static void AfterTriggerEnlargeQueryState(void);
     110             : static bool before_stmt_triggers_fired(Oid relid, CmdType cmdType);
     111             : 
     112             : 
     113             : /*
     114             :  * Create a trigger.  Returns the address of the created trigger.
     115             :  *
     116             :  * queryString is the source text of the CREATE TRIGGER command.
     117             :  * This must be supplied if a whenClause is specified, else it can be NULL.
     118             :  *
     119             :  * relOid, if nonzero, is the relation on which the trigger should be
     120             :  * created.  If zero, the name provided in the statement will be looked up.
     121             :  *
     122             :  * refRelOid, if nonzero, is the relation to which the constraint trigger
     123             :  * refers.  If zero, the constraint relation name provided in the statement
     124             :  * will be looked up as needed.
     125             :  *
     126             :  * constraintOid, if nonzero, says that this trigger is being created
     127             :  * internally to implement that constraint.  A suitable pg_depend entry will
     128             :  * be made to link the trigger to that constraint.  constraintOid is zero when
     129             :  * executing a user-entered CREATE TRIGGER command.  (For CREATE CONSTRAINT
     130             :  * TRIGGER, we build a pg_constraint entry internally.)
     131             :  *
     132             :  * indexOid, if nonzero, is the OID of an index associated with the constraint.
     133             :  * We do nothing with this except store it into pg_trigger.tgconstrindid;
     134             :  * but when creating a trigger for a deferrable unique constraint on a
     135             :  * partitioned table, its children are looked up.  Note we don't cope with
     136             :  * invalid indexes in that case.
     137             :  *
     138             :  * funcoid, if nonzero, is the OID of the function to invoke.  When this is
     139             :  * given, stmt->funcname is ignored.
     140             :  *
     141             :  * parentTriggerOid, if nonzero, is a trigger that begets this one; so that
     142             :  * if that trigger is dropped, this one should be too.  There are two cases
     143             :  * when a nonzero value is passed for this: 1) when this function recurses to
     144             :  * create the trigger on partitions, 2) when creating child foreign key
     145             :  * triggers; see CreateFKCheckTrigger() and createForeignKeyActionTriggers().
     146             :  *
     147             :  * If whenClause is passed, it is an already-transformed expression for
     148             :  * WHEN.  In this case, we ignore any that may come in stmt->whenClause.
     149             :  *
     150             :  * If isInternal is true then this is an internally-generated trigger.
     151             :  * This argument sets the tgisinternal field of the pg_trigger entry, and
     152             :  * if true causes us to modify the given trigger name to ensure uniqueness.
     153             :  *
     154             :  * When isInternal is not true we require ACL_TRIGGER permissions on the
     155             :  * relation, as well as ACL_EXECUTE on the trigger function.  For internal
     156             :  * triggers the caller must apply any required permission checks.
     157             :  *
     158             :  * When called on partitioned tables, this function recurses to create the
     159             :  * trigger on all the partitions, except if isInternal is true, in which
     160             :  * case caller is expected to execute recursion on its own.  in_partition
     161             :  * indicates such a recursive call; outside callers should pass "false"
     162             :  * (but see CloneRowTriggersToPartition).
     163             :  */
     164             : ObjectAddress
     165       12936 : CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
     166             :               Oid relOid, Oid refRelOid, Oid constraintOid, Oid indexOid,
     167             :               Oid funcoid, Oid parentTriggerOid, Node *whenClause,
     168             :               bool isInternal, bool in_partition)
     169             : {
     170             :     return
     171       12936 :         CreateTriggerFiringOn(stmt, queryString, relOid, refRelOid,
     172             :                               constraintOid, indexOid, funcoid,
     173             :                               parentTriggerOid, whenClause, isInternal,
     174             :                               in_partition, TRIGGER_FIRES_ON_ORIGIN);
     175             : }
     176             : 
     177             : /*
     178             :  * Like the above; additionally the firing condition
     179             :  * (always/origin/replica/disabled) can be specified.
     180             :  */
     181             : ObjectAddress
     182       13680 : CreateTriggerFiringOn(CreateTrigStmt *stmt, const char *queryString,
     183             :                       Oid relOid, Oid refRelOid, Oid constraintOid,
     184             :                       Oid indexOid, Oid funcoid, Oid parentTriggerOid,
     185             :                       Node *whenClause, bool isInternal, bool in_partition,
     186             :                       char trigger_fires_when)
     187             : {
     188             :     int16       tgtype;
     189             :     int         ncolumns;
     190             :     int16      *columns;
     191             :     int2vector *tgattr;
     192             :     List       *whenRtable;
     193             :     char       *qual;
     194             :     Datum       values[Natts_pg_trigger];
     195             :     bool        nulls[Natts_pg_trigger];
     196             :     Relation    rel;
     197             :     AclResult   aclresult;
     198             :     Relation    tgrel;
     199             :     Relation    pgrel;
     200       13680 :     HeapTuple   tuple = NULL;
     201             :     Oid         funcrettype;
     202       13680 :     Oid         trigoid = InvalidOid;
     203             :     char        internaltrigname[NAMEDATALEN];
     204             :     char       *trigname;
     205       13680 :     Oid         constrrelid = InvalidOid;
     206             :     ObjectAddress myself,
     207             :                 referenced;
     208       13680 :     char       *oldtablename = NULL;
     209       13680 :     char       *newtablename = NULL;
     210             :     bool        partition_recurse;
     211       13680 :     bool        trigger_exists = false;
     212       13680 :     Oid         existing_constraint_oid = InvalidOid;
     213       13680 :     bool        existing_isInternal = false;
     214       13680 :     bool        existing_isClone = false;
     215             : 
     216       13680 :     if (OidIsValid(relOid))
     217       10648 :         rel = table_open(relOid, ShareRowExclusiveLock);
     218             :     else
     219        3032 :         rel = table_openrv(stmt->relation, ShareRowExclusiveLock);
     220             : 
     221             :     /*
     222             :      * Triggers must be on tables or views, and there are additional
     223             :      * relation-type-specific restrictions.
     224             :      */
     225       13680 :     if (rel->rd_rel->relkind == RELKIND_RELATION)
     226             :     {
     227             :         /* Tables can't have INSTEAD OF triggers */
     228       11264 :         if (stmt->timing != TRIGGER_TYPE_BEFORE &&
     229       10048 :             stmt->timing != TRIGGER_TYPE_AFTER)
     230          18 :             ereport(ERROR,
     231             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     232             :                      errmsg("\"%s\" is a table",
     233             :                             RelationGetRelationName(rel)),
     234             :                      errdetail("Tables cannot have INSTEAD OF triggers.")));
     235             :     }
     236        2416 :     else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     237             :     {
     238             :         /* Partitioned tables can't have INSTEAD OF triggers */
     239        2114 :         if (stmt->timing != TRIGGER_TYPE_BEFORE &&
     240        2036 :             stmt->timing != TRIGGER_TYPE_AFTER)
     241           6 :             ereport(ERROR,
     242             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     243             :                      errmsg("\"%s\" is a table",
     244             :                             RelationGetRelationName(rel)),
     245             :                      errdetail("Tables cannot have INSTEAD OF triggers.")));
     246             : 
     247             :         /*
     248             :          * FOR EACH ROW triggers have further restrictions
     249             :          */
     250        2108 :         if (stmt->row)
     251             :         {
     252             :             /*
     253             :              * Disallow use of transition tables.
     254             :              *
     255             :              * Note that we have another restriction about transition tables
     256             :              * in partitions; search for 'has_superclass' below for an
     257             :              * explanation.  The check here is just to protect from the fact
     258             :              * that if we allowed it here, the creation would succeed for a
     259             :              * partitioned table with no partitions, but would be blocked by
     260             :              * the other restriction when the first partition was created,
     261             :              * which is very unfriendly behavior.
     262             :              */
     263        1914 :             if (stmt->transitionRels != NIL)
     264           6 :                 ereport(ERROR,
     265             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     266             :                          errmsg("\"%s\" is a partitioned table",
     267             :                                 RelationGetRelationName(rel)),
     268             :                          errdetail("ROW triggers with transition tables are not supported on partitioned tables.")));
     269             :         }
     270             :     }
     271         302 :     else if (rel->rd_rel->relkind == RELKIND_VIEW)
     272             :     {
     273             :         /*
     274             :          * Views can have INSTEAD OF triggers (which we check below are
     275             :          * row-level), or statement-level BEFORE/AFTER triggers.
     276             :          */
     277         198 :         if (stmt->timing != TRIGGER_TYPE_INSTEAD && stmt->row)
     278          36 :             ereport(ERROR,
     279             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     280             :                      errmsg("\"%s\" is a view",
     281             :                             RelationGetRelationName(rel)),
     282             :                      errdetail("Views cannot have row-level BEFORE or AFTER triggers.")));
     283             :         /* Disallow TRUNCATE triggers on VIEWs */
     284         162 :         if (TRIGGER_FOR_TRUNCATE(stmt->events))
     285          12 :             ereport(ERROR,
     286             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     287             :                      errmsg("\"%s\" is a view",
     288             :                             RelationGetRelationName(rel)),
     289             :                      errdetail("Views cannot have TRUNCATE triggers.")));
     290             :     }
     291         104 :     else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
     292             :     {
     293         104 :         if (stmt->timing != TRIGGER_TYPE_BEFORE &&
     294          54 :             stmt->timing != TRIGGER_TYPE_AFTER)
     295           0 :             ereport(ERROR,
     296             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     297             :                      errmsg("\"%s\" is a foreign table",
     298             :                             RelationGetRelationName(rel)),
     299             :                      errdetail("Foreign tables cannot have INSTEAD OF 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         104 :         if (stmt->isconstraint)
     307           6 :             ereport(ERROR,
     308             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     309             :                      errmsg("\"%s\" is a foreign table",
     310             :                             RelationGetRelationName(rel)),
     311             :                      errdetail("Foreign tables cannot have constraint triggers.")));
     312             :     }
     313             :     else
     314           0 :         ereport(ERROR,
     315             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     316             :                  errmsg("relation \"%s\" cannot have triggers",
     317             :                         RelationGetRelationName(rel)),
     318             :                  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
     319             : 
     320       13596 :     if (!allowSystemTableMods && IsSystemRelation(rel))
     321           2 :         ereport(ERROR,
     322             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     323             :                  errmsg("permission denied: \"%s\" is a system catalog",
     324             :                         RelationGetRelationName(rel))));
     325             : 
     326       13594 :     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       10054 :         if (OidIsValid(refRelOid))
     336             :         {
     337        9842 :             LockRelationOid(refRelOid, AccessShareLock);
     338        9842 :             constrrelid = refRelOid;
     339             :         }
     340         212 :         else if (stmt->constrrel != NULL)
     341          24 :             constrrelid = RangeVarGetRelid(stmt->constrrel, AccessShareLock,
     342             :                                            false);
     343             :     }
     344             : 
     345             :     /* permission checks */
     346       13594 :     if (!isInternal)
     347             :     {
     348        3690 :         aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
     349             :                                       ACL_TRIGGER);
     350        3690 :         if (aclresult != ACLCHECK_OK)
     351           0 :             aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
     352           0 :                            RelationGetRelationName(rel));
     353             : 
     354        3690 :         if (OidIsValid(constrrelid))
     355             :         {
     356          42 :             aclresult = pg_class_aclcheck(constrrelid, GetUserId(),
     357             :                                           ACL_TRIGGER);
     358          42 :             if (aclresult != ACLCHECK_OK)
     359           0 :                 aclcheck_error(aclresult, get_relkind_objtype(get_rel_relkind(constrrelid)),
     360           0 :                                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       16332 :     partition_recurse = !isInternal && stmt->row &&
     371        2738 :         rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
     372       13594 :     if (partition_recurse)
     373         374 :         list_free(find_all_inheritors(RelationGetRelid(rel),
     374             :                                       ShareRowExclusiveLock, NULL));
     375             : 
     376             :     /* Compute tgtype */
     377       13594 :     TRIGGER_CLEAR_TYPE(tgtype);
     378       13594 :     if (stmt->row)
     379       12642 :         TRIGGER_SETT_ROW(tgtype);
     380       13594 :     tgtype |= stmt->timing;
     381       13594 :     tgtype |= stmt->events;
     382             : 
     383             :     /* Disallow ROW-level TRUNCATE triggers */
     384       13594 :     if (TRIGGER_FOR_ROW(tgtype) && TRIGGER_FOR_TRUNCATE(tgtype))
     385           0 :         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       13594 :     if (TRIGGER_FOR_INSTEAD(tgtype))
     391             :     {
     392         108 :         if (!TRIGGER_FOR_ROW(tgtype))
     393           6 :             ereport(ERROR,
     394             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     395             :                      errmsg("INSTEAD OF triggers must be FOR EACH ROW")));
     396         102 :         if (stmt->whenClause)
     397           6 :             ereport(ERROR,
     398             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     399             :                      errmsg("INSTEAD OF triggers cannot have WHEN conditions")));
     400          96 :         if (stmt->columns != NIL)
     401           6 :             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       13576 :     if (stmt->transitionRels != NIL)
     421             :     {
     422         418 :         List       *varList = stmt->transitionRels;
     423             :         ListCell   *lc;
     424             : 
     425         914 :         foreach(lc, varList)
     426             :         {
     427         544 :             TriggerTransition *tt = lfirst_node(TriggerTransition, lc);
     428             : 
     429         544 :             if (!(tt->isTable))
     430           0 :                 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         544 :             if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
     442           6 :                 ereport(ERROR,
     443             :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     444             :                          errmsg("\"%s\" is a foreign table",
     445             :                                 RelationGetRelationName(rel)),
     446             :                          errdetail("Triggers on foreign tables cannot have transition tables.")));
     447             : 
     448         538 :             if (rel->rd_rel->relkind == RELKIND_VIEW)
     449           6 :                 ereport(ERROR,
     450             :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     451             :                          errmsg("\"%s\" is a view",
     452             :                                 RelationGetRelationName(rel)),
     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         532 :             if (TRIGGER_FOR_ROW(tgtype) && has_superclass(rel->rd_id))
     464             :             {
     465             :                 /* Use appropriate error message. */
     466          12 :                 if (rel->rd_rel->relispartition)
     467           6 :                     ereport(ERROR,
     468             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     469             :                              errmsg("ROW triggers with transition tables are not supported on partitions")));
     470             :                 else
     471           6 :                     ereport(ERROR,
     472             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     473             :                              errmsg("ROW triggers with transition tables are not supported on inheritance children")));
     474             :             }
     475             : 
     476         520 :             if (stmt->timing != TRIGGER_TYPE_AFTER)
     477           0 :                 ereport(ERROR,
     478             :                         (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     479             :                          errmsg("transition table name can only be specified for an AFTER trigger")));
     480             : 
     481         520 :             if (TRIGGER_FOR_TRUNCATE(tgtype))
     482           6 :                 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         514 :             if (((TRIGGER_FOR_INSERT(tgtype) ? 1 : 0) +
     497         514 :                  (TRIGGER_FOR_UPDATE(tgtype) ? 1 : 0) +
     498         514 :                  (TRIGGER_FOR_DELETE(tgtype) ? 1 : 0)) != 1)
     499           6 :                 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         508 :             if (stmt->columns != NIL)
     510           6 :                 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         502 :             if (tt->isNew)
     524             :             {
     525         264 :                 if (!(TRIGGER_FOR_INSERT(tgtype) ||
     526         146 :                       TRIGGER_FOR_UPDATE(tgtype)))
     527           0 :                     ereport(ERROR,
     528             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     529             :                              errmsg("NEW TABLE can only be specified for an INSERT or UPDATE trigger")));
     530             : 
     531         264 :                 if (newtablename != NULL)
     532           0 :                     ereport(ERROR,
     533             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     534             :                              errmsg("NEW TABLE cannot be specified multiple times")));
     535             : 
     536         264 :                 newtablename = tt->name;
     537             :             }
     538             :             else
     539             :             {
     540         238 :                 if (!(TRIGGER_FOR_DELETE(tgtype) ||
     541         140 :                       TRIGGER_FOR_UPDATE(tgtype)))
     542           6 :                     ereport(ERROR,
     543             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     544             :                              errmsg("OLD TABLE can only be specified for a DELETE or UPDATE trigger")));
     545             : 
     546         232 :                 if (oldtablename != NULL)
     547           0 :                     ereport(ERROR,
     548             :                             (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
     549             :                              errmsg("OLD TABLE cannot be specified multiple times")));
     550             : 
     551         232 :                 oldtablename = tt->name;
     552             :             }
     553             :         }
     554             : 
     555         370 :         if (newtablename != NULL && oldtablename != NULL &&
     556         126 :             strcmp(newtablename, oldtablename) == 0)
     557           0 :             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       13528 :     if (!whenClause && stmt->whenClause)
     571         110 :     {
     572             :         ParseState *pstate;
     573             :         ParseNamespaceItem *nsitem;
     574             :         List       *varList;
     575             :         ListCell   *lc;
     576             : 
     577             :         /* Set up a pstate to parse with */
     578         146 :         pstate = make_parsestate(NULL);
     579         146 :         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         146 :         nsitem = addRangeTableEntryForRelation(pstate, rel,
     587             :                                                AccessShareLock,
     588             :                                                makeAlias("old", NIL),
     589             :                                                false, false);
     590         146 :         addNSItemToQuery(pstate, nsitem, false, true, true);
     591         146 :         nsitem = addRangeTableEntryForRelation(pstate, rel,
     592             :                                                AccessShareLock,
     593             :                                                makeAlias("new", NIL),
     594             :                                                false, false);
     595         146 :         addNSItemToQuery(pstate, nsitem, false, true, true);
     596             : 
     597             :         /* Transform expression.  Copy to be sure we don't modify original */
     598         146 :         whenClause = transformWhereClause(pstate,
     599         146 :                                           copyObject(stmt->whenClause),
     600             :                                           EXPR_KIND_TRIGGER_WHEN,
     601             :                                           "WHEN");
     602             :         /* we have to fix its collations too */
     603         146 :         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         146 :         varList = pull_var_clause(whenClause, 0);
     613         300 :         foreach(lc, varList)
     614             :         {
     615         190 :             Var        *var = (Var *) lfirst(lc);
     616             : 
     617         190 :             switch (var->varno)
     618             :             {
     619          74 :                 case PRS2_OLD_VARNO:
     620          74 :                     if (!TRIGGER_FOR_ROW(tgtype))
     621           6 :                         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          68 :                     if (TRIGGER_FOR_INSERT(tgtype))
     626           6 :                         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          62 :                     break;
     632         116 :                 case PRS2_NEW_VARNO:
     633         116 :                     if (!TRIGGER_FOR_ROW(tgtype))
     634           0 :                         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         116 :                     if (TRIGGER_FOR_DELETE(tgtype))
     639           6 :                         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         110 :                     if (var->varattno < 0 && TRIGGER_FOR_BEFORE(tgtype))
     644           6 :                         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         104 :                     if (TRIGGER_FOR_BEFORE(tgtype) &&
     649          34 :                         var->varattno == 0 &&
     650          12 :                         RelationGetDescr(rel)->constr &&
     651           6 :                         RelationGetDescr(rel)->constr->has_generated_stored)
     652           6 :                         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          98 :                     if (TRIGGER_FOR_BEFORE(tgtype) &&
     658          28 :                         var->varattno > 0 &&
     659          22 :                         TupleDescAttr(RelationGetDescr(rel), var->varattno - 1)->attgenerated)
     660           6 :                         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          92 :                     break;
     667           0 :                 default:
     668             :                     /* can't happen without add_missing_from, so just elog */
     669           0 :                     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         110 :         whenRtable = pstate->p_rtable;
     676             : 
     677         110 :         qual = nodeToString(whenClause);
     678             : 
     679         110 :         free_parsestate(pstate);
     680             :     }
     681       13382 :     else if (!whenClause)
     682             :     {
     683       13340 :         whenClause = NULL;
     684       13340 :         whenRtable = NIL;
     685       13340 :         qual = NULL;
     686             :     }
     687             :     else
     688             :     {
     689          42 :         qual = nodeToString(whenClause);
     690          42 :         whenRtable = NIL;
     691             :     }
     692             : 
     693             :     /*
     694             :      * Find and validate the trigger function.
     695             :      */
     696       13492 :     if (!OidIsValid(funcoid))
     697       12748 :         funcoid = LookupFuncName(stmt->funcname, 0, NULL, false);
     698       13492 :     if (!isInternal)
     699             :     {
     700        3588 :         aclresult = object_aclcheck(ProcedureRelationId, funcoid, GetUserId(), ACL_EXECUTE);
     701        3588 :         if (aclresult != ACLCHECK_OK)
     702           0 :             aclcheck_error(aclresult, OBJECT_FUNCTION,
     703           0 :                            NameListToString(stmt->funcname));
     704             :     }
     705       13492 :     funcrettype = get_func_rettype(funcoid);
     706       13492 :     if (funcrettype != TRIGGEROID)
     707           0 :         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       13492 :     tgrel = table_open(TriggerRelationId, RowExclusiveLock);
     721       13492 :     if (!isInternal)
     722             :     {
     723             :         ScanKeyData skeys[2];
     724             :         SysScanDesc tgscan;
     725             : 
     726        3588 :         ScanKeyInit(&skeys[0],
     727             :                     Anum_pg_trigger_tgrelid,
     728             :                     BTEqualStrategyNumber, F_OIDEQ,
     729             :                     ObjectIdGetDatum(RelationGetRelid(rel)));
     730             : 
     731        3588 :         ScanKeyInit(&skeys[1],
     732             :                     Anum_pg_trigger_tgname,
     733             :                     BTEqualStrategyNumber, F_NAMEEQ,
     734        3588 :                     CStringGetDatum(stmt->trigname));
     735             : 
     736        3588 :         tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
     737             :                                     NULL, 2, skeys);
     738             : 
     739             :         /* There should be at most one matching tuple */
     740        3588 :         if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
     741             :         {
     742         102 :             Form_pg_trigger oldtrigger = (Form_pg_trigger) GETSTRUCT(tuple);
     743             : 
     744         102 :             trigoid = oldtrigger->oid;
     745         102 :             existing_constraint_oid = oldtrigger->tgconstraint;
     746         102 :             existing_isInternal = oldtrigger->tgisinternal;
     747         102 :             existing_isClone = OidIsValid(oldtrigger->tgparentid);
     748         102 :             trigger_exists = true;
     749             :             /* copy the tuple to use in CatalogTupleUpdate() */
     750         102 :             tuple = heap_copytuple(tuple);
     751             :         }
     752        3588 :         systable_endscan(tgscan);
     753             :     }
     754             : 
     755       13492 :     if (!trigger_exists)
     756             :     {
     757             :         /* Generate the OID for the new trigger. */
     758       13390 :         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         102 :         if (!stmt->replace)
     768          18 :             ereport(ERROR,
     769             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
     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          84 :         if ((existing_isInternal || existing_isClone) &&
     780          60 :             !isInternal && !in_partition)
     781           6 :             ereport(ERROR,
     782             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
     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          78 :         if (OidIsValid(existing_constraint_oid))
     800           0 :             ereport(ERROR,
     801             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
     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       13468 :     if (stmt->isconstraint && !OidIsValid(constraintOid))
     811             :     {
     812             :         /* Internal callers should have made their own constraints */
     813             :         Assert(!isInternal);
     814         150 :         constraintOid = CreateConstraintEntry(stmt->trigname,
     815         150 :                                               RelationGetNamespace(rel),
     816             :                                               CONSTRAINT_TRIGGER,
     817         150 :                                               stmt->deferrable,
     818         150 :                                               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       13468 :     if (isInternal)
     853             :     {
     854        9904 :         snprintf(internaltrigname, sizeof(internaltrigname),
     855             :                  "%s_%u", stmt->trigname, trigoid);
     856        9904 :         trigname = internaltrigname;
     857             :     }
     858             :     else
     859             :     {
     860             :         /* user-defined trigger; use the specified trigger name as-is */
     861        3564 :         trigname = stmt->trigname;
     862             :     }
     863             : 
     864             :     /*
     865             :      * Build the new pg_trigger tuple.
     866             :      */
     867       13468 :     memset(nulls, false, sizeof(nulls));
     868             : 
     869       13468 :     values[Anum_pg_trigger_oid - 1] = ObjectIdGetDatum(trigoid);
     870       13468 :     values[Anum_pg_trigger_tgrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
     871       13468 :     values[Anum_pg_trigger_tgparentid - 1] = ObjectIdGetDatum(parentTriggerOid);
     872       13468 :     values[Anum_pg_trigger_tgname - 1] = DirectFunctionCall1(namein,
     873             :                                                              CStringGetDatum(trigname));
     874       13468 :     values[Anum_pg_trigger_tgfoid - 1] = ObjectIdGetDatum(funcoid);
     875       13468 :     values[Anum_pg_trigger_tgtype - 1] = Int16GetDatum(tgtype);
     876       13468 :     values[Anum_pg_trigger_tgenabled - 1] = trigger_fires_when;
     877       13468 :     values[Anum_pg_trigger_tgisinternal - 1] = BoolGetDatum(isInternal);
     878       13468 :     values[Anum_pg_trigger_tgconstrrelid - 1] = ObjectIdGetDatum(constrrelid);
     879       13468 :     values[Anum_pg_trigger_tgconstrindid - 1] = ObjectIdGetDatum(indexOid);
     880       13468 :     values[Anum_pg_trigger_tgconstraint - 1] = ObjectIdGetDatum(constraintOid);
     881       13468 :     values[Anum_pg_trigger_tgdeferrable - 1] = BoolGetDatum(stmt->deferrable);
     882       13468 :     values[Anum_pg_trigger_tginitdeferred - 1] = BoolGetDatum(stmt->initdeferred);
     883             : 
     884       13468 :     if (stmt->args)
     885             :     {
     886             :         ListCell   *le;
     887             :         char       *args;
     888         484 :         int16       nargs = list_length(stmt->args);
     889         484 :         int         len = 0;
     890             : 
     891        1250 :         foreach(le, stmt->args)
     892             :         {
     893         766 :             char       *ar = strVal(lfirst(le));
     894             : 
     895         766 :             len += strlen(ar) + 4;
     896        6242 :             for (; *ar; ar++)
     897             :             {
     898        5476 :                 if (*ar == '\\')
     899           0 :                     len++;
     900             :             }
     901             :         }
     902         484 :         args = (char *) palloc(len + 1);
     903         484 :         args[0] = '\0';
     904        1250 :         foreach(le, stmt->args)
     905             :         {
     906         766 :             char       *s = strVal(lfirst(le));
     907         766 :             char       *d = args + strlen(args);
     908             : 
     909        6242 :             while (*s)
     910             :             {
     911        5476 :                 if (*s == '\\')
     912           0 :                     *d++ = '\\';
     913        5476 :                 *d++ = *s++;
     914             :             }
     915         766 :             strcpy(d, "\\000");
     916             :         }
     917         484 :         values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(nargs);
     918         484 :         values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
     919             :                                                                  CStringGetDatum(args));
     920             :     }
     921             :     else
     922             :     {
     923       12984 :         values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(0);
     924       12984 :         values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
     925             :                                                                  CStringGetDatum(""));
     926             :     }
     927             : 
     928             :     /* build column number array if it's a column-specific trigger */
     929       13468 :     ncolumns = list_length(stmt->columns);
     930       13468 :     if (ncolumns == 0)
     931       13368 :         columns = NULL;
     932             :     else
     933             :     {
     934             :         ListCell   *cell;
     935         100 :         int         i = 0;
     936             : 
     937         100 :         columns = (int16 *) palloc(ncolumns * sizeof(int16));
     938         208 :         foreach(cell, stmt->columns)
     939             :         {
     940         114 :             char       *name = strVal(lfirst(cell));
     941             :             int16       attnum;
     942             :             int         j;
     943             : 
     944             :             /* Lookup column name.  System columns are not allowed */
     945         114 :             attnum = attnameAttNum(rel, name, false);
     946         114 :             if (attnum == InvalidAttrNumber)
     947           0 :                 ereport(ERROR,
     948             :                         (errcode(ERRCODE_UNDEFINED_COLUMN),
     949             :                          errmsg("column \"%s\" of relation \"%s\" does not exist",
     950             :                                 name, RelationGetRelationName(rel))));
     951             : 
     952             :             /* Check for duplicates */
     953         122 :             for (j = i - 1; j >= 0; j--)
     954             :             {
     955          14 :                 if (columns[j] == attnum)
     956           6 :                     ereport(ERROR,
     957             :                             (errcode(ERRCODE_DUPLICATE_COLUMN),
     958             :                              errmsg("column \"%s\" specified more than once",
     959             :                                     name)));
     960             :             }
     961             : 
     962         108 :             columns[i++] = attnum;
     963             :         }
     964             :     }
     965       13462 :     tgattr = buildint2vector(columns, ncolumns);
     966       13462 :     values[Anum_pg_trigger_tgattr - 1] = PointerGetDatum(tgattr);
     967             : 
     968             :     /* set tgqual if trigger has WHEN clause */
     969       13462 :     if (qual)
     970         152 :         values[Anum_pg_trigger_tgqual - 1] = CStringGetTextDatum(qual);
     971             :     else
     972       13310 :         nulls[Anum_pg_trigger_tgqual - 1] = true;
     973             : 
     974       13462 :     if (oldtablename)
     975         232 :         values[Anum_pg_trigger_tgoldtable - 1] = DirectFunctionCall1(namein,
     976             :                                                                      CStringGetDatum(oldtablename));
     977             :     else
     978       13230 :         nulls[Anum_pg_trigger_tgoldtable - 1] = true;
     979       13462 :     if (newtablename)
     980         264 :         values[Anum_pg_trigger_tgnewtable - 1] = DirectFunctionCall1(namein,
     981             :                                                                      CStringGetDatum(newtablename));
     982             :     else
     983       13198 :         nulls[Anum_pg_trigger_tgnewtable - 1] = true;
     984             : 
     985             :     /*
     986             :      * Insert or replace tuple in pg_trigger.
     987             :      */
     988       13462 :     if (!trigger_exists)
     989             :     {
     990       13384 :         tuple = heap_form_tuple(tgrel->rd_att, values, nulls);
     991       13384 :         CatalogTupleInsert(tgrel, tuple);
     992             :     }
     993             :     else
     994             :     {
     995             :         HeapTuple   newtup;
     996             : 
     997          78 :         newtup = heap_form_tuple(tgrel->rd_att, values, nulls);
     998          78 :         CatalogTupleUpdate(tgrel, &tuple->t_self, newtup);
     999          78 :         heap_freetuple(newtup);
    1000             :     }
    1001             : 
    1002       13462 :     heap_freetuple(tuple);      /* free either original or new tuple */
    1003       13462 :     table_close(tgrel, RowExclusiveLock);
    1004             : 
    1005       13462 :     pfree(DatumGetPointer(values[Anum_pg_trigger_tgname - 1]));
    1006       13462 :     pfree(DatumGetPointer(values[Anum_pg_trigger_tgargs - 1]));
    1007       13462 :     pfree(DatumGetPointer(values[Anum_pg_trigger_tgattr - 1]));
    1008       13462 :     if (oldtablename)
    1009         232 :         pfree(DatumGetPointer(values[Anum_pg_trigger_tgoldtable - 1]));
    1010       13462 :     if (newtablename)
    1011         264 :         pfree(DatumGetPointer(values[Anum_pg_trigger_tgnewtable - 1]));
    1012             : 
    1013             :     /*
    1014             :      * Update relation's pg_class entry; if necessary; and if not, send an SI
    1015             :      * message to make other backends (and this one) rebuild relcache entries.
    1016             :      */
    1017       13462 :     pgrel = table_open(RelationRelationId, RowExclusiveLock);
    1018       13462 :     tuple = SearchSysCacheCopy1(RELOID,
    1019             :                                 ObjectIdGetDatum(RelationGetRelid(rel)));
    1020       13462 :     if (!HeapTupleIsValid(tuple))
    1021           0 :         elog(ERROR, "cache lookup failed for relation %u",
    1022             :              RelationGetRelid(rel));
    1023       13462 :     if (!((Form_pg_class) GETSTRUCT(tuple))->relhastriggers)
    1024             :     {
    1025        5490 :         ((Form_pg_class) GETSTRUCT(tuple))->relhastriggers = true;
    1026             : 
    1027        5490 :         CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
    1028             : 
    1029        5490 :         CommandCounterIncrement();
    1030             :     }
    1031             :     else
    1032        7972 :         CacheInvalidateRelcacheByTuple(tuple);
    1033             : 
    1034       13462 :     heap_freetuple(tuple);
    1035       13462 :     table_close(pgrel, RowExclusiveLock);
    1036             : 
    1037             :     /*
    1038             :      * If we're replacing a trigger, flush all the old dependencies before
    1039             :      * recording new ones.
    1040             :      */
    1041       13462 :     if (trigger_exists)
    1042          78 :         deleteDependencyRecordsFor(TriggerRelationId, trigoid, true);
    1043             : 
    1044             :     /*
    1045             :      * Record dependencies for trigger.  Always place a normal dependency on
    1046             :      * the function.
    1047             :      */
    1048       13462 :     myself.classId = TriggerRelationId;
    1049       13462 :     myself.objectId = trigoid;
    1050       13462 :     myself.objectSubId = 0;
    1051             : 
    1052       13462 :     referenced.classId = ProcedureRelationId;
    1053       13462 :     referenced.objectId = funcoid;
    1054       13462 :     referenced.objectSubId = 0;
    1055       13462 :     recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    1056             : 
    1057       13462 :     if (isInternal && OidIsValid(constraintOid))
    1058             :     {
    1059             :         /*
    1060             :          * Internally-generated trigger for a constraint, so make it an
    1061             :          * internal dependency of the constraint.  We can skip depending on
    1062             :          * the relation(s), as there'll be an indirect dependency via the
    1063             :          * constraint.
    1064             :          */
    1065        9904 :         referenced.classId = ConstraintRelationId;
    1066        9904 :         referenced.objectId = constraintOid;
    1067        9904 :         referenced.objectSubId = 0;
    1068        9904 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_INTERNAL);
    1069             :     }
    1070             :     else
    1071             :     {
    1072             :         /*
    1073             :          * User CREATE TRIGGER, so place dependencies.  We make trigger be
    1074             :          * auto-dropped if its relation is dropped or if the FK relation is
    1075             :          * dropped.  (Auto drop is compatible with our pre-7.3 behavior.)
    1076             :          */
    1077        3558 :         referenced.classId = RelationRelationId;
    1078        3558 :         referenced.objectId = RelationGetRelid(rel);
    1079        3558 :         referenced.objectSubId = 0;
    1080        3558 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
    1081             : 
    1082        3558 :         if (OidIsValid(constrrelid))
    1083             :         {
    1084          42 :             referenced.classId = RelationRelationId;
    1085          42 :             referenced.objectId = constrrelid;
    1086          42 :             referenced.objectSubId = 0;
    1087          42 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
    1088             :         }
    1089             :         /* Not possible to have an index dependency in this case */
    1090             :         Assert(!OidIsValid(indexOid));
    1091             : 
    1092             :         /*
    1093             :          * If it's a user-specified constraint trigger, make the constraint
    1094             :          * internally dependent on the trigger instead of vice versa.
    1095             :          */
    1096        3558 :         if (OidIsValid(constraintOid))
    1097             :         {
    1098         150 :             referenced.classId = ConstraintRelationId;
    1099         150 :             referenced.objectId = constraintOid;
    1100         150 :             referenced.objectSubId = 0;
    1101         150 :             recordDependencyOn(&referenced, &myself, DEPENDENCY_INTERNAL);
    1102             :         }
    1103             : 
    1104             :         /*
    1105             :          * If it's a partition trigger, create the partition dependencies.
    1106             :          */
    1107        3558 :         if (OidIsValid(parentTriggerOid))
    1108             :         {
    1109         732 :             ObjectAddressSet(referenced, TriggerRelationId, parentTriggerOid);
    1110         732 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
    1111         732 :             ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
    1112         732 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
    1113             :         }
    1114             :     }
    1115             : 
    1116             :     /* If column-specific trigger, add normal dependencies on columns */
    1117       13462 :     if (columns != NULL)
    1118             :     {
    1119             :         int         i;
    1120             : 
    1121          94 :         referenced.classId = RelationRelationId;
    1122          94 :         referenced.objectId = RelationGetRelid(rel);
    1123         196 :         for (i = 0; i < ncolumns; i++)
    1124             :         {
    1125         102 :             referenced.objectSubId = columns[i];
    1126         102 :             recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    1127             :         }
    1128             :     }
    1129             : 
    1130             :     /*
    1131             :      * If it has a WHEN clause, add dependencies on objects mentioned in the
    1132             :      * expression (eg, functions, as well as any columns used).
    1133             :      */
    1134       13462 :     if (whenRtable != NIL)
    1135         110 :         recordDependencyOnExpr(&myself, whenClause, whenRtable,
    1136             :                                DEPENDENCY_NORMAL);
    1137             : 
    1138             :     /* Post creation hook for new trigger */
    1139       13462 :     InvokeObjectPostCreateHookArg(TriggerRelationId, trigoid, 0,
    1140             :                                   isInternal);
    1141             : 
    1142             :     /*
    1143             :      * Lastly, create the trigger on child relations, if needed.
    1144             :      */
    1145       13462 :     if (partition_recurse)
    1146             :     {
    1147         362 :         PartitionDesc partdesc = RelationGetPartitionDesc(rel, true);
    1148             :         int         i;
    1149             :         MemoryContext oldcxt,
    1150             :                     perChildCxt;
    1151             : 
    1152         362 :         perChildCxt = AllocSetContextCreate(CurrentMemoryContext,
    1153             :                                             "part trig clone",
    1154             :                                             ALLOCSET_SMALL_SIZES);
    1155             : 
    1156             :         /*
    1157             :          * We don't currently expect to be called with a valid indexOid.  If
    1158             :          * that ever changes then we'll need to write code here to find the
    1159             :          * corresponding child index.
    1160             :          */
    1161             :         Assert(!OidIsValid(indexOid));
    1162             : 
    1163         362 :         oldcxt = MemoryContextSwitchTo(perChildCxt);
    1164             : 
    1165             :         /* Iterate to create the trigger on each existing partition */
    1166         944 :         for (i = 0; i < partdesc->nparts; i++)
    1167             :         {
    1168             :             CreateTrigStmt *childStmt;
    1169             :             Relation    childTbl;
    1170             :             Node       *qual;
    1171             : 
    1172         588 :             childTbl = table_open(partdesc->oids[i], ShareRowExclusiveLock);
    1173             : 
    1174             :             /*
    1175             :              * Initialize our fabricated parse node by copying the original
    1176             :              * one, then resetting fields that we pass separately.
    1177             :              */
    1178         588 :             childStmt = (CreateTrigStmt *) copyObject(stmt);
    1179         588 :             childStmt->funcname = NIL;
    1180         588 :             childStmt->whenClause = NULL;
    1181             : 
    1182             :             /* If there is a WHEN clause, create a modified copy of it */
    1183         588 :             qual = copyObject(whenClause);
    1184             :             qual = (Node *)
    1185         588 :                 map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
    1186             :                                         childTbl, rel);
    1187             :             qual = (Node *)
    1188         588 :                 map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
    1189             :                                         childTbl, rel);
    1190             : 
    1191         588 :             CreateTriggerFiringOn(childStmt, queryString,
    1192         588 :                                   partdesc->oids[i], refRelOid,
    1193             :                                   InvalidOid, InvalidOid,
    1194             :                                   funcoid, trigoid, qual,
    1195             :                                   isInternal, true, trigger_fires_when);
    1196             : 
    1197         582 :             table_close(childTbl, NoLock);
    1198             : 
    1199         582 :             MemoryContextReset(perChildCxt);
    1200             :         }
    1201             : 
    1202         356 :         MemoryContextSwitchTo(oldcxt);
    1203         356 :         MemoryContextDelete(perChildCxt);
    1204             :     }
    1205             : 
    1206             :     /* Keep lock on target rel until end of xact */
    1207       13456 :     table_close(rel, NoLock);
    1208             : 
    1209       13456 :     return myself;
    1210             : }
    1211             : 
    1212             : /*
    1213             :  * TriggerSetParentTrigger
    1214             :  *      Set a partition's trigger as child of its parent trigger,
    1215             :  *      or remove the linkage if parentTrigId is InvalidOid.
    1216             :  *
    1217             :  * This updates the constraint's pg_trigger row to show it as inherited, and
    1218             :  * adds PARTITION dependencies to prevent the trigger from being deleted
    1219             :  * on its own.  Alternatively, reverse that.
    1220             :  */
    1221             : void
    1222         276 : TriggerSetParentTrigger(Relation trigRel,
    1223             :                         Oid childTrigId,
    1224             :                         Oid parentTrigId,
    1225             :                         Oid childTableId)
    1226             : {
    1227             :     SysScanDesc tgscan;
    1228             :     ScanKeyData skey[1];
    1229             :     Form_pg_trigger trigForm;
    1230             :     HeapTuple   tuple,
    1231             :                 newtup;
    1232             :     ObjectAddress depender;
    1233             :     ObjectAddress referenced;
    1234             : 
    1235             :     /*
    1236             :      * Find the trigger to delete.
    1237             :      */
    1238         276 :     ScanKeyInit(&skey[0],
    1239             :                 Anum_pg_trigger_oid,
    1240             :                 BTEqualStrategyNumber, F_OIDEQ,
    1241             :                 ObjectIdGetDatum(childTrigId));
    1242             : 
    1243         276 :     tgscan = systable_beginscan(trigRel, TriggerOidIndexId, true,
    1244             :                                 NULL, 1, skey);
    1245             : 
    1246         276 :     tuple = systable_getnext(tgscan);
    1247         276 :     if (!HeapTupleIsValid(tuple))
    1248           0 :         elog(ERROR, "could not find tuple for trigger %u", childTrigId);
    1249         276 :     newtup = heap_copytuple(tuple);
    1250         276 :     trigForm = (Form_pg_trigger) GETSTRUCT(newtup);
    1251         276 :     if (OidIsValid(parentTrigId))
    1252             :     {
    1253             :         /* don't allow setting parent for a constraint that already has one */
    1254         156 :         if (OidIsValid(trigForm->tgparentid))
    1255           0 :             elog(ERROR, "trigger %u already has a parent trigger",
    1256             :                  childTrigId);
    1257             : 
    1258         156 :         trigForm->tgparentid = parentTrigId;
    1259             : 
    1260         156 :         CatalogTupleUpdate(trigRel, &tuple->t_self, newtup);
    1261             : 
    1262         156 :         ObjectAddressSet(depender, TriggerRelationId, childTrigId);
    1263             : 
    1264         156 :         ObjectAddressSet(referenced, TriggerRelationId, parentTrigId);
    1265         156 :         recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_PRI);
    1266             : 
    1267         156 :         ObjectAddressSet(referenced, RelationRelationId, childTableId);
    1268         156 :         recordDependencyOn(&depender, &referenced, DEPENDENCY_PARTITION_SEC);
    1269             :     }
    1270             :     else
    1271             :     {
    1272         120 :         trigForm->tgparentid = InvalidOid;
    1273             : 
    1274         120 :         CatalogTupleUpdate(trigRel, &tuple->t_self, newtup);
    1275             : 
    1276         120 :         deleteDependencyRecordsForClass(TriggerRelationId, childTrigId,
    1277             :                                         TriggerRelationId,
    1278             :                                         DEPENDENCY_PARTITION_PRI);
    1279         120 :         deleteDependencyRecordsForClass(TriggerRelationId, childTrigId,
    1280             :                                         RelationRelationId,
    1281             :                                         DEPENDENCY_PARTITION_SEC);
    1282             :     }
    1283             : 
    1284         276 :     heap_freetuple(newtup);
    1285         276 :     systable_endscan(tgscan);
    1286         276 : }
    1287             : 
    1288             : 
    1289             : /*
    1290             :  * Guts of trigger deletion.
    1291             :  */
    1292             : void
    1293       11208 : RemoveTriggerById(Oid trigOid)
    1294             : {
    1295             :     Relation    tgrel;
    1296             :     SysScanDesc tgscan;
    1297             :     ScanKeyData skey[1];
    1298             :     HeapTuple   tup;
    1299             :     Oid         relid;
    1300             :     Relation    rel;
    1301             : 
    1302       11208 :     tgrel = table_open(TriggerRelationId, RowExclusiveLock);
    1303             : 
    1304             :     /*
    1305             :      * Find the trigger to delete.
    1306             :      */
    1307       11208 :     ScanKeyInit(&skey[0],
    1308             :                 Anum_pg_trigger_oid,
    1309             :                 BTEqualStrategyNumber, F_OIDEQ,
    1310             :                 ObjectIdGetDatum(trigOid));
    1311             : 
    1312       11208 :     tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
    1313             :                                 NULL, 1, skey);
    1314             : 
    1315       11208 :     tup = systable_getnext(tgscan);
    1316       11208 :     if (!HeapTupleIsValid(tup))
    1317           0 :         elog(ERROR, "could not find tuple for trigger %u", trigOid);
    1318             : 
    1319             :     /*
    1320             :      * Open and exclusive-lock the relation the trigger belongs to.
    1321             :      */
    1322       11208 :     relid = ((Form_pg_trigger) GETSTRUCT(tup))->tgrelid;
    1323             : 
    1324       11208 :     rel = table_open(relid, AccessExclusiveLock);
    1325             : 
    1326       11208 :     if (rel->rd_rel->relkind != RELKIND_RELATION &&
    1327        1882 :         rel->rd_rel->relkind != RELKIND_VIEW &&
    1328        1758 :         rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
    1329        1666 :         rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    1330           0 :         ereport(ERROR,
    1331             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1332             :                  errmsg("relation \"%s\" cannot have triggers",
    1333             :                         RelationGetRelationName(rel)),
    1334             :                  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
    1335             : 
    1336       11208 :     if (!allowSystemTableMods && IsSystemRelation(rel))
    1337           0 :         ereport(ERROR,
    1338             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1339             :                  errmsg("permission denied: \"%s\" is a system catalog",
    1340             :                         RelationGetRelationName(rel))));
    1341             : 
    1342             :     /*
    1343             :      * Delete the pg_trigger tuple.
    1344             :      */
    1345       11208 :     CatalogTupleDelete(tgrel, &tup->t_self);
    1346             : 
    1347       11208 :     systable_endscan(tgscan);
    1348       11208 :     table_close(tgrel, RowExclusiveLock);
    1349             : 
    1350             :     /*
    1351             :      * We do not bother to try to determine whether any other triggers remain,
    1352             :      * which would be needed in order to decide whether it's safe to clear the
    1353             :      * relation's relhastriggers.  (In any case, there might be a concurrent
    1354             :      * process adding new triggers.)  Instead, just force a relcache inval to
    1355             :      * make other backends (and this one too!) rebuild their relcache entries.
    1356             :      * There's no great harm in leaving relhastriggers true even if there are
    1357             :      * no triggers left.
    1358             :      */
    1359       11208 :     CacheInvalidateRelcache(rel);
    1360             : 
    1361             :     /* Keep lock on trigger's rel until end of xact */
    1362       11208 :     table_close(rel, NoLock);
    1363       11208 : }
    1364             : 
    1365             : /*
    1366             :  * get_trigger_oid - Look up a trigger by name to find its OID.
    1367             :  *
    1368             :  * If missing_ok is false, throw an error if trigger not found.  If
    1369             :  * true, just return InvalidOid.
    1370             :  */
    1371             : Oid
    1372         740 : get_trigger_oid(Oid relid, const char *trigname, bool missing_ok)
    1373             : {
    1374             :     Relation    tgrel;
    1375             :     ScanKeyData skey[2];
    1376             :     SysScanDesc tgscan;
    1377             :     HeapTuple   tup;
    1378             :     Oid         oid;
    1379             : 
    1380             :     /*
    1381             :      * Find the trigger, verify permissions, set up object address
    1382             :      */
    1383         740 :     tgrel = table_open(TriggerRelationId, AccessShareLock);
    1384             : 
    1385         740 :     ScanKeyInit(&skey[0],
    1386             :                 Anum_pg_trigger_tgrelid,
    1387             :                 BTEqualStrategyNumber, F_OIDEQ,
    1388             :                 ObjectIdGetDatum(relid));
    1389         740 :     ScanKeyInit(&skey[1],
    1390             :                 Anum_pg_trigger_tgname,
    1391             :                 BTEqualStrategyNumber, F_NAMEEQ,
    1392             :                 CStringGetDatum(trigname));
    1393             : 
    1394         740 :     tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
    1395             :                                 NULL, 2, skey);
    1396             : 
    1397         740 :     tup = systable_getnext(tgscan);
    1398             : 
    1399         740 :     if (!HeapTupleIsValid(tup))
    1400             :     {
    1401          30 :         if (!missing_ok)
    1402          24 :             ereport(ERROR,
    1403             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    1404             :                      errmsg("trigger \"%s\" for table \"%s\" does not exist",
    1405             :                             trigname, get_rel_name(relid))));
    1406           6 :         oid = InvalidOid;
    1407             :     }
    1408             :     else
    1409             :     {
    1410         710 :         oid = ((Form_pg_trigger) GETSTRUCT(tup))->oid;
    1411             :     }
    1412             : 
    1413         716 :     systable_endscan(tgscan);
    1414         716 :     table_close(tgrel, AccessShareLock);
    1415         716 :     return oid;
    1416             : }
    1417             : 
    1418             : /*
    1419             :  * Perform permissions and integrity checks before acquiring a relation lock.
    1420             :  */
    1421             : static void
    1422          42 : RangeVarCallbackForRenameTrigger(const RangeVar *rv, Oid relid, Oid oldrelid,
    1423             :                                  void *arg)
    1424             : {
    1425             :     HeapTuple   tuple;
    1426             :     Form_pg_class form;
    1427             : 
    1428          42 :     tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    1429          42 :     if (!HeapTupleIsValid(tuple))
    1430           0 :         return;                 /* concurrently dropped */
    1431          42 :     form = (Form_pg_class) GETSTRUCT(tuple);
    1432             : 
    1433             :     /* only tables and views can have triggers */
    1434          42 :     if (form->relkind != RELKIND_RELATION && form->relkind != RELKIND_VIEW &&
    1435          24 :         form->relkind != RELKIND_FOREIGN_TABLE &&
    1436          24 :         form->relkind != RELKIND_PARTITIONED_TABLE)
    1437           0 :         ereport(ERROR,
    1438             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    1439             :                  errmsg("relation \"%s\" cannot have triggers",
    1440             :                         rv->relname),
    1441             :                  errdetail_relkind_not_supported(form->relkind)));
    1442             : 
    1443             :     /* you must own the table to rename one of its triggers */
    1444          42 :     if (!object_ownercheck(RelationRelationId, relid, GetUserId()))
    1445           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(get_rel_relkind(relid)), rv->relname);
    1446          42 :     if (!allowSystemTableMods && IsSystemClass(relid, form))
    1447           2 :         ereport(ERROR,
    1448             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1449             :                  errmsg("permission denied: \"%s\" is a system catalog",
    1450             :                         rv->relname)));
    1451             : 
    1452          40 :     ReleaseSysCache(tuple);
    1453             : }
    1454             : 
    1455             : /*
    1456             :  *      renametrig      - changes the name of a trigger on a relation
    1457             :  *
    1458             :  *      trigger name is changed in trigger catalog.
    1459             :  *      No record of the previous name is kept.
    1460             :  *
    1461             :  *      get proper relrelation from relation catalog (if not arg)
    1462             :  *      scan trigger catalog
    1463             :  *              for name conflict (within rel)
    1464             :  *              for original trigger (if not arg)
    1465             :  *      modify tgname in trigger tuple
    1466             :  *      update row in catalog
    1467             :  */
    1468             : ObjectAddress
    1469          40 : renametrig(RenameStmt *stmt)
    1470             : {
    1471             :     Oid         tgoid;
    1472             :     Relation    targetrel;
    1473             :     Relation    tgrel;
    1474             :     HeapTuple   tuple;
    1475             :     SysScanDesc tgscan;
    1476             :     ScanKeyData key[2];
    1477             :     Oid         relid;
    1478             :     ObjectAddress address;
    1479             : 
    1480             :     /*
    1481             :      * Look up name, check permissions, and acquire lock (which we will NOT
    1482             :      * release until end of transaction).
    1483             :      */
    1484          40 :     relid = RangeVarGetRelidExtended(stmt->relation, AccessExclusiveLock,
    1485             :                                      0,
    1486             :                                      RangeVarCallbackForRenameTrigger,
    1487             :                                      NULL);
    1488             : 
    1489             :     /* Have lock already, so just need to build relcache entry. */
    1490          38 :     targetrel = relation_open(relid, NoLock);
    1491             : 
    1492             :     /*
    1493             :      * On partitioned tables, this operation recurses to partitions.  Lock all
    1494             :      * tables upfront.
    1495             :      */
    1496          38 :     if (targetrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    1497          24 :         (void) find_all_inheritors(relid, AccessExclusiveLock, NULL);
    1498             : 
    1499          38 :     tgrel = table_open(TriggerRelationId, RowExclusiveLock);
    1500             : 
    1501             :     /*
    1502             :      * Search for the trigger to modify.
    1503             :      */
    1504          38 :     ScanKeyInit(&key[0],
    1505             :                 Anum_pg_trigger_tgrelid,
    1506             :                 BTEqualStrategyNumber, F_OIDEQ,
    1507             :                 ObjectIdGetDatum(relid));
    1508          38 :     ScanKeyInit(&key[1],
    1509             :                 Anum_pg_trigger_tgname,
    1510             :                 BTEqualStrategyNumber, F_NAMEEQ,
    1511          38 :                 PointerGetDatum(stmt->subname));
    1512          38 :     tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
    1513             :                                 NULL, 2, key);
    1514          38 :     if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
    1515             :     {
    1516             :         Form_pg_trigger trigform;
    1517             : 
    1518          38 :         trigform = (Form_pg_trigger) GETSTRUCT(tuple);
    1519          38 :         tgoid = trigform->oid;
    1520             : 
    1521             :         /*
    1522             :          * If the trigger descends from a trigger on a parent partitioned
    1523             :          * table, reject the rename.  We don't allow a trigger in a partition
    1524             :          * to differ in name from that of its parent: that would lead to an
    1525             :          * inconsistency that pg_dump would not reproduce.
    1526             :          */
    1527          38 :         if (OidIsValid(trigform->tgparentid))
    1528           6 :             ereport(ERROR,
    1529             :                     errmsg("cannot rename trigger \"%s\" on table \"%s\"",
    1530             :                            stmt->subname, RelationGetRelationName(targetrel)),
    1531             :                     errhint("Rename the trigger on the partitioned table \"%s\" instead.",
    1532             :                             get_rel_name(get_partition_parent(relid, false))));
    1533             : 
    1534             : 
    1535             :         /* Rename the trigger on this relation ... */
    1536          32 :         renametrig_internal(tgrel, targetrel, tuple, stmt->newname,
    1537          32 :                             stmt->subname);
    1538             : 
    1539             :         /* ... and if it is partitioned, recurse to its partitions */
    1540          32 :         if (targetrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    1541             :         {
    1542          18 :             PartitionDesc partdesc = RelationGetPartitionDesc(targetrel, true);
    1543             : 
    1544          30 :             for (int i = 0; i < partdesc->nparts; i++)
    1545             :             {
    1546          18 :                 Oid         partitionId = partdesc->oids[i];
    1547             : 
    1548          18 :                 renametrig_partition(tgrel, partitionId, trigform->oid,
    1549          18 :                                      stmt->newname, stmt->subname);
    1550             :             }
    1551             :         }
    1552             :     }
    1553             :     else
    1554             :     {
    1555           0 :         ereport(ERROR,
    1556             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    1557             :                  errmsg("trigger \"%s\" for table \"%s\" does not exist",
    1558             :                         stmt->subname, RelationGetRelationName(targetrel))));
    1559             :     }
    1560             : 
    1561          26 :     ObjectAddressSet(address, TriggerRelationId, tgoid);
    1562             : 
    1563          26 :     systable_endscan(tgscan);
    1564             : 
    1565          26 :     table_close(tgrel, RowExclusiveLock);
    1566             : 
    1567             :     /*
    1568             :      * Close rel, but keep exclusive lock!
    1569             :      */
    1570          26 :     relation_close(targetrel, NoLock);
    1571             : 
    1572          26 :     return address;
    1573             : }
    1574             : 
    1575             : /*
    1576             :  * Subroutine for renametrig -- perform the actual work of renaming one
    1577             :  * trigger on one table.
    1578             :  *
    1579             :  * If the trigger has a name different from the expected one, raise a
    1580             :  * NOTICE about it.
    1581             :  */
    1582             : static void
    1583          56 : renametrig_internal(Relation tgrel, Relation targetrel, HeapTuple trigtup,
    1584             :                     const char *newname, const char *expected_name)
    1585             : {
    1586             :     HeapTuple   tuple;
    1587             :     Form_pg_trigger tgform;
    1588             :     ScanKeyData key[2];
    1589             :     SysScanDesc tgscan;
    1590             : 
    1591             :     /* If the trigger already has the new name, nothing to do. */
    1592          56 :     tgform = (Form_pg_trigger) GETSTRUCT(trigtup);
    1593          56 :     if (strcmp(NameStr(tgform->tgname), newname) == 0)
    1594           0 :         return;
    1595             : 
    1596             :     /*
    1597             :      * Before actually trying the rename, search for triggers with the same
    1598             :      * name.  The update would fail with an ugly message in that case, and it
    1599             :      * is better to throw a nicer error.
    1600             :      */
    1601          56 :     ScanKeyInit(&key[0],
    1602             :                 Anum_pg_trigger_tgrelid,
    1603             :                 BTEqualStrategyNumber, F_OIDEQ,
    1604             :                 ObjectIdGetDatum(RelationGetRelid(targetrel)));
    1605          56 :     ScanKeyInit(&key[1],
    1606             :                 Anum_pg_trigger_tgname,
    1607             :                 BTEqualStrategyNumber, F_NAMEEQ,
    1608             :                 PointerGetDatum(newname));
    1609          56 :     tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
    1610             :                                 NULL, 2, key);
    1611          56 :     if (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
    1612           6 :         ereport(ERROR,
    1613             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
    1614             :                  errmsg("trigger \"%s\" for relation \"%s\" already exists",
    1615             :                         newname, RelationGetRelationName(targetrel))));
    1616          50 :     systable_endscan(tgscan);
    1617             : 
    1618             :     /*
    1619             :      * The target name is free; update the existing pg_trigger tuple with it.
    1620             :      */
    1621          50 :     tuple = heap_copytuple(trigtup);    /* need a modifiable copy */
    1622          50 :     tgform = (Form_pg_trigger) GETSTRUCT(tuple);
    1623             : 
    1624             :     /*
    1625             :      * If the trigger has a name different from what we expected, let the user
    1626             :      * know. (We can proceed anyway, since we must have reached here following
    1627             :      * a tgparentid link.)
    1628             :      */
    1629          50 :     if (strcmp(NameStr(tgform->tgname), expected_name) != 0)
    1630           0 :         ereport(NOTICE,
    1631             :                 errmsg("renamed trigger \"%s\" on relation \"%s\"",
    1632             :                        NameStr(tgform->tgname),
    1633             :                        RelationGetRelationName(targetrel)));
    1634             : 
    1635          50 :     namestrcpy(&tgform->tgname, newname);
    1636             : 
    1637          50 :     CatalogTupleUpdate(tgrel, &tuple->t_self, tuple);
    1638             : 
    1639          50 :     InvokeObjectPostAlterHook(TriggerRelationId, tgform->oid, 0);
    1640             : 
    1641             :     /*
    1642             :      * Invalidate relation's relcache entry so that other backends (and this
    1643             :      * one too!) are sent SI message to make them rebuild relcache entries.
    1644             :      * (Ideally this should happen automatically...)
    1645             :      */
    1646          50 :     CacheInvalidateRelcache(targetrel);
    1647             : }
    1648             : 
    1649             : /*
    1650             :  * Subroutine for renametrig -- Helper for recursing to partitions when
    1651             :  * renaming triggers on a partitioned table.
    1652             :  */
    1653             : static void
    1654          30 : renametrig_partition(Relation tgrel, Oid partitionId, Oid parentTriggerOid,
    1655             :                      const char *newname, const char *expected_name)
    1656             : {
    1657             :     SysScanDesc tgscan;
    1658             :     ScanKeyData key;
    1659             :     HeapTuple   tuple;
    1660             : 
    1661             :     /*
    1662             :      * Given a relation and the OID of a trigger on parent relation, find the
    1663             :      * corresponding trigger in the child and rename that trigger to the given
    1664             :      * name.
    1665             :      */
    1666          30 :     ScanKeyInit(&key,
    1667             :                 Anum_pg_trigger_tgrelid,
    1668             :                 BTEqualStrategyNumber, F_OIDEQ,
    1669             :                 ObjectIdGetDatum(partitionId));
    1670          30 :     tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
    1671             :                                 NULL, 1, &key);
    1672          48 :     while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
    1673             :     {
    1674          42 :         Form_pg_trigger tgform = (Form_pg_trigger) GETSTRUCT(tuple);
    1675             :         Relation    partitionRel;
    1676             : 
    1677          42 :         if (tgform->tgparentid != parentTriggerOid)
    1678          18 :             continue;           /* not our trigger */
    1679             : 
    1680          24 :         partitionRel = table_open(partitionId, NoLock);
    1681             : 
    1682             :         /* Rename the trigger on this partition */
    1683          24 :         renametrig_internal(tgrel, partitionRel, tuple, newname, expected_name);
    1684             : 
    1685             :         /* And if this relation is partitioned, recurse to its partitions */
    1686          18 :         if (partitionRel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    1687             :         {
    1688           6 :             PartitionDesc partdesc = RelationGetPartitionDesc(partitionRel,
    1689             :                                                               true);
    1690             : 
    1691          18 :             for (int i = 0; i < partdesc->nparts; i++)
    1692             :             {
    1693          12 :                 Oid         partoid = partdesc->oids[i];
    1694             : 
    1695          12 :                 renametrig_partition(tgrel, partoid, tgform->oid, newname,
    1696          12 :                                      NameStr(tgform->tgname));
    1697             :             }
    1698             :         }
    1699          18 :         table_close(partitionRel, NoLock);
    1700             : 
    1701             :         /* There should be at most one matching tuple */
    1702          18 :         break;
    1703             :     }
    1704          24 :     systable_endscan(tgscan);
    1705          24 : }
    1706             : 
    1707             : /*
    1708             :  * EnableDisableTrigger()
    1709             :  *
    1710             :  *  Called by ALTER TABLE ENABLE/DISABLE [ REPLICA | ALWAYS ] TRIGGER
    1711             :  *  to change 'tgenabled' field for the specified trigger(s)
    1712             :  *
    1713             :  * rel: relation to process (caller must hold suitable lock on it)
    1714             :  * tgname: name of trigger to process, or NULL to scan all triggers
    1715             :  * tgparent: if not zero, process only triggers with this tgparentid
    1716             :  * fires_when: new value for tgenabled field. In addition to generic
    1717             :  *             enablement/disablement, this also defines when the trigger
    1718             :  *             should be fired in session replication roles.
    1719             :  * skip_system: if true, skip "system" triggers (constraint triggers)
    1720             :  * recurse: if true, recurse to partitions
    1721             :  *
    1722             :  * Caller should have checked permissions for the table; here we also
    1723             :  * enforce that superuser privilege is required to alter the state of
    1724             :  * system triggers
    1725             :  */
    1726             : void
    1727         446 : EnableDisableTrigger(Relation rel, const char *tgname, Oid tgparent,
    1728             :                      char fires_when, bool skip_system, bool recurse,
    1729             :                      LOCKMODE lockmode)
    1730             : {
    1731             :     Relation    tgrel;
    1732             :     int         nkeys;
    1733             :     ScanKeyData keys[2];
    1734             :     SysScanDesc tgscan;
    1735             :     HeapTuple   tuple;
    1736             :     bool        found;
    1737             :     bool        changed;
    1738             : 
    1739             :     /* Scan the relevant entries in pg_triggers */
    1740         446 :     tgrel = table_open(TriggerRelationId, RowExclusiveLock);
    1741             : 
    1742         446 :     ScanKeyInit(&keys[0],
    1743             :                 Anum_pg_trigger_tgrelid,
    1744             :                 BTEqualStrategyNumber, F_OIDEQ,
    1745             :                 ObjectIdGetDatum(RelationGetRelid(rel)));
    1746         446 :     if (tgname)
    1747             :     {
    1748         312 :         ScanKeyInit(&keys[1],
    1749             :                     Anum_pg_trigger_tgname,
    1750             :                     BTEqualStrategyNumber, F_NAMEEQ,
    1751             :                     CStringGetDatum(tgname));
    1752         312 :         nkeys = 2;
    1753             :     }
    1754             :     else
    1755         134 :         nkeys = 1;
    1756             : 
    1757         446 :     tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
    1758             :                                 NULL, nkeys, keys);
    1759             : 
    1760         446 :     found = changed = false;
    1761             : 
    1762        1120 :     while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
    1763             :     {
    1764         674 :         Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
    1765             : 
    1766         674 :         if (OidIsValid(tgparent) && tgparent != oldtrig->tgparentid)
    1767         156 :             continue;
    1768             : 
    1769         518 :         if (oldtrig->tgisinternal)
    1770             :         {
    1771             :             /* system trigger ... ok to process? */
    1772          60 :             if (skip_system)
    1773          12 :                 continue;
    1774          48 :             if (!superuser())
    1775           0 :                 ereport(ERROR,
    1776             :                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1777             :                          errmsg("permission denied: \"%s\" is a system trigger",
    1778             :                                 NameStr(oldtrig->tgname))));
    1779             :         }
    1780             : 
    1781         506 :         found = true;
    1782             : 
    1783         506 :         if (oldtrig->tgenabled != fires_when)
    1784             :         {
    1785             :             /* need to change this one ... make a copy to scribble on */
    1786         476 :             HeapTuple   newtup = heap_copytuple(tuple);
    1787         476 :             Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
    1788             : 
    1789         476 :             newtrig->tgenabled = fires_when;
    1790             : 
    1791         476 :             CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
    1792             : 
    1793         476 :             heap_freetuple(newtup);
    1794             : 
    1795         476 :             changed = true;
    1796             :         }
    1797             : 
    1798             :         /*
    1799             :          * When altering FOR EACH ROW triggers on a partitioned table, do the
    1800             :          * same on the partitions as well, unless ONLY is specified.
    1801             :          *
    1802             :          * Note that we recurse even if we didn't change the trigger above,
    1803             :          * because the partitions' copy of the trigger may have a different
    1804             :          * value of tgenabled than the parent's trigger and thus might need to
    1805             :          * be changed.
    1806             :          */
    1807         506 :         if (recurse &&
    1808         478 :             rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
    1809          86 :             (TRIGGER_FOR_ROW(oldtrig->tgtype)))
    1810             :         {
    1811          74 :             PartitionDesc partdesc = RelationGetPartitionDesc(rel, true);
    1812             :             int         i;
    1813             : 
    1814         184 :             for (i = 0; i < partdesc->nparts; i++)
    1815             :             {
    1816             :                 Relation    part;
    1817             : 
    1818         110 :                 part = relation_open(partdesc->oids[i], lockmode);
    1819             :                 /* Match on child triggers' tgparentid, not their name */
    1820         110 :                 EnableDisableTrigger(part, NULL, oldtrig->oid,
    1821             :                                      fires_when, skip_system, recurse,
    1822             :                                      lockmode);
    1823         110 :                 table_close(part, NoLock);  /* keep lock till commit */
    1824             :             }
    1825             :         }
    1826             : 
    1827         506 :         InvokeObjectPostAlterHook(TriggerRelationId,
    1828             :                                   oldtrig->oid, 0);
    1829             :     }
    1830             : 
    1831         446 :     systable_endscan(tgscan);
    1832             : 
    1833         446 :     table_close(tgrel, RowExclusiveLock);
    1834             : 
    1835         446 :     if (tgname && !found)
    1836           0 :         ereport(ERROR,
    1837             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    1838             :                  errmsg("trigger \"%s\" for table \"%s\" does not exist",
    1839             :                         tgname, RelationGetRelationName(rel))));
    1840             : 
    1841             :     /*
    1842             :      * If we changed anything, broadcast a SI inval message to force each
    1843             :      * backend (including our own!) to rebuild relation's relcache entry.
    1844             :      * Otherwise they will fail to apply the change promptly.
    1845             :      */
    1846         446 :     if (changed)
    1847         428 :         CacheInvalidateRelcache(rel);
    1848         446 : }
    1849             : 
    1850             : 
    1851             : /*
    1852             :  * Build trigger data to attach to the given relcache entry.
    1853             :  *
    1854             :  * Note that trigger data attached to a relcache entry must be stored in
    1855             :  * CacheMemoryContext to ensure it survives as long as the relcache entry.
    1856             :  * But we should be running in a less long-lived working context.  To avoid
    1857             :  * leaking cache memory if this routine fails partway through, we build a
    1858             :  * temporary TriggerDesc in working memory and then copy the completed
    1859             :  * structure into cache memory.
    1860             :  */
    1861             : void
    1862       49972 : RelationBuildTriggers(Relation relation)
    1863             : {
    1864             :     TriggerDesc *trigdesc;
    1865             :     int         numtrigs;
    1866             :     int         maxtrigs;
    1867             :     Trigger    *triggers;
    1868             :     Relation    tgrel;
    1869             :     ScanKeyData skey;
    1870             :     SysScanDesc tgscan;
    1871             :     HeapTuple   htup;
    1872             :     MemoryContext oldContext;
    1873             :     int         i;
    1874             : 
    1875             :     /*
    1876             :      * Allocate a working array to hold the triggers (the array is extended if
    1877             :      * necessary)
    1878             :      */
    1879       49972 :     maxtrigs = 16;
    1880       49972 :     triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
    1881       49972 :     numtrigs = 0;
    1882             : 
    1883             :     /*
    1884             :      * Note: since we scan the triggers using TriggerRelidNameIndexId, we will
    1885             :      * be reading the triggers in name order, except possibly during
    1886             :      * emergency-recovery operations (ie, IgnoreSystemIndexes). This in turn
    1887             :      * ensures that triggers will be fired in name order.
    1888             :      */
    1889       49972 :     ScanKeyInit(&skey,
    1890             :                 Anum_pg_trigger_tgrelid,
    1891             :                 BTEqualStrategyNumber, F_OIDEQ,
    1892             :                 ObjectIdGetDatum(RelationGetRelid(relation)));
    1893             : 
    1894       49972 :     tgrel = table_open(TriggerRelationId, AccessShareLock);
    1895       49972 :     tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
    1896             :                                 NULL, 1, &skey);
    1897             : 
    1898      136950 :     while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
    1899             :     {
    1900       86978 :         Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
    1901             :         Trigger    *build;
    1902             :         Datum       datum;
    1903             :         bool        isnull;
    1904             : 
    1905       86978 :         if (numtrigs >= maxtrigs)
    1906             :         {
    1907          48 :             maxtrigs *= 2;
    1908          48 :             triggers = (Trigger *) repalloc(triggers, maxtrigs * sizeof(Trigger));
    1909             :         }
    1910       86978 :         build = &(triggers[numtrigs]);
    1911             : 
    1912       86978 :         build->tgoid = pg_trigger->oid;
    1913       86978 :         build->tgname = DatumGetCString(DirectFunctionCall1(nameout,
    1914             :                                                             NameGetDatum(&pg_trigger->tgname)));
    1915       86978 :         build->tgfoid = pg_trigger->tgfoid;
    1916       86978 :         build->tgtype = pg_trigger->tgtype;
    1917       86978 :         build->tgenabled = pg_trigger->tgenabled;
    1918       86978 :         build->tgisinternal = pg_trigger->tgisinternal;
    1919       86978 :         build->tgisclone = OidIsValid(pg_trigger->tgparentid);
    1920       86978 :         build->tgconstrrelid = pg_trigger->tgconstrrelid;
    1921       86978 :         build->tgconstrindid = pg_trigger->tgconstrindid;
    1922       86978 :         build->tgconstraint = pg_trigger->tgconstraint;
    1923       86978 :         build->tgdeferrable = pg_trigger->tgdeferrable;
    1924       86978 :         build->tginitdeferred = pg_trigger->tginitdeferred;
    1925       86978 :         build->tgnargs = pg_trigger->tgnargs;
    1926             :         /* tgattr is first var-width field, so OK to access directly */
    1927       86978 :         build->tgnattr = pg_trigger->tgattr.dim1;
    1928       86978 :         if (build->tgnattr > 0)
    1929             :         {
    1930         500 :             build->tgattr = (int16 *) palloc(build->tgnattr * sizeof(int16));
    1931         500 :             memcpy(build->tgattr, &(pg_trigger->tgattr.values),
    1932         500 :                    build->tgnattr * sizeof(int16));
    1933             :         }
    1934             :         else
    1935       86478 :             build->tgattr = NULL;
    1936       86978 :         if (build->tgnargs > 0)
    1937             :         {
    1938             :             bytea      *val;
    1939             :             char       *p;
    1940             : 
    1941        2802 :             val = DatumGetByteaPP(fastgetattr(htup,
    1942             :                                               Anum_pg_trigger_tgargs,
    1943             :                                               tgrel->rd_att, &isnull));
    1944        2802 :             if (isnull)
    1945           0 :                 elog(ERROR, "tgargs is null in trigger for relation \"%s\"",
    1946             :                      RelationGetRelationName(relation));
    1947        2802 :             p = (char *) VARDATA_ANY(val);
    1948        2802 :             build->tgargs = (char **) palloc(build->tgnargs * sizeof(char *));
    1949        6314 :             for (i = 0; i < build->tgnargs; i++)
    1950             :             {
    1951        3512 :                 build->tgargs[i] = pstrdup(p);
    1952        3512 :                 p += strlen(p) + 1;
    1953             :             }
    1954             :         }
    1955             :         else
    1956       84176 :             build->tgargs = NULL;
    1957             : 
    1958       86978 :         datum = fastgetattr(htup, Anum_pg_trigger_tgoldtable,
    1959             :                             tgrel->rd_att, &isnull);
    1960       86978 :         if (!isnull)
    1961         730 :             build->tgoldtable =
    1962         730 :                 DatumGetCString(DirectFunctionCall1(nameout, datum));
    1963             :         else
    1964       86248 :             build->tgoldtable = NULL;
    1965             : 
    1966       86978 :         datum = fastgetattr(htup, Anum_pg_trigger_tgnewtable,
    1967             :                             tgrel->rd_att, &isnull);
    1968       86978 :         if (!isnull)
    1969        1034 :             build->tgnewtable =
    1970        1034 :                 DatumGetCString(DirectFunctionCall1(nameout, datum));
    1971             :         else
    1972       85944 :             build->tgnewtable = NULL;
    1973             : 
    1974       86978 :         datum = fastgetattr(htup, Anum_pg_trigger_tgqual,
    1975             :                             tgrel->rd_att, &isnull);
    1976       86978 :         if (!isnull)
    1977         744 :             build->tgqual = TextDatumGetCString(datum);
    1978             :         else
    1979       86234 :             build->tgqual = NULL;
    1980             : 
    1981       86978 :         numtrigs++;
    1982             :     }
    1983             : 
    1984       49972 :     systable_endscan(tgscan);
    1985       49972 :     table_close(tgrel, AccessShareLock);
    1986             : 
    1987             :     /* There might not be any triggers */
    1988       49972 :     if (numtrigs == 0)
    1989             :     {
    1990       11690 :         pfree(triggers);
    1991       11690 :         return;
    1992             :     }
    1993             : 
    1994             :     /* Build trigdesc */
    1995       38282 :     trigdesc = (TriggerDesc *) palloc0(sizeof(TriggerDesc));
    1996       38282 :     trigdesc->triggers = triggers;
    1997       38282 :     trigdesc->numtriggers = numtrigs;
    1998      125260 :     for (i = 0; i < numtrigs; i++)
    1999       86978 :         SetTriggerFlags(trigdesc, &(triggers[i]));
    2000             : 
    2001             :     /* Copy completed trigdesc into cache storage */
    2002       38282 :     oldContext = MemoryContextSwitchTo(CacheMemoryContext);
    2003       38282 :     relation->trigdesc = CopyTriggerDesc(trigdesc);
    2004       38282 :     MemoryContextSwitchTo(oldContext);
    2005             : 
    2006             :     /* Release working memory */
    2007       38282 :     FreeTriggerDesc(trigdesc);
    2008             : }
    2009             : 
    2010             : /*
    2011             :  * Update the TriggerDesc's hint flags to include the specified trigger
    2012             :  */
    2013             : static void
    2014       86978 : SetTriggerFlags(TriggerDesc *trigdesc, Trigger *trigger)
    2015             : {
    2016       86978 :     int16       tgtype = trigger->tgtype;
    2017             : 
    2018       86978 :     trigdesc->trig_insert_before_row |=
    2019       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2020             :                              TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT);
    2021       86978 :     trigdesc->trig_insert_after_row |=
    2022       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2023             :                              TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT);
    2024       86978 :     trigdesc->trig_insert_instead_row |=
    2025       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2026             :                              TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_INSERT);
    2027       86978 :     trigdesc->trig_insert_before_statement |=
    2028       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
    2029             :                              TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT);
    2030       86978 :     trigdesc->trig_insert_after_statement |=
    2031       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
    2032             :                              TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT);
    2033       86978 :     trigdesc->trig_update_before_row |=
    2034       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2035             :                              TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_UPDATE);
    2036       86978 :     trigdesc->trig_update_after_row |=
    2037       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2038             :                              TRIGGER_TYPE_AFTER, TRIGGER_TYPE_UPDATE);
    2039       86978 :     trigdesc->trig_update_instead_row |=
    2040       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2041             :                              TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_UPDATE);
    2042       86978 :     trigdesc->trig_update_before_statement |=
    2043       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
    2044             :                              TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_UPDATE);
    2045       86978 :     trigdesc->trig_update_after_statement |=
    2046       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
    2047             :                              TRIGGER_TYPE_AFTER, TRIGGER_TYPE_UPDATE);
    2048       86978 :     trigdesc->trig_delete_before_row |=
    2049       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2050             :                              TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE);
    2051       86978 :     trigdesc->trig_delete_after_row |=
    2052       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2053             :                              TRIGGER_TYPE_AFTER, TRIGGER_TYPE_DELETE);
    2054       86978 :     trigdesc->trig_delete_instead_row |=
    2055       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
    2056             :                              TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_DELETE);
    2057       86978 :     trigdesc->trig_delete_before_statement |=
    2058       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
    2059             :                              TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE);
    2060       86978 :     trigdesc->trig_delete_after_statement |=
    2061       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
    2062             :                              TRIGGER_TYPE_AFTER, TRIGGER_TYPE_DELETE);
    2063             :     /* there are no row-level truncate triggers */
    2064       86978 :     trigdesc->trig_truncate_before_statement |=
    2065       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
    2066             :                              TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_TRUNCATE);
    2067       86978 :     trigdesc->trig_truncate_after_statement |=
    2068       86978 :         TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
    2069             :                              TRIGGER_TYPE_AFTER, TRIGGER_TYPE_TRUNCATE);
    2070             : 
    2071      173956 :     trigdesc->trig_insert_new_table |=
    2072      116990 :         (TRIGGER_FOR_INSERT(tgtype) &&
    2073       30012 :          TRIGGER_USES_TRANSITION_TABLE(trigger->tgnewtable));
    2074      173956 :     trigdesc->trig_update_old_table |=
    2075      126396 :         (TRIGGER_FOR_UPDATE(tgtype) &&
    2076       39418 :          TRIGGER_USES_TRANSITION_TABLE(trigger->tgoldtable));
    2077      173956 :     trigdesc->trig_update_new_table |=
    2078      126396 :         (TRIGGER_FOR_UPDATE(tgtype) &&
    2079       39418 :          TRIGGER_USES_TRANSITION_TABLE(trigger->tgnewtable));
    2080      173956 :     trigdesc->trig_delete_old_table |=
    2081      110196 :         (TRIGGER_FOR_DELETE(tgtype) &&
    2082       23218 :          TRIGGER_USES_TRANSITION_TABLE(trigger->tgoldtable));
    2083       86978 : }
    2084             : 
    2085             : /*
    2086             :  * Copy a TriggerDesc data structure.
    2087             :  *
    2088             :  * The copy is allocated in the current memory context.
    2089             :  */
    2090             : TriggerDesc *
    2091      492488 : CopyTriggerDesc(TriggerDesc *trigdesc)
    2092             : {
    2093             :     TriggerDesc *newdesc;
    2094             :     Trigger    *trigger;
    2095             :     int         i;
    2096             : 
    2097      492488 :     if (trigdesc == NULL || trigdesc->numtriggers <= 0)
    2098      438092 :         return NULL;
    2099             : 
    2100       54396 :     newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
    2101       54396 :     memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
    2102             : 
    2103       54396 :     trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
    2104       54396 :     memcpy(trigger, trigdesc->triggers,
    2105       54396 :            trigdesc->numtriggers * sizeof(Trigger));
    2106       54396 :     newdesc->triggers = trigger;
    2107             : 
    2108      186878 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2109             :     {
    2110      132482 :         trigger->tgname = pstrdup(trigger->tgname);
    2111      132482 :         if (trigger->tgnattr > 0)
    2112             :         {
    2113             :             int16      *newattr;
    2114             : 
    2115         986 :             newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
    2116         986 :             memcpy(newattr, trigger->tgattr,
    2117         986 :                    trigger->tgnattr * sizeof(int16));
    2118         986 :             trigger->tgattr = newattr;
    2119             :         }
    2120      132482 :         if (trigger->tgnargs > 0)
    2121             :         {
    2122             :             char      **newargs;
    2123             :             int16       j;
    2124             : 
    2125        9282 :             newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
    2126       20830 :             for (j = 0; j < trigger->tgnargs; j++)
    2127       11548 :                 newargs[j] = pstrdup(trigger->tgargs[j]);
    2128        9282 :             trigger->tgargs = newargs;
    2129             :         }
    2130      132482 :         if (trigger->tgqual)
    2131        1242 :             trigger->tgqual = pstrdup(trigger->tgqual);
    2132      132482 :         if (trigger->tgoldtable)
    2133        1918 :             trigger->tgoldtable = pstrdup(trigger->tgoldtable);
    2134      132482 :         if (trigger->tgnewtable)
    2135        2300 :             trigger->tgnewtable = pstrdup(trigger->tgnewtable);
    2136      132482 :         trigger++;
    2137             :     }
    2138             : 
    2139       54396 :     return newdesc;
    2140             : }
    2141             : 
    2142             : /*
    2143             :  * Free a TriggerDesc data structure.
    2144             :  */
    2145             : void
    2146     1496844 : FreeTriggerDesc(TriggerDesc *trigdesc)
    2147             : {
    2148             :     Trigger    *trigger;
    2149             :     int         i;
    2150             : 
    2151     1496844 :     if (trigdesc == NULL)
    2152     1423972 :         return;
    2153             : 
    2154       72872 :     trigger = trigdesc->triggers;
    2155      235476 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2156             :     {
    2157      162604 :         pfree(trigger->tgname);
    2158      162604 :         if (trigger->tgnattr > 0)
    2159         934 :             pfree(trigger->tgattr);
    2160      162604 :         if (trigger->tgnargs > 0)
    2161             :         {
    2162       11914 :             while (--(trigger->tgnargs) >= 0)
    2163        6640 :                 pfree(trigger->tgargs[trigger->tgnargs]);
    2164        5274 :             pfree(trigger->tgargs);
    2165             :         }
    2166      162604 :         if (trigger->tgqual)
    2167        1380 :             pfree(trigger->tgqual);
    2168      162604 :         if (trigger->tgoldtable)
    2169        1382 :             pfree(trigger->tgoldtable);
    2170      162604 :         if (trigger->tgnewtable)
    2171        1976 :             pfree(trigger->tgnewtable);
    2172      162604 :         trigger++;
    2173             :     }
    2174       72872 :     pfree(trigdesc->triggers);
    2175       72872 :     pfree(trigdesc);
    2176             : }
    2177             : 
    2178             : /*
    2179             :  * Compare two TriggerDesc structures for logical equality.
    2180             :  */
    2181             : #ifdef NOT_USED
    2182             : bool
    2183             : equalTriggerDescs(TriggerDesc *trigdesc1, TriggerDesc *trigdesc2)
    2184             : {
    2185             :     int         i,
    2186             :                 j;
    2187             : 
    2188             :     /*
    2189             :      * We need not examine the hint flags, just the trigger array itself; if
    2190             :      * we have the same triggers with the same types, the flags should match.
    2191             :      *
    2192             :      * As of 7.3 we assume trigger set ordering is significant in the
    2193             :      * comparison; so we just compare corresponding slots of the two sets.
    2194             :      *
    2195             :      * Note: comparing the stringToNode forms of the WHEN clauses means that
    2196             :      * parse column locations will affect the result.  This is okay as long as
    2197             :      * this function is only used for detecting exact equality, as for example
    2198             :      * in checking for staleness of a cache entry.
    2199             :      */
    2200             :     if (trigdesc1 != NULL)
    2201             :     {
    2202             :         if (trigdesc2 == NULL)
    2203             :             return false;
    2204             :         if (trigdesc1->numtriggers != trigdesc2->numtriggers)
    2205             :             return false;
    2206             :         for (i = 0; i < trigdesc1->numtriggers; i++)
    2207             :         {
    2208             :             Trigger    *trig1 = trigdesc1->triggers + i;
    2209             :             Trigger    *trig2 = trigdesc2->triggers + i;
    2210             : 
    2211             :             if (trig1->tgoid != trig2->tgoid)
    2212             :                 return false;
    2213             :             if (strcmp(trig1->tgname, trig2->tgname) != 0)
    2214             :                 return false;
    2215             :             if (trig1->tgfoid != trig2->tgfoid)
    2216             :                 return false;
    2217             :             if (trig1->tgtype != trig2->tgtype)
    2218             :                 return false;
    2219             :             if (trig1->tgenabled != trig2->tgenabled)
    2220             :                 return false;
    2221             :             if (trig1->tgisinternal != trig2->tgisinternal)
    2222             :                 return false;
    2223             :             if (trig1->tgisclone != trig2->tgisclone)
    2224             :                 return false;
    2225             :             if (trig1->tgconstrrelid != trig2->tgconstrrelid)
    2226             :                 return false;
    2227             :             if (trig1->tgconstrindid != trig2->tgconstrindid)
    2228             :                 return false;
    2229             :             if (trig1->tgconstraint != trig2->tgconstraint)
    2230             :                 return false;
    2231             :             if (trig1->tgdeferrable != trig2->tgdeferrable)
    2232             :                 return false;
    2233             :             if (trig1->tginitdeferred != trig2->tginitdeferred)
    2234             :                 return false;
    2235             :             if (trig1->tgnargs != trig2->tgnargs)
    2236             :                 return false;
    2237             :             if (trig1->tgnattr != trig2->tgnattr)
    2238             :                 return false;
    2239             :             if (trig1->tgnattr > 0 &&
    2240             :                 memcmp(trig1->tgattr, trig2->tgattr,
    2241             :                        trig1->tgnattr * sizeof(int16)) != 0)
    2242             :                 return false;
    2243             :             for (j = 0; j < trig1->tgnargs; j++)
    2244             :                 if (strcmp(trig1->tgargs[j], trig2->tgargs[j]) != 0)
    2245             :                     return false;
    2246             :             if (trig1->tgqual == NULL && trig2->tgqual == NULL)
    2247             :                  /* ok */ ;
    2248             :             else if (trig1->tgqual == NULL || trig2->tgqual == NULL)
    2249             :                 return false;
    2250             :             else if (strcmp(trig1->tgqual, trig2->tgqual) != 0)
    2251             :                 return false;
    2252             :             if (trig1->tgoldtable == NULL && trig2->tgoldtable == NULL)
    2253             :                  /* ok */ ;
    2254             :             else if (trig1->tgoldtable == NULL || trig2->tgoldtable == NULL)
    2255             :                 return false;
    2256             :             else if (strcmp(trig1->tgoldtable, trig2->tgoldtable) != 0)
    2257             :                 return false;
    2258             :             if (trig1->tgnewtable == NULL && trig2->tgnewtable == NULL)
    2259             :                  /* ok */ ;
    2260             :             else if (trig1->tgnewtable == NULL || trig2->tgnewtable == NULL)
    2261             :                 return false;
    2262             :             else if (strcmp(trig1->tgnewtable, trig2->tgnewtable) != 0)
    2263             :                 return false;
    2264             :         }
    2265             :     }
    2266             :     else if (trigdesc2 != NULL)
    2267             :         return false;
    2268             :     return true;
    2269             : }
    2270             : #endif                          /* NOT_USED */
    2271             : 
    2272             : /*
    2273             :  * Check if there is a row-level trigger with transition tables that prevents
    2274             :  * a table from becoming an inheritance child or partition.  Return the name
    2275             :  * of the first such incompatible trigger, or NULL if there is none.
    2276             :  */
    2277             : const char *
    2278        2204 : FindTriggerIncompatibleWithInheritance(TriggerDesc *trigdesc)
    2279             : {
    2280        2204 :     if (trigdesc != NULL)
    2281             :     {
    2282             :         int         i;
    2283             : 
    2284         336 :         for (i = 0; i < trigdesc->numtriggers; ++i)
    2285             :         {
    2286         246 :             Trigger    *trigger = &trigdesc->triggers[i];
    2287             : 
    2288         246 :             if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
    2289          12 :                 return trigger->tgname;
    2290             :         }
    2291             :     }
    2292             : 
    2293        2192 :     return NULL;
    2294             : }
    2295             : 
    2296             : /*
    2297             :  * Call a trigger function.
    2298             :  *
    2299             :  *      trigdata: trigger descriptor.
    2300             :  *      tgindx: trigger's index in finfo and instr arrays.
    2301             :  *      finfo: array of cached trigger function call information.
    2302             :  *      instr: optional array of EXPLAIN ANALYZE instrumentation state.
    2303             :  *      per_tuple_context: memory context to execute the function in.
    2304             :  *
    2305             :  * Returns the tuple (or NULL) as returned by the function.
    2306             :  */
    2307             : static HeapTuple
    2308       20706 : ExecCallTriggerFunc(TriggerData *trigdata,
    2309             :                     int tgindx,
    2310             :                     FmgrInfo *finfo,
    2311             :                     Instrumentation *instr,
    2312             :                     MemoryContext per_tuple_context)
    2313             : {
    2314       20706 :     LOCAL_FCINFO(fcinfo, 0);
    2315             :     PgStat_FunctionCallUsage fcusage;
    2316             :     Datum       result;
    2317             :     MemoryContext oldContext;
    2318             : 
    2319             :     /*
    2320             :      * Protect against code paths that may fail to initialize transition table
    2321             :      * info.
    2322             :      */
    2323             :     Assert(((TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||
    2324             :              TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event) ||
    2325             :              TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) &&
    2326             :             TRIGGER_FIRED_AFTER(trigdata->tg_event) &&
    2327             :             !(trigdata->tg_event & AFTER_TRIGGER_DEFERRABLE) &&
    2328             :             !(trigdata->tg_event & AFTER_TRIGGER_INITDEFERRED)) ||
    2329             :            (trigdata->tg_oldtable == NULL && trigdata->tg_newtable == NULL));
    2330             : 
    2331       20706 :     finfo += tgindx;
    2332             : 
    2333             :     /*
    2334             :      * We cache fmgr lookup info, to avoid making the lookup again on each
    2335             :      * call.
    2336             :      */
    2337       20706 :     if (finfo->fn_oid == InvalidOid)
    2338       17680 :         fmgr_info(trigdata->tg_trigger->tgfoid, finfo);
    2339             : 
    2340             :     Assert(finfo->fn_oid == trigdata->tg_trigger->tgfoid);
    2341             : 
    2342             :     /*
    2343             :      * If doing EXPLAIN ANALYZE, start charging time to this trigger.
    2344             :      */
    2345       20706 :     if (instr)
    2346           0 :         InstrStartNode(instr + tgindx);
    2347             : 
    2348             :     /*
    2349             :      * Do the function evaluation in the per-tuple memory context, so that
    2350             :      * leaked memory will be reclaimed once per tuple. Note in particular that
    2351             :      * any new tuple created by the trigger function will live till the end of
    2352             :      * the tuple cycle.
    2353             :      */
    2354       20706 :     oldContext = MemoryContextSwitchTo(per_tuple_context);
    2355             : 
    2356             :     /*
    2357             :      * Call the function, passing no arguments but setting a context.
    2358             :      */
    2359       20706 :     InitFunctionCallInfoData(*fcinfo, finfo, 0,
    2360             :                              InvalidOid, (Node *) trigdata, NULL);
    2361             : 
    2362       20706 :     pgstat_init_function_usage(fcinfo, &fcusage);
    2363             : 
    2364       20706 :     MyTriggerDepth++;
    2365       20706 :     PG_TRY();
    2366             :     {
    2367       20706 :         result = FunctionCallInvoke(fcinfo);
    2368             :     }
    2369        1164 :     PG_FINALLY();
    2370             :     {
    2371       20706 :         MyTriggerDepth--;
    2372             :     }
    2373       20706 :     PG_END_TRY();
    2374             : 
    2375       19542 :     pgstat_end_function_usage(&fcusage, true);
    2376             : 
    2377       19542 :     MemoryContextSwitchTo(oldContext);
    2378             : 
    2379             :     /*
    2380             :      * Trigger protocol allows function to return a null pointer, but NOT to
    2381             :      * set the isnull result flag.
    2382             :      */
    2383       19542 :     if (fcinfo->isnull)
    2384           0 :         ereport(ERROR,
    2385             :                 (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2386             :                  errmsg("trigger function %u returned null value",
    2387             :                         fcinfo->flinfo->fn_oid)));
    2388             : 
    2389             :     /*
    2390             :      * If doing EXPLAIN ANALYZE, stop charging time to this trigger, and count
    2391             :      * one "tuple returned" (really the number of firings).
    2392             :      */
    2393       19542 :     if (instr)
    2394           0 :         InstrStopNode(instr + tgindx, 1);
    2395             : 
    2396       19542 :     return (HeapTuple) DatumGetPointer(result);
    2397             : }
    2398             : 
    2399             : void
    2400      107948 : ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
    2401             : {
    2402             :     TriggerDesc *trigdesc;
    2403             :     int         i;
    2404      107948 :     TriggerData LocTriggerData = {0};
    2405             : 
    2406      107948 :     trigdesc = relinfo->ri_TrigDesc;
    2407             : 
    2408      107948 :     if (trigdesc == NULL)
    2409      107742 :         return;
    2410        6630 :     if (!trigdesc->trig_insert_before_statement)
    2411        6424 :         return;
    2412             : 
    2413             :     /* no-op if we already fired BS triggers in this context */
    2414         206 :     if (before_stmt_triggers_fired(RelationGetRelid(relinfo->ri_RelationDesc),
    2415             :                                    CMD_INSERT))
    2416           0 :         return;
    2417             : 
    2418         206 :     LocTriggerData.type = T_TriggerData;
    2419         206 :     LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
    2420             :         TRIGGER_EVENT_BEFORE;
    2421         206 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    2422        1754 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2423             :     {
    2424        1560 :         Trigger    *trigger = &trigdesc->triggers[i];
    2425             :         HeapTuple   newtuple;
    2426             : 
    2427        1560 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    2428             :                                   TRIGGER_TYPE_STATEMENT,
    2429             :                                   TRIGGER_TYPE_BEFORE,
    2430             :                                   TRIGGER_TYPE_INSERT))
    2431        1342 :             continue;
    2432         218 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    2433             :                             NULL, NULL, NULL))
    2434          30 :             continue;
    2435             : 
    2436         188 :         LocTriggerData.tg_trigger = trigger;
    2437         188 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    2438             :                                        i,
    2439             :                                        relinfo->ri_TrigFunctions,
    2440             :                                        relinfo->ri_TrigInstrument,
    2441         188 :                                        GetPerTupleMemoryContext(estate));
    2442             : 
    2443         176 :         if (newtuple)
    2444           0 :             ereport(ERROR,
    2445             :                     (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2446             :                      errmsg("BEFORE STATEMENT trigger cannot return a value")));
    2447             :     }
    2448             : }
    2449             : 
    2450             : void
    2451      105736 : ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo,
    2452             :                      TransitionCaptureState *transition_capture)
    2453             : {
    2454      105736 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2455             : 
    2456      105736 :     if (trigdesc && trigdesc->trig_insert_after_statement)
    2457         418 :         AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
    2458             :                               TRIGGER_EVENT_INSERT,
    2459             :                               false, NULL, NULL, NIL, NULL, transition_capture,
    2460             :                               false);
    2461      105736 : }
    2462             : 
    2463             : bool
    2464        2316 : ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo,
    2465             :                      TupleTableSlot *slot)
    2466             : {
    2467        2316 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2468        2316 :     HeapTuple   newtuple = NULL;
    2469             :     bool        should_free;
    2470        2316 :     TriggerData LocTriggerData = {0};
    2471             :     int         i;
    2472             : 
    2473        2316 :     LocTriggerData.type = T_TriggerData;
    2474        2316 :     LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
    2475             :         TRIGGER_EVENT_ROW |
    2476             :         TRIGGER_EVENT_BEFORE;
    2477        2316 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    2478       10826 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2479             :     {
    2480        8778 :         Trigger    *trigger = &trigdesc->triggers[i];
    2481             :         HeapTuple   oldtuple;
    2482             : 
    2483        8778 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    2484             :                                   TRIGGER_TYPE_ROW,
    2485             :                                   TRIGGER_TYPE_BEFORE,
    2486             :                                   TRIGGER_TYPE_INSERT))
    2487        4166 :             continue;
    2488        4612 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    2489             :                             NULL, NULL, slot))
    2490          50 :             continue;
    2491             : 
    2492        4562 :         if (!newtuple)
    2493        2282 :             newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
    2494             : 
    2495        4562 :         LocTriggerData.tg_trigslot = slot;
    2496        4562 :         LocTriggerData.tg_trigtuple = oldtuple = newtuple;
    2497        4562 :         LocTriggerData.tg_trigger = trigger;
    2498        4562 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    2499             :                                        i,
    2500             :                                        relinfo->ri_TrigFunctions,
    2501             :                                        relinfo->ri_TrigInstrument,
    2502        4562 :                                        GetPerTupleMemoryContext(estate));
    2503        4470 :         if (newtuple == NULL)
    2504             :         {
    2505         152 :             if (should_free)
    2506           2 :                 heap_freetuple(oldtuple);
    2507         152 :             return false;       /* "do nothing" */
    2508             :         }
    2509        4318 :         else if (newtuple != oldtuple)
    2510             :         {
    2511         746 :             ExecForceStoreHeapTuple(newtuple, slot, false);
    2512             : 
    2513             :             /*
    2514             :              * After a tuple in a partition goes through a trigger, the user
    2515             :              * could have changed the partition key enough that the tuple no
    2516             :              * longer fits the partition.  Verify that.
    2517             :              */
    2518         746 :             if (trigger->tgisclone &&
    2519          66 :                 !ExecPartitionCheck(relinfo, slot, estate, false))
    2520          24 :                 ereport(ERROR,
    2521             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2522             :                          errmsg("moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported"),
    2523             :                          errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
    2524             :                                    trigger->tgname,
    2525             :                                    get_namespace_name(RelationGetNamespace(relinfo->ri_RelationDesc)),
    2526             :                                    RelationGetRelationName(relinfo->ri_RelationDesc))));
    2527             : 
    2528         722 :             if (should_free)
    2529          40 :                 heap_freetuple(oldtuple);
    2530             : 
    2531             :             /* signal tuple should be re-fetched if used */
    2532         722 :             newtuple = NULL;
    2533             :         }
    2534             :     }
    2535             : 
    2536        2048 :     return true;
    2537             : }
    2538             : 
    2539             : void
    2540    12391450 : ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo,
    2541             :                      TupleTableSlot *slot, List *recheckIndexes,
    2542             :                      TransitionCaptureState *transition_capture)
    2543             : {
    2544    12391450 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2545             : 
    2546    12391450 :     if ((trigdesc && trigdesc->trig_insert_after_row) ||
    2547       60300 :         (transition_capture && transition_capture->tcs_insert_new_table))
    2548       65176 :         AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
    2549             :                               TRIGGER_EVENT_INSERT,
    2550             :                               true, NULL, slot,
    2551             :                               recheckIndexes, NULL,
    2552             :                               transition_capture,
    2553             :                               false);
    2554    12391450 : }
    2555             : 
    2556             : bool
    2557         150 : ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo,
    2558             :                      TupleTableSlot *slot)
    2559             : {
    2560         150 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2561         150 :     HeapTuple   newtuple = NULL;
    2562             :     bool        should_free;
    2563         150 :     TriggerData LocTriggerData = {0};
    2564             :     int         i;
    2565             : 
    2566         150 :     LocTriggerData.type = T_TriggerData;
    2567         150 :     LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
    2568             :         TRIGGER_EVENT_ROW |
    2569             :         TRIGGER_EVENT_INSTEAD;
    2570         150 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    2571         462 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2572             :     {
    2573         330 :         Trigger    *trigger = &trigdesc->triggers[i];
    2574             :         HeapTuple   oldtuple;
    2575             : 
    2576         330 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    2577             :                                   TRIGGER_TYPE_ROW,
    2578             :                                   TRIGGER_TYPE_INSTEAD,
    2579             :                                   TRIGGER_TYPE_INSERT))
    2580         180 :             continue;
    2581         150 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    2582             :                             NULL, NULL, slot))
    2583           0 :             continue;
    2584             : 
    2585         150 :         if (!newtuple)
    2586         150 :             newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
    2587             : 
    2588         150 :         LocTriggerData.tg_trigslot = slot;
    2589         150 :         LocTriggerData.tg_trigtuple = oldtuple = newtuple;
    2590         150 :         LocTriggerData.tg_trigger = trigger;
    2591         150 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    2592             :                                        i,
    2593             :                                        relinfo->ri_TrigFunctions,
    2594             :                                        relinfo->ri_TrigInstrument,
    2595         150 :                                        GetPerTupleMemoryContext(estate));
    2596         150 :         if (newtuple == NULL)
    2597             :         {
    2598          18 :             if (should_free)
    2599          18 :                 heap_freetuple(oldtuple);
    2600          18 :             return false;       /* "do nothing" */
    2601             :         }
    2602         132 :         else if (newtuple != oldtuple)
    2603             :         {
    2604          36 :             ExecForceStoreHeapTuple(newtuple, slot, false);
    2605             : 
    2606          36 :             if (should_free)
    2607          36 :                 heap_freetuple(oldtuple);
    2608             : 
    2609             :             /* signal tuple should be re-fetched if used */
    2610          36 :             newtuple = NULL;
    2611             :         }
    2612             :     }
    2613             : 
    2614         132 :     return true;
    2615             : }
    2616             : 
    2617             : void
    2618       11954 : ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
    2619             : {
    2620             :     TriggerDesc *trigdesc;
    2621             :     int         i;
    2622       11954 :     TriggerData LocTriggerData = {0};
    2623             : 
    2624       11954 :     trigdesc = relinfo->ri_TrigDesc;
    2625             : 
    2626       11954 :     if (trigdesc == NULL)
    2627       11882 :         return;
    2628        1390 :     if (!trigdesc->trig_delete_before_statement)
    2629        1276 :         return;
    2630             : 
    2631             :     /* no-op if we already fired BS triggers in this context */
    2632         114 :     if (before_stmt_triggers_fired(RelationGetRelid(relinfo->ri_RelationDesc),
    2633             :                                    CMD_DELETE))
    2634          42 :         return;
    2635             : 
    2636          72 :     LocTriggerData.type = T_TriggerData;
    2637          72 :     LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
    2638             :         TRIGGER_EVENT_BEFORE;
    2639          72 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    2640         630 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2641             :     {
    2642         558 :         Trigger    *trigger = &trigdesc->triggers[i];
    2643             :         HeapTuple   newtuple;
    2644             : 
    2645         558 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    2646             :                                   TRIGGER_TYPE_STATEMENT,
    2647             :                                   TRIGGER_TYPE_BEFORE,
    2648             :                                   TRIGGER_TYPE_DELETE))
    2649         486 :             continue;
    2650          72 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    2651             :                             NULL, NULL, NULL))
    2652          12 :             continue;
    2653             : 
    2654          60 :         LocTriggerData.tg_trigger = trigger;
    2655          60 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    2656             :                                        i,
    2657             :                                        relinfo->ri_TrigFunctions,
    2658             :                                        relinfo->ri_TrigInstrument,
    2659          60 :                                        GetPerTupleMemoryContext(estate));
    2660             : 
    2661          60 :         if (newtuple)
    2662           0 :             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
    2669       11802 : ExecASDeleteTriggers(EState *estate, ResultRelInfo *relinfo,
    2670             :                      TransitionCaptureState *transition_capture)
    2671             : {
    2672       11802 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2673             : 
    2674       11802 :     if (trigdesc && trigdesc->trig_delete_after_statement)
    2675         224 :         AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
    2676             :                               TRIGGER_EVENT_DELETE,
    2677             :                               false, NULL, NULL, NIL, NULL, transition_capture,
    2678             :                               false);
    2679       11802 : }
    2680             : 
    2681             : /*
    2682             :  * Execute BEFORE ROW DELETE triggers.
    2683             :  *
    2684             :  * True indicates caller can proceed with the delete.  False indicates caller
    2685             :  * need to suppress the delete and additionally if requested, we need to pass
    2686             :  * back the concurrently updated tuple if any.
    2687             :  */
    2688             : bool
    2689         340 : ExecBRDeleteTriggers(EState *estate, EPQState *epqstate,
    2690             :                      ResultRelInfo *relinfo,
    2691             :                      ItemPointer tupleid,
    2692             :                      HeapTuple fdw_trigtuple,
    2693             :                      TupleTableSlot **epqslot,
    2694             :                      TM_Result *tmresult,
    2695             :                      TM_FailureData *tmfd)
    2696             : {
    2697         340 :     TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
    2698         340 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2699         340 :     bool        result = true;
    2700         340 :     TriggerData LocTriggerData = {0};
    2701             :     HeapTuple   trigtuple;
    2702         340 :     bool        should_free = false;
    2703             :     int         i;
    2704             : 
    2705             :     Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
    2706         340 :     if (fdw_trigtuple == NULL)
    2707             :     {
    2708         324 :         TupleTableSlot *epqslot_candidate = NULL;
    2709             : 
    2710         324 :         if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
    2711             :                                 LockTupleExclusive, slot, &epqslot_candidate,
    2712             :                                 tmresult, tmfd))
    2713          12 :             return false;
    2714             : 
    2715             :         /*
    2716             :          * If the tuple was concurrently updated and the caller of this
    2717             :          * function requested for the updated tuple, skip the trigger
    2718             :          * execution.
    2719             :          */
    2720         308 :         if (epqslot_candidate != NULL && epqslot != NULL)
    2721             :         {
    2722           2 :             *epqslot = epqslot_candidate;
    2723           2 :             return false;
    2724             :         }
    2725             : 
    2726         306 :         trigtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
    2727             :     }
    2728             :     else
    2729             :     {
    2730          16 :         trigtuple = fdw_trigtuple;
    2731          16 :         ExecForceStoreHeapTuple(trigtuple, slot, false);
    2732             :     }
    2733             : 
    2734         322 :     LocTriggerData.type = T_TriggerData;
    2735         322 :     LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
    2736             :         TRIGGER_EVENT_ROW |
    2737             :         TRIGGER_EVENT_BEFORE;
    2738         322 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    2739        1144 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2740             :     {
    2741             :         HeapTuple   newtuple;
    2742         878 :         Trigger    *trigger = &trigdesc->triggers[i];
    2743             : 
    2744         878 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    2745             :                                   TRIGGER_TYPE_ROW,
    2746             :                                   TRIGGER_TYPE_BEFORE,
    2747             :                                   TRIGGER_TYPE_DELETE))
    2748         550 :             continue;
    2749         328 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    2750             :                             NULL, slot, NULL))
    2751          14 :             continue;
    2752             : 
    2753         314 :         LocTriggerData.tg_trigslot = slot;
    2754         314 :         LocTriggerData.tg_trigtuple = trigtuple;
    2755         314 :         LocTriggerData.tg_trigger = trigger;
    2756         314 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    2757             :                                        i,
    2758             :                                        relinfo->ri_TrigFunctions,
    2759             :                                        relinfo->ri_TrigInstrument,
    2760         314 :                                        GetPerTupleMemoryContext(estate));
    2761         286 :         if (newtuple == NULL)
    2762             :         {
    2763          28 :             result = false;     /* tell caller to suppress delete */
    2764          28 :             break;
    2765             :         }
    2766         258 :         if (newtuple != trigtuple)
    2767          56 :             heap_freetuple(newtuple);
    2768             :     }
    2769         294 :     if (should_free)
    2770           0 :         heap_freetuple(trigtuple);
    2771             : 
    2772         294 :     return result;
    2773             : }
    2774             : 
    2775             : /*
    2776             :  * Note: is_crosspart_update must be true if the DELETE is being performed
    2777             :  * as part of a cross-partition update.
    2778             :  */
    2779             : void
    2780     1767794 : ExecARDeleteTriggers(EState *estate,
    2781             :                      ResultRelInfo *relinfo,
    2782             :                      ItemPointer tupleid,
    2783             :                      HeapTuple fdw_trigtuple,
    2784             :                      TransitionCaptureState *transition_capture,
    2785             :                      bool is_crosspart_update)
    2786             : {
    2787     1767794 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2788             : 
    2789     1767794 :     if ((trigdesc && trigdesc->trig_delete_after_row) ||
    2790        4998 :         (transition_capture && transition_capture->tcs_delete_old_table))
    2791             :     {
    2792        5986 :         TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
    2793             : 
    2794             :         Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
    2795        5986 :         if (fdw_trigtuple == NULL)
    2796        5970 :             GetTupleForTrigger(estate,
    2797             :                                NULL,
    2798             :                                relinfo,
    2799             :                                tupleid,
    2800             :                                LockTupleExclusive,
    2801             :                                slot,
    2802             :                                NULL,
    2803             :                                NULL,
    2804             :                                NULL);
    2805             :         else
    2806          16 :             ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
    2807             : 
    2808        5986 :         AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
    2809             :                               TRIGGER_EVENT_DELETE,
    2810             :                               true, slot, NULL, NIL, NULL,
    2811             :                               transition_capture,
    2812             :                               is_crosspart_update);
    2813             :     }
    2814     1767794 : }
    2815             : 
    2816             : bool
    2817          54 : ExecIRDeleteTriggers(EState *estate, ResultRelInfo *relinfo,
    2818             :                      HeapTuple trigtuple)
    2819             : {
    2820          54 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2821          54 :     TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
    2822          54 :     TriggerData LocTriggerData = {0};
    2823             :     int         i;
    2824             : 
    2825          54 :     LocTriggerData.type = T_TriggerData;
    2826          54 :     LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
    2827             :         TRIGGER_EVENT_ROW |
    2828             :         TRIGGER_EVENT_INSTEAD;
    2829          54 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    2830             : 
    2831          54 :     ExecForceStoreHeapTuple(trigtuple, slot, false);
    2832             : 
    2833         330 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2834             :     {
    2835             :         HeapTuple   rettuple;
    2836         282 :         Trigger    *trigger = &trigdesc->triggers[i];
    2837             : 
    2838         282 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    2839             :                                   TRIGGER_TYPE_ROW,
    2840             :                                   TRIGGER_TYPE_INSTEAD,
    2841             :                                   TRIGGER_TYPE_DELETE))
    2842         228 :             continue;
    2843          54 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    2844             :                             NULL, slot, NULL))
    2845           0 :             continue;
    2846             : 
    2847          54 :         LocTriggerData.tg_trigslot = slot;
    2848          54 :         LocTriggerData.tg_trigtuple = trigtuple;
    2849          54 :         LocTriggerData.tg_trigger = trigger;
    2850          54 :         rettuple = ExecCallTriggerFunc(&LocTriggerData,
    2851             :                                        i,
    2852             :                                        relinfo->ri_TrigFunctions,
    2853             :                                        relinfo->ri_TrigInstrument,
    2854          54 :                                        GetPerTupleMemoryContext(estate));
    2855          54 :         if (rettuple == NULL)
    2856           6 :             return false;       /* Delete was suppressed */
    2857          48 :         if (rettuple != trigtuple)
    2858           0 :             heap_freetuple(rettuple);
    2859             :     }
    2860          48 :     return true;
    2861             : }
    2862             : 
    2863             : void
    2864       16798 : ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
    2865             : {
    2866             :     TriggerDesc *trigdesc;
    2867             :     int         i;
    2868       16798 :     TriggerData LocTriggerData = {0};
    2869             :     Bitmapset  *updatedCols;
    2870             : 
    2871       16798 :     trigdesc = relinfo->ri_TrigDesc;
    2872             : 
    2873       16798 :     if (trigdesc == NULL)
    2874       16644 :         return;
    2875        3700 :     if (!trigdesc->trig_update_before_statement)
    2876        3546 :         return;
    2877             : 
    2878             :     /* no-op if we already fired BS triggers in this context */
    2879         154 :     if (before_stmt_triggers_fired(RelationGetRelid(relinfo->ri_RelationDesc),
    2880             :                                    CMD_UPDATE))
    2881           0 :         return;
    2882             : 
    2883             :     /* statement-level triggers operate on the parent table */
    2884             :     Assert(relinfo->ri_RootResultRelInfo == NULL);
    2885             : 
    2886         154 :     updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
    2887             : 
    2888         154 :     LocTriggerData.type = T_TriggerData;
    2889         154 :     LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
    2890             :         TRIGGER_EVENT_BEFORE;
    2891         154 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    2892         154 :     LocTriggerData.tg_updatedcols = updatedCols;
    2893        1450 :     for (i = 0; i < trigdesc->numtriggers; i++)
    2894             :     {
    2895        1296 :         Trigger    *trigger = &trigdesc->triggers[i];
    2896             :         HeapTuple   newtuple;
    2897             : 
    2898        1296 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    2899             :                                   TRIGGER_TYPE_STATEMENT,
    2900             :                                   TRIGGER_TYPE_BEFORE,
    2901             :                                   TRIGGER_TYPE_UPDATE))
    2902        1142 :             continue;
    2903         154 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    2904             :                             updatedCols, NULL, NULL))
    2905           6 :             continue;
    2906             : 
    2907         148 :         LocTriggerData.tg_trigger = trigger;
    2908         148 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    2909             :                                        i,
    2910             :                                        relinfo->ri_TrigFunctions,
    2911             :                                        relinfo->ri_TrigInstrument,
    2912         148 :                                        GetPerTupleMemoryContext(estate));
    2913             : 
    2914         148 :         if (newtuple)
    2915           0 :             ereport(ERROR,
    2916             :                     (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    2917             :                      errmsg("BEFORE STATEMENT trigger cannot return a value")));
    2918             :     }
    2919             : }
    2920             : 
    2921             : void
    2922       16080 : ExecASUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
    2923             :                      TransitionCaptureState *transition_capture)
    2924             : {
    2925       16080 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2926             : 
    2927             :     /* statement-level triggers operate on the parent table */
    2928             :     Assert(relinfo->ri_RootResultRelInfo == NULL);
    2929             : 
    2930       16080 :     if (trigdesc && trigdesc->trig_update_after_statement)
    2931         378 :         AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
    2932             :                               TRIGGER_EVENT_UPDATE,
    2933             :                               false, NULL, NULL, NIL,
    2934             :                               ExecGetAllUpdatedCols(relinfo, estate),
    2935             :                               transition_capture,
    2936             :                               false);
    2937       16080 : }
    2938             : 
    2939             : bool
    2940        2536 : ExecBRUpdateTriggers(EState *estate, EPQState *epqstate,
    2941             :                      ResultRelInfo *relinfo,
    2942             :                      ItemPointer tupleid,
    2943             :                      HeapTuple fdw_trigtuple,
    2944             :                      TupleTableSlot *newslot,
    2945             :                      TM_Result *tmresult,
    2946             :                      TM_FailureData *tmfd)
    2947             : {
    2948        2536 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    2949        2536 :     TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
    2950        2536 :     HeapTuple   newtuple = NULL;
    2951             :     HeapTuple   trigtuple;
    2952        2536 :     bool        should_free_trig = false;
    2953        2536 :     bool        should_free_new = false;
    2954        2536 :     TriggerData LocTriggerData = {0};
    2955             :     int         i;
    2956             :     Bitmapset  *updatedCols;
    2957             :     LockTupleMode lockmode;
    2958             : 
    2959             :     /* Determine lock mode to use */
    2960        2536 :     lockmode = ExecUpdateLockMode(estate, relinfo);
    2961             : 
    2962             :     Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
    2963        2536 :     if (fdw_trigtuple == NULL)
    2964             :     {
    2965        2498 :         TupleTableSlot *epqslot_candidate = NULL;
    2966             : 
    2967             :         /* get a copy of the on-disk tuple we are planning to update */
    2968        2498 :         if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
    2969             :                                 lockmode, oldslot, &epqslot_candidate,
    2970             :                                 tmresult, tmfd))
    2971          22 :             return false;       /* cancel the update action */
    2972             : 
    2973             :         /*
    2974             :          * In READ COMMITTED isolation level it's possible that target tuple
    2975             :          * was changed due to concurrent update.  In that case we have a raw
    2976             :          * subplan output tuple in epqslot_candidate, and need to form a new
    2977             :          * insertable tuple using ExecGetUpdateNewTuple to replace the one we
    2978             :          * received in newslot.  Neither we nor our callers have any further
    2979             :          * interest in the passed-in tuple, so it's okay to overwrite newslot
    2980             :          * with the newer data.
    2981             :          *
    2982             :          * (Typically, newslot was also generated by ExecGetUpdateNewTuple, so
    2983             :          * that epqslot_clean will be that same slot and the copy step below
    2984             :          * is not needed.)
    2985             :          */
    2986        2468 :         if (epqslot_candidate != NULL)
    2987             :         {
    2988             :             TupleTableSlot *epqslot_clean;
    2989             : 
    2990           6 :             epqslot_clean = ExecGetUpdateNewTuple(relinfo, epqslot_candidate,
    2991             :                                                   oldslot);
    2992             : 
    2993           6 :             if (newslot != epqslot_clean)
    2994           0 :                 ExecCopySlot(newslot, epqslot_clean);
    2995             :         }
    2996             : 
    2997        2468 :         trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
    2998             :     }
    2999             :     else
    3000             :     {
    3001          38 :         ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
    3002          38 :         trigtuple = fdw_trigtuple;
    3003             :     }
    3004             : 
    3005        2506 :     LocTriggerData.type = T_TriggerData;
    3006        2506 :     LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
    3007             :         TRIGGER_EVENT_ROW |
    3008             :         TRIGGER_EVENT_BEFORE;
    3009        2506 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    3010        2506 :     updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
    3011        2506 :     LocTriggerData.tg_updatedcols = updatedCols;
    3012       11164 :     for (i = 0; i < trigdesc->numtriggers; i++)
    3013             :     {
    3014        8824 :         Trigger    *trigger = &trigdesc->triggers[i];
    3015             :         HeapTuple   oldtuple;
    3016             : 
    3017        8824 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    3018             :                                   TRIGGER_TYPE_ROW,
    3019             :                                   TRIGGER_TYPE_BEFORE,
    3020             :                                   TRIGGER_TYPE_UPDATE))
    3021        4234 :             continue;
    3022        4590 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    3023             :                             updatedCols, oldslot, newslot))
    3024          86 :             continue;
    3025             : 
    3026        4504 :         if (!newtuple)
    3027        2512 :             newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
    3028             : 
    3029        4504 :         LocTriggerData.tg_trigslot = oldslot;
    3030        4504 :         LocTriggerData.tg_trigtuple = trigtuple;
    3031        4504 :         LocTriggerData.tg_newtuple = oldtuple = newtuple;
    3032        4504 :         LocTriggerData.tg_newslot = newslot;
    3033        4504 :         LocTriggerData.tg_trigger = trigger;
    3034        4504 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    3035             :                                        i,
    3036             :                                        relinfo->ri_TrigFunctions,
    3037             :                                        relinfo->ri_TrigInstrument,
    3038        4504 :                                        GetPerTupleMemoryContext(estate));
    3039             : 
    3040        4476 :         if (newtuple == NULL)
    3041             :         {
    3042         138 :             if (should_free_trig)
    3043           0 :                 heap_freetuple(trigtuple);
    3044         138 :             if (should_free_new)
    3045           4 :                 heap_freetuple(oldtuple);
    3046         138 :             return false;       /* "do nothing" */
    3047             :         }
    3048        4338 :         else if (newtuple != oldtuple)
    3049             :         {
    3050        1292 :             ExecForceStoreHeapTuple(newtuple, newslot, false);
    3051             : 
    3052             :             /*
    3053             :              * If the tuple returned by the trigger / being stored, is the old
    3054             :              * row version, and the heap tuple passed to the trigger was
    3055             :              * allocated locally, materialize the slot. Otherwise we might
    3056             :              * free it while still referenced by the slot.
    3057             :              */
    3058        1292 :             if (should_free_trig && newtuple == trigtuple)
    3059           0 :                 ExecMaterializeSlot(newslot);
    3060             : 
    3061        1292 :             if (should_free_new)
    3062           2 :                 heap_freetuple(oldtuple);
    3063             : 
    3064             :             /* signal tuple should be re-fetched if used */
    3065        1292 :             newtuple = NULL;
    3066             :         }
    3067             :     }
    3068        2340 :     if (should_free_trig)
    3069           0 :         heap_freetuple(trigtuple);
    3070             : 
    3071        2340 :     return true;
    3072             : }
    3073             : 
    3074             : /*
    3075             :  * Note: 'src_partinfo' and 'dst_partinfo', when non-NULL, refer to the source
    3076             :  * and destination partitions, respectively, of a cross-partition update of
    3077             :  * the root partitioned table mentioned in the query, given by 'relinfo'.
    3078             :  * 'tupleid' in that case refers to the ctid of the "old" tuple in the source
    3079             :  * partition, and 'newslot' contains the "new" tuple in the destination
    3080             :  * partition.  This interface allows to support the requirements of
    3081             :  * ExecCrossPartitionUpdateForeignKey(); is_crosspart_update must be true in
    3082             :  * that case.
    3083             :  */
    3084             : void
    3085      436022 : ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
    3086             :                      ResultRelInfo *src_partinfo,
    3087             :                      ResultRelInfo *dst_partinfo,
    3088             :                      ItemPointer tupleid,
    3089             :                      HeapTuple fdw_trigtuple,
    3090             :                      TupleTableSlot *newslot,
    3091             :                      List *recheckIndexes,
    3092             :                      TransitionCaptureState *transition_capture,
    3093             :                      bool is_crosspart_update)
    3094             : {
    3095      436022 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    3096             : 
    3097      436022 :     if ((trigdesc && trigdesc->trig_update_after_row) ||
    3098         360 :         (transition_capture &&
    3099         360 :          (transition_capture->tcs_update_old_table ||
    3100          12 :           transition_capture->tcs_update_new_table)))
    3101             :     {
    3102             :         /*
    3103             :          * Note: if the UPDATE is converted into a DELETE+INSERT as part of
    3104             :          * update-partition-key operation, then this function is also called
    3105             :          * separately for DELETE and INSERT to capture transition table rows.
    3106             :          * In such case, either old tuple or new tuple can be NULL.
    3107             :          */
    3108             :         TupleTableSlot *oldslot;
    3109             :         ResultRelInfo *tupsrc;
    3110             : 
    3111             :         Assert((src_partinfo != NULL && dst_partinfo != NULL) ||
    3112             :                !is_crosspart_update);
    3113             : 
    3114        3328 :         tupsrc = src_partinfo ? src_partinfo : relinfo;
    3115        3328 :         oldslot = ExecGetTriggerOldSlot(estate, tupsrc);
    3116             : 
    3117        3328 :         if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
    3118        3266 :             GetTupleForTrigger(estate,
    3119             :                                NULL,
    3120             :                                tupsrc,
    3121             :                                tupleid,
    3122             :                                LockTupleExclusive,
    3123             :                                oldslot,
    3124             :                                NULL,
    3125             :                                NULL,
    3126             :                                NULL);
    3127          62 :         else if (fdw_trigtuple != NULL)
    3128          20 :             ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
    3129             :         else
    3130          42 :             ExecClearTuple(oldslot);
    3131             : 
    3132        3328 :         AfterTriggerSaveEvent(estate, relinfo,
    3133             :                               src_partinfo, dst_partinfo,
    3134             :                               TRIGGER_EVENT_UPDATE,
    3135             :                               true,
    3136             :                               oldslot, newslot, recheckIndexes,
    3137             :                               ExecGetAllUpdatedCols(relinfo, estate),
    3138             :                               transition_capture,
    3139             :                               is_crosspart_update);
    3140             :     }
    3141      436022 : }
    3142             : 
    3143             : bool
    3144         114 : ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
    3145             :                      HeapTuple trigtuple, TupleTableSlot *newslot)
    3146             : {
    3147         114 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    3148         114 :     TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
    3149         114 :     HeapTuple   newtuple = NULL;
    3150             :     bool        should_free;
    3151         114 :     TriggerData LocTriggerData = {0};
    3152             :     int         i;
    3153             : 
    3154         114 :     LocTriggerData.type = T_TriggerData;
    3155         114 :     LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
    3156             :         TRIGGER_EVENT_ROW |
    3157             :         TRIGGER_EVENT_INSTEAD;
    3158         114 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    3159             : 
    3160         114 :     ExecForceStoreHeapTuple(trigtuple, oldslot, false);
    3161             : 
    3162         528 :     for (i = 0; i < trigdesc->numtriggers; i++)
    3163             :     {
    3164         438 :         Trigger    *trigger = &trigdesc->triggers[i];
    3165             :         HeapTuple   oldtuple;
    3166             : 
    3167         438 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    3168             :                                   TRIGGER_TYPE_ROW,
    3169             :                                   TRIGGER_TYPE_INSTEAD,
    3170             :                                   TRIGGER_TYPE_UPDATE))
    3171         324 :             continue;
    3172         114 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    3173             :                             NULL, oldslot, newslot))
    3174           0 :             continue;
    3175             : 
    3176         114 :         if (!newtuple)
    3177         114 :             newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
    3178             : 
    3179         114 :         LocTriggerData.tg_trigslot = oldslot;
    3180         114 :         LocTriggerData.tg_trigtuple = trigtuple;
    3181         114 :         LocTriggerData.tg_newslot = newslot;
    3182         114 :         LocTriggerData.tg_newtuple = oldtuple = newtuple;
    3183             : 
    3184         114 :         LocTriggerData.tg_trigger = trigger;
    3185         114 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    3186             :                                        i,
    3187             :                                        relinfo->ri_TrigFunctions,
    3188             :                                        relinfo->ri_TrigInstrument,
    3189         114 :                                        GetPerTupleMemoryContext(estate));
    3190         108 :         if (newtuple == NULL)
    3191             :         {
    3192          18 :             return false;       /* "do nothing" */
    3193             :         }
    3194          90 :         else if (newtuple != oldtuple)
    3195             :         {
    3196          54 :             ExecForceStoreHeapTuple(newtuple, newslot, false);
    3197             : 
    3198          54 :             if (should_free)
    3199          54 :                 heap_freetuple(oldtuple);
    3200             : 
    3201             :             /* signal tuple should be re-fetched if used */
    3202          54 :             newtuple = NULL;
    3203             :         }
    3204             :     }
    3205             : 
    3206          90 :     return true;
    3207             : }
    3208             : 
    3209             : void
    3210        3120 : ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
    3211             : {
    3212             :     TriggerDesc *trigdesc;
    3213             :     int         i;
    3214        3120 :     TriggerData LocTriggerData = {0};
    3215             : 
    3216        3120 :     trigdesc = relinfo->ri_TrigDesc;
    3217             : 
    3218        3120 :     if (trigdesc == NULL)
    3219        3108 :         return;
    3220         516 :     if (!trigdesc->trig_truncate_before_statement)
    3221         504 :         return;
    3222             : 
    3223          12 :     LocTriggerData.type = T_TriggerData;
    3224          12 :     LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
    3225             :         TRIGGER_EVENT_BEFORE;
    3226          12 :     LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
    3227             : 
    3228          36 :     for (i = 0; i < trigdesc->numtriggers; i++)
    3229             :     {
    3230          24 :         Trigger    *trigger = &trigdesc->triggers[i];
    3231             :         HeapTuple   newtuple;
    3232             : 
    3233          24 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    3234             :                                   TRIGGER_TYPE_STATEMENT,
    3235             :                                   TRIGGER_TYPE_BEFORE,
    3236             :                                   TRIGGER_TYPE_TRUNCATE))
    3237          12 :             continue;
    3238          12 :         if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
    3239             :                             NULL, NULL, NULL))
    3240           0 :             continue;
    3241             : 
    3242          12 :         LocTriggerData.tg_trigger = trigger;
    3243          12 :         newtuple = ExecCallTriggerFunc(&LocTriggerData,
    3244             :                                        i,
    3245             :                                        relinfo->ri_TrigFunctions,
    3246             :                                        relinfo->ri_TrigInstrument,
    3247          12 :                                        GetPerTupleMemoryContext(estate));
    3248             : 
    3249          12 :         if (newtuple)
    3250           0 :             ereport(ERROR,
    3251             :                     (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
    3252             :                      errmsg("BEFORE STATEMENT trigger cannot return a value")));
    3253             :     }
    3254             : }
    3255             : 
    3256             : void
    3257        3112 : ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
    3258             : {
    3259        3112 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    3260             : 
    3261        3112 :     if (trigdesc && trigdesc->trig_truncate_after_statement)
    3262           8 :         AfterTriggerSaveEvent(estate, relinfo,
    3263             :                               NULL, NULL,
    3264             :                               TRIGGER_EVENT_TRUNCATE,
    3265             :                               false, NULL, NULL, NIL, NULL, NULL,
    3266             :                               false);
    3267        3112 : }
    3268             : 
    3269             : 
    3270             : /*
    3271             :  * Fetch tuple into "oldslot", dealing with locking and EPQ if necessary
    3272             :  */
    3273             : static bool
    3274       12058 : GetTupleForTrigger(EState *estate,
    3275             :                    EPQState *epqstate,
    3276             :                    ResultRelInfo *relinfo,
    3277             :                    ItemPointer tid,
    3278             :                    LockTupleMode lockmode,
    3279             :                    TupleTableSlot *oldslot,
    3280             :                    TupleTableSlot **epqslot,
    3281             :                    TM_Result *tmresultp,
    3282             :                    TM_FailureData *tmfdp)
    3283             : {
    3284       12058 :     Relation    relation = relinfo->ri_RelationDesc;
    3285             : 
    3286       12058 :     if (epqslot != NULL)
    3287             :     {
    3288             :         TM_Result   test;
    3289             :         TM_FailureData tmfd;
    3290        2822 :         int         lockflags = 0;
    3291             : 
    3292        2822 :         *epqslot = NULL;
    3293             : 
    3294             :         /* caller must pass an epqstate if EvalPlanQual is possible */
    3295             :         Assert(epqstate != NULL);
    3296             : 
    3297             :         /*
    3298             :          * lock tuple for update
    3299             :          */
    3300        2822 :         if (!IsolationUsesXactSnapshot())
    3301        1958 :             lockflags |= TUPLE_LOCK_FLAG_FIND_LAST_VERSION;
    3302        2822 :         test = table_tuple_lock(relation, tid, estate->es_snapshot, oldslot,
    3303             :                                 estate->es_output_cid,
    3304             :                                 lockmode, LockWaitBlock,
    3305             :                                 lockflags,
    3306             :                                 &tmfd);
    3307             : 
    3308             :         /* Let the caller know about the status of this operation */
    3309        2818 :         if (tmresultp)
    3310         102 :             *tmresultp = test;
    3311        2818 :         if (tmfdp)
    3312        2812 :             *tmfdp = tmfd;
    3313             : 
    3314        2818 :         switch (test)
    3315             :         {
    3316           6 :             case TM_SelfModified:
    3317             : 
    3318             :                 /*
    3319             :                  * The target tuple was already updated or deleted by the
    3320             :                  * current command, or by a later command in the current
    3321             :                  * transaction.  We ignore the tuple in the former case, and
    3322             :                  * throw error in the latter case, for the same reasons
    3323             :                  * enumerated in ExecUpdate and ExecDelete in
    3324             :                  * nodeModifyTable.c.
    3325             :                  */
    3326           6 :                 if (tmfd.cmax != estate->es_output_cid)
    3327           6 :                     ereport(ERROR,
    3328             :                             (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
    3329             :                              errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
    3330             :                              errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
    3331             : 
    3332             :                 /* treat it as deleted; do not process */
    3333          32 :                 return false;
    3334             : 
    3335        2794 :             case TM_Ok:
    3336        2794 :                 if (tmfd.traversed)
    3337             :                 {
    3338             :                     /*
    3339             :                      * Recheck the tuple using EPQ. For MERGE, we leave this
    3340             :                      * to the caller (it must do additional rechecking, and
    3341             :                      * might end up executing a different action entirely).
    3342             :                      */
    3343          26 :                     if (estate->es_plannedstmt->commandType == CMD_MERGE)
    3344             :                     {
    3345          14 :                         if (tmresultp)
    3346          14 :                             *tmresultp = TM_Updated;
    3347          14 :                         return false;
    3348             :                     }
    3349             : 
    3350          12 :                     *epqslot = EvalPlanQual(epqstate,
    3351             :                                             relation,
    3352             :                                             relinfo->ri_RangeTableIndex,
    3353             :                                             oldslot);
    3354             : 
    3355             :                     /*
    3356             :                      * If PlanQual failed for updated tuple - we must not
    3357             :                      * process this tuple!
    3358             :                      */
    3359          12 :                     if (TupIsNull(*epqslot))
    3360             :                     {
    3361           4 :                         *epqslot = NULL;
    3362           4 :                         return false;
    3363             :                     }
    3364             :                 }
    3365        2776 :                 break;
    3366             : 
    3367           2 :             case TM_Updated:
    3368           2 :                 if (IsolationUsesXactSnapshot())
    3369           2 :                     ereport(ERROR,
    3370             :                             (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3371             :                              errmsg("could not serialize access due to concurrent update")));
    3372           0 :                 elog(ERROR, "unexpected table_tuple_lock status: %u", test);
    3373             :                 break;
    3374             : 
    3375          16 :             case TM_Deleted:
    3376          16 :                 if (IsolationUsesXactSnapshot())
    3377           2 :                     ereport(ERROR,
    3378             :                             (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
    3379             :                              errmsg("could not serialize access due to concurrent delete")));
    3380             :                 /* tuple was deleted */
    3381          14 :                 return false;
    3382             : 
    3383           0 :             case TM_Invisible:
    3384           0 :                 elog(ERROR, "attempted to lock invisible tuple");
    3385             :                 break;
    3386             : 
    3387           0 :             default:
    3388           0 :                 elog(ERROR, "unrecognized table_tuple_lock status: %u", test);
    3389             :                 return false;   /* keep compiler quiet */
    3390             :         }
    3391             :     }
    3392             :     else
    3393             :     {
    3394             :         /*
    3395             :          * We expect the tuple to be present, thus very simple error handling
    3396             :          * suffices.
    3397             :          */
    3398        9236 :         if (!table_tuple_fetch_row_version(relation, tid, SnapshotAny,
    3399             :                                            oldslot))
    3400           0 :             elog(ERROR, "failed to fetch tuple for trigger");
    3401             :     }
    3402             : 
    3403       12012 :     return true;
    3404             : }
    3405             : 
    3406             : /*
    3407             :  * Is trigger enabled to fire?
    3408             :  */
    3409             : static bool
    3410       23124 : TriggerEnabled(EState *estate, ResultRelInfo *relinfo,
    3411             :                Trigger *trigger, TriggerEvent event,
    3412             :                Bitmapset *modifiedCols,
    3413             :                TupleTableSlot *oldslot, TupleTableSlot *newslot)
    3414             : {
    3415             :     /* Check replication-role-dependent enable state */
    3416       23124 :     if (SessionReplicationRole == SESSION_REPLICATION_ROLE_REPLICA)
    3417             :     {
    3418         126 :         if (trigger->tgenabled == TRIGGER_FIRES_ON_ORIGIN ||
    3419          78 :             trigger->tgenabled == TRIGGER_DISABLED)
    3420          84 :             return false;
    3421             :     }
    3422             :     else                        /* ORIGIN or LOCAL role */
    3423             :     {
    3424       22998 :         if (trigger->tgenabled == TRIGGER_FIRES_ON_REPLICA ||
    3425       22996 :             trigger->tgenabled == TRIGGER_DISABLED)
    3426         158 :             return false;
    3427             :     }
    3428             : 
    3429             :     /*
    3430             :      * Check for column-specific trigger (only possible for UPDATE, and in
    3431             :      * fact we *must* ignore tgattr for other event types)
    3432             :      */
    3433       22882 :     if (trigger->tgnattr > 0 && TRIGGER_FIRED_BY_UPDATE(event))
    3434             :     {
    3435             :         int         i;
    3436             :         bool        modified;
    3437             : 
    3438         424 :         modified = false;
    3439         556 :         for (i = 0; i < trigger->tgnattr; i++)
    3440             :         {
    3441         472 :             if (bms_is_member(trigger->tgattr[i] - FirstLowInvalidHeapAttributeNumber,
    3442             :                               modifiedCols))
    3443             :             {
    3444         340 :                 modified = true;
    3445         340 :                 break;
    3446             :             }
    3447             :         }
    3448         424 :         if (!modified)
    3449          84 :             return false;
    3450             :     }
    3451             : 
    3452             :     /* Check for WHEN clause */
    3453       22798 :     if (trigger->tgqual)
    3454             :     {
    3455             :         ExprState **predicate;
    3456             :         ExprContext *econtext;
    3457             :         MemoryContext oldContext;
    3458             :         int         i;
    3459             : 
    3460             :         Assert(estate != NULL);
    3461             : 
    3462             :         /*
    3463             :          * trigger is an element of relinfo->ri_TrigDesc->triggers[]; find the
    3464             :          * matching element of relinfo->ri_TrigWhenExprs[]
    3465             :          */
    3466         450 :         i = trigger - relinfo->ri_TrigDesc->triggers;
    3467         450 :         predicate = &relinfo->ri_TrigWhenExprs[i];
    3468             : 
    3469             :         /*
    3470             :          * If first time through for this WHEN expression, build expression
    3471             :          * nodetrees for it.  Keep them in the per-query memory context so
    3472             :          * they'll survive throughout the query.
    3473             :          */
    3474         450 :         if (*predicate == NULL)
    3475             :         {
    3476             :             Node       *tgqual;
    3477             : 
    3478         242 :             oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
    3479         242 :             tgqual = stringToNode(trigger->tgqual);
    3480             :             /* Change references to OLD and NEW to INNER_VAR and OUTER_VAR */
    3481         242 :             ChangeVarNodes(tgqual, PRS2_OLD_VARNO, INNER_VAR, 0);
    3482         242 :             ChangeVarNodes(tgqual, PRS2_NEW_VARNO, OUTER_VAR, 0);
    3483             :             /* ExecPrepareQual wants implicit-AND form */
    3484         242 :             tgqual = (Node *) make_ands_implicit((Expr *) tgqual);
    3485         242 :             *predicate = ExecPrepareQual((List *) tgqual, estate);
    3486         242 :             MemoryContextSwitchTo(oldContext);
    3487             :         }
    3488             : 
    3489             :         /*
    3490             :          * We will use the EState's per-tuple context for evaluating WHEN
    3491             :          * expressions (creating it if it's not already there).
    3492             :          */
    3493         450 :         econtext = GetPerTupleExprContext(estate);
    3494             : 
    3495             :         /*
    3496             :          * Finally evaluate the expression, making the old and/or new tuples
    3497             :          * available as INNER_VAR/OUTER_VAR respectively.
    3498             :          */
    3499         450 :         econtext->ecxt_innertuple = oldslot;
    3500         450 :         econtext->ecxt_outertuple = newslot;
    3501         450 :         if (!ExecQual(*predicate, econtext))
    3502         240 :             return false;
    3503             :     }
    3504             : 
    3505       22558 :     return true;
    3506             : }
    3507             : 
    3508             : 
    3509             : /* ----------
    3510             :  * After-trigger stuff
    3511             :  *
    3512             :  * The AfterTriggersData struct holds data about pending AFTER trigger events
    3513             :  * during the current transaction tree.  (BEFORE triggers are fired
    3514             :  * immediately so we don't need any persistent state about them.)  The struct
    3515             :  * and most of its subsidiary data are kept in TopTransactionContext; however
    3516             :  * some data that can be discarded sooner appears in the CurTransactionContext
    3517             :  * of the relevant subtransaction.  Also, the individual event records are
    3518             :  * kept in a separate sub-context of TopTransactionContext.  This is done
    3519             :  * mainly so that it's easy to tell from a memory context dump how much space
    3520             :  * is being eaten by trigger events.
    3521             :  *
    3522             :  * Because the list of pending events can grow large, we go to some
    3523             :  * considerable effort to minimize per-event memory consumption.  The event
    3524             :  * records are grouped into chunks and common data for similar events in the
    3525             :  * same chunk is only stored once.
    3526             :  *
    3527             :  * XXX We need to be able to save the per-event data in a file if it grows too
    3528             :  * large.
    3529             :  * ----------
    3530             :  */
    3531             : 
    3532             : /* Per-trigger SET CONSTRAINT status */
    3533             : typedef struct SetConstraintTriggerData
    3534             : {
    3535             :     Oid         sct_tgoid;
    3536             :     bool        sct_tgisdeferred;
    3537             : } SetConstraintTriggerData;
    3538             : 
    3539             : typedef struct SetConstraintTriggerData *SetConstraintTrigger;
    3540             : 
    3541             : /*
    3542             :  * SET CONSTRAINT intra-transaction status.
    3543             :  *
    3544             :  * We make this a single palloc'd object so it can be copied and freed easily.
    3545             :  *
    3546             :  * all_isset and all_isdeferred are used to keep track
    3547             :  * of SET CONSTRAINTS ALL {DEFERRED, IMMEDIATE}.
    3548             :  *
    3549             :  * trigstates[] stores per-trigger tgisdeferred settings.
    3550             :  */
    3551             : typedef struct SetConstraintStateData
    3552             : {
    3553             :     bool        all_isset;
    3554             :     bool        all_isdeferred;
    3555             :     int         numstates;      /* number of trigstates[] entries in use */
    3556             :     int         numalloc;       /* allocated size of trigstates[] */
    3557             :     SetConstraintTriggerData trigstates[FLEXIBLE_ARRAY_MEMBER];
    3558             : } SetConstraintStateData;
    3559             : 
    3560             : typedef SetConstraintStateData *SetConstraintState;
    3561             : 
    3562             : 
    3563             : /*
    3564             :  * Per-trigger-event data
    3565             :  *
    3566             :  * The actual per-event data, AfterTriggerEventData, includes DONE/IN_PROGRESS
    3567             :  * status bits, up to two tuple CTIDs, and optionally two OIDs of partitions.
    3568             :  * Each event record also has an associated AfterTriggerSharedData that is
    3569             :  * shared across all instances of similar events within a "chunk".
    3570             :  *
    3571             :  * For row-level triggers, we arrange not to waste storage on unneeded ctid
    3572             :  * fields.  Updates of regular tables use two; inserts and deletes of regular
    3573             :  * tables use one; foreign tables always use zero and save the tuple(s) to a
    3574             :  * tuplestore.  AFTER_TRIGGER_FDW_FETCH directs AfterTriggerExecute() to
    3575             :  * retrieve a fresh tuple or pair of tuples from that tuplestore, while
    3576             :  * AFTER_TRIGGER_FDW_REUSE directs it to use the most-recently-retrieved
    3577             :  * tuple(s).  This permits storing tuples once regardless of the number of
    3578             :  * row-level triggers on a foreign table.
    3579             :  *
    3580             :  * When updates on partitioned tables cause rows to move between partitions,
    3581             :  * the OIDs of both partitions are stored too, so that the tuples can be
    3582             :  * fetched; such entries are marked AFTER_TRIGGER_CP_UPDATE (for "cross-
    3583             :  * partition update").
    3584             :  *
    3585             :  * Note that we need triggers on foreign tables to be fired in exactly the
    3586             :  * order they were queued, so that the tuples come out of the tuplestore in
    3587             :  * the right order.  To ensure that, we forbid deferrable (constraint)
    3588             :  * triggers on foreign tables.  This also ensures that such triggers do not
    3589             :  * get deferred into outer trigger query levels, meaning that it's okay to
    3590             :  * destroy the tuplestore at the end of the query level.
    3591             :  *
    3592             :  * Statement-level triggers always bear AFTER_TRIGGER_1CTID, though they
    3593             :  * require no ctid field.  We lack the flag bit space to neatly represent that
    3594             :  * distinct case, and it seems unlikely to be worth much trouble.
    3595             :  *
    3596             :  * Note: ats_firing_id is initially zero and is set to something else when
    3597             :  * AFTER_TRIGGER_IN_PROGRESS is set.  It indicates which trigger firing
    3598             :  * cycle the trigger will be fired in (or was fired in, if DONE is set).
    3599             :  * Although this is mutable state, we can keep it in AfterTriggerSharedData
    3600             :  * because all instances of the same type of event in a given event list will
    3601             :  * be fired at the same time, if they were queued between the same firing
    3602             :  * cycles.  So we need only ensure that ats_firing_id is zero when attaching
    3603             :  * a new event to an existing AfterTriggerSharedData record.
    3604             :  */
    3605             : typedef uint32 TriggerFlags;
    3606             : 
    3607             : #define AFTER_TRIGGER_OFFSET            0x07FFFFFF  /* must be low-order bits */
    3608             : #define AFTER_TRIGGER_DONE              0x80000000
    3609             : #define AFTER_TRIGGER_IN_PROGRESS       0x40000000
    3610             : /* bits describing the size and tuple sources of this event */
    3611             : #define AFTER_TRIGGER_FDW_REUSE         0x00000000
    3612             : #define AFTER_TRIGGER_FDW_FETCH         0x20000000
    3613             : #define AFTER_TRIGGER_1CTID             0x10000000
    3614             : #define AFTER_TRIGGER_2CTID             0x30000000
    3615             : #define AFTER_TRIGGER_CP_UPDATE         0x08000000
    3616             : #define AFTER_TRIGGER_TUP_BITS          0x38000000
    3617             : typedef struct AfterTriggerSharedData *AfterTriggerShared;
    3618             : 
    3619             : typedef struct AfterTriggerSharedData
    3620             : {
    3621             :     TriggerEvent ats_event;     /* event type indicator, see trigger.h */
    3622             :     Oid         ats_tgoid;      /* the trigger's ID */
    3623             :     Oid         ats_relid;      /* the relation it's on */
    3624             :     CommandId   ats_firing_id;  /* ID for firing cycle */
    3625             :     struct AfterTriggersTableData *ats_table;   /* transition table access */
    3626             :     Bitmapset  *ats_modifiedcols;   /* modified columns */
    3627             : } AfterTriggerSharedData;
    3628             : 
    3629             : typedef struct AfterTriggerEventData *AfterTriggerEvent;
    3630             : 
    3631             : typedef struct AfterTriggerEventData
    3632             : {
    3633             :     TriggerFlags ate_flags;     /* status bits and offset to shared data */
    3634             :     ItemPointerData ate_ctid1;  /* inserted, deleted, or old updated tuple */
    3635             :     ItemPointerData ate_ctid2;  /* new updated tuple */
    3636             : 
    3637             :     /*
    3638             :      * During a cross-partition update of a partitioned table, we also store
    3639             :      * the OIDs of source and destination partitions that are needed to fetch
    3640             :      * the old (ctid1) and the new tuple (ctid2) from, respectively.
    3641             :      */
    3642             :     Oid         ate_src_part;
    3643             :     Oid         ate_dst_part;
    3644             : } AfterTriggerEventData;
    3645             : 
    3646             : /* AfterTriggerEventData, minus ate_src_part, ate_dst_part */
    3647             : typedef struct AfterTriggerEventDataNoOids
    3648             : {
    3649             :     TriggerFlags ate_flags;
    3650             :     ItemPointerData ate_ctid1;
    3651             :     ItemPointerData ate_ctid2;
    3652             : }           AfterTriggerEventDataNoOids;
    3653             : 
    3654             : /* AfterTriggerEventData, minus ate_*_part and ate_ctid2 */
    3655             : typedef struct AfterTriggerEventDataOneCtid
    3656             : {
    3657             :     TriggerFlags ate_flags;     /* status bits and offset to shared data */
    3658             :     ItemPointerData ate_ctid1;  /* inserted, deleted, or old updated tuple */
    3659             : }           AfterTriggerEventDataOneCtid;
    3660             : 
    3661             : /* AfterTriggerEventData, minus ate_*_part, ate_ctid1 and ate_ctid2 */
    3662             : typedef struct AfterTriggerEventDataZeroCtids
    3663             : {
    3664             :     TriggerFlags ate_flags;     /* status bits and offset to shared data */
    3665             : }           AfterTriggerEventDataZeroCtids;
    3666             : 
    3667             : #define SizeofTriggerEvent(evt) \
    3668             :     (((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_CP_UPDATE ? \
    3669             :      sizeof(AfterTriggerEventData) : \
    3670             :      (((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_2CTID ? \
    3671             :       sizeof(AfterTriggerEventDataNoOids) : \
    3672             :       (((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_1CTID ? \
    3673             :        sizeof(AfterTriggerEventDataOneCtid) : \
    3674             :        sizeof(AfterTriggerEventDataZeroCtids))))
    3675             : 
    3676             : #define GetTriggerSharedData(evt) \
    3677             :     ((AfterTriggerShared) ((char *) (evt) + ((evt)->ate_flags & AFTER_TRIGGER_OFFSET)))
    3678             : 
    3679             : /*
    3680             :  * To avoid palloc overhead, we keep trigger events in arrays in successively-
    3681             :  * larger chunks (a slightly more sophisticated version of an expansible
    3682             :  * array).  The space between CHUNK_DATA_START and freeptr is occupied by
    3683             :  * AfterTriggerEventData records; the space between endfree and endptr is
    3684             :  * occupied by AfterTriggerSharedData records.
    3685             :  */
    3686             : typedef struct AfterTriggerEventChunk
    3687             : {
    3688             :     struct AfterTriggerEventChunk *next;    /* list link */
    3689             :     char       *freeptr;        /* start of free space in chunk */
    3690             :     char       *endfree;        /* end of free space in chunk */
    3691             :     char       *endptr;         /* end of chunk */
    3692             :     /* event data follows here */
    3693             : } AfterTriggerEventChunk;
    3694             : 
    3695             : #define CHUNK_DATA_START(cptr) ((char *) (cptr) + MAXALIGN(sizeof(AfterTriggerEventChunk)))
    3696             : 
    3697             : /* A list of events */
    3698             : typedef struct AfterTriggerEventList
    3699             : {
    3700             :     AfterTriggerEventChunk *head;
    3701             :     AfterTriggerEventChunk *tail;
    3702             :     char       *tailfree;       /* freeptr of tail chunk */
    3703             : } AfterTriggerEventList;
    3704             : 
    3705             : /* Macros to help in iterating over a list of events */
    3706             : #define for_each_chunk(cptr, evtlist) \
    3707             :     for (cptr = (evtlist).head; cptr != NULL; cptr = cptr->next)
    3708             : #define for_each_event(eptr, cptr) \
    3709             :     for (eptr = (AfterTriggerEvent) CHUNK_DATA_START(cptr); \
    3710             :          (char *) eptr < (cptr)->freeptr; \
    3711             :          eptr = (AfterTriggerEvent) (((char *) eptr) + SizeofTriggerEvent(eptr)))
    3712             : /* Use this if no special per-chunk processing is needed */
    3713             : #define for_each_event_chunk(eptr, cptr, evtlist) \
    3714             :     for_each_chunk(cptr, evtlist) for_each_event(eptr, cptr)
    3715             : 
    3716             : /* Macros for iterating from a start point that might not be list start */
    3717             : #define for_each_chunk_from(cptr) \
    3718             :     for (; cptr != NULL; cptr = cptr->next)
    3719             : #define for_each_event_from(eptr, cptr) \
    3720             :     for (; \
    3721             :          (char *) eptr < (cptr)->freeptr; \
    3722             :          eptr = (AfterTriggerEvent) (((char *) eptr) + SizeofTriggerEvent(eptr)))
    3723             : 
    3724             : 
    3725             : /*
    3726             :  * All per-transaction data for the AFTER TRIGGERS module.
    3727             :  *
    3728             :  * AfterTriggersData has the following fields:
    3729             :  *
    3730             :  * firing_counter is incremented for each call of afterTriggerInvokeEvents.
    3731             :  * We mark firable events with the current firing cycle's ID so that we can
    3732             :  * tell which ones to work on.  This ensures sane behavior if a trigger
    3733             :  * function chooses to do SET CONSTRAINTS: the inner SET CONSTRAINTS will
    3734             :  * only fire those events that weren't already scheduled for firing.
    3735             :  *
    3736             :  * state keeps track of the transaction-local effects of SET CONSTRAINTS.
    3737             :  * This is saved and restored across failed subtransactions.
    3738             :  *
    3739             :  * events is the current list of deferred events.  This is global across
    3740             :  * all subtransactions of the current transaction.  In a subtransaction
    3741             :  * abort, we know that the events added by the subtransaction are at the
    3742             :  * end of the list, so it is relatively easy to discard them.  The event
    3743             :  * list chunks themselves are stored in event_cxt.
    3744             :  *
    3745             :  * query_depth is the current depth of nested AfterTriggerBeginQuery calls
    3746             :  * (-1 when the stack is empty).
    3747             :  *
    3748             :  * query_stack[query_depth] is the per-query-level data, including these fields:
    3749             :  *
    3750             :  * events is a list of AFTER trigger events queued by the current query.
    3751             :  * None of these are valid until the matching AfterTriggerEndQuery call
    3752             :  * occurs.  At that point we fire immediate-mode triggers, and append any
    3753             :  * deferred events to the main events list.
    3754             :  *
    3755             :  * fdw_tuplestore is a tuplestore containing the foreign-table tuples
    3756             :  * needed by events queued by the current query.  (Note: we use just one
    3757             :  * tuplestore even though more than one foreign table might be involved.
    3758             :  * This is okay because tuplestores don't really care what's in the tuples
    3759             :  * they store; but it's possible that someday it'd break.)
    3760             :  *
    3761             :  * tables is a List of AfterTriggersTableData structs for target tables
    3762             :  * of the current query (see below).
    3763             :  *
    3764             :  * maxquerydepth is just the allocated length of query_stack.
    3765             :  *
    3766             :  * trans_stack holds per-subtransaction data, including these fields:
    3767             :  *
    3768             :  * state is NULL or a pointer to a saved copy of the SET CONSTRAINTS
    3769             :  * state data.  Each subtransaction level that modifies that state first
    3770             :  * saves a copy, which we use to restore the state if we abort.
    3771             :  *
    3772             :  * events is a copy of the events head/tail pointers,
    3773             :  * which we use to restore those values during subtransaction abort.
    3774             :  *
    3775             :  * query_depth is the subtransaction-start-time value of query_depth,
    3776             :  * which we similarly use to clean up at subtransaction abort.
    3777             :  *
    3778             :  * firing_counter is the subtransaction-start-time value of firing_counter.
    3779             :  * We use this to recognize which deferred triggers were fired (or marked
    3780             :  * for firing) within an aborted subtransaction.
    3781             :  *
    3782             :  * We use GetCurrentTransactionNestLevel() to determine the correct array
    3783             :  * index in trans_stack.  maxtransdepth is the number of allocated entries in
    3784             :  * trans_stack.  (By not keeping our own stack pointer, we can avoid trouble
    3785             :  * in cases where errors during subxact abort cause multiple invocations
    3786             :  * of AfterTriggerEndSubXact() at the same nesting depth.)
    3787             :  *
    3788             :  * We create an AfterTriggersTableData struct for each target table of the
    3789             :  * current query, and each operation mode (INSERT/UPDATE/DELETE), that has
    3790             :  * either transition tables or statement-level triggers.  This is used to
    3791             :  * hold the relevant transition tables, as well as info tracking whether
    3792             :  * we already queued the statement triggers.  (We use that info to prevent
    3793             :  * firing the same statement triggers more than once per statement, or really
    3794             :  * once per transition table set.)  These structs, along with the transition
    3795             :  * table tuplestores, live in the (sub)transaction's CurTransactionContext.
    3796             :  * That's sufficient lifespan because we don't allow transition tables to be
    3797             :  * used by deferrable triggers, so they only need to survive until
    3798             :  * AfterTriggerEndQuery.
    3799             :  */
    3800             : typedef struct AfterTriggersQueryData AfterTriggersQueryData;
    3801             : typedef struct AfterTriggersTransData AfterTriggersTransData;
    3802             : typedef struct AfterTriggersTableData AfterTriggersTableData;
    3803             : 
    3804             : typedef struct AfterTriggersData
    3805             : {
    3806             :     CommandId   firing_counter; /* next firing ID to assign */
    3807             :     SetConstraintState state;   /* the active S C state */
    3808             :     AfterTriggerEventList events;   /* deferred-event list */
    3809             :     MemoryContext event_cxt;    /* memory context for events, if any */
    3810             : 
    3811             :     /* per-query-level data: */
    3812             :     AfterTriggersQueryData *query_stack;    /* array of structs shown below */
    3813             :     int         query_depth;    /* current index in above array */
    3814             :     int         maxquerydepth;  /* allocated len of above array */
    3815             : 
    3816             :     /* per-subtransaction-level data: */
    3817             :     AfterTriggersTransData *trans_stack;    /* array of structs shown below */
    3818             :     int         maxtransdepth;  /* allocated len of above array */
    3819             : } AfterTriggersData;
    3820             : 
    3821             : struct AfterTriggersQueryData
    3822             : {
    3823             :     AfterTriggerEventList events;   /* events pending from this query */
    3824             :     Tuplestorestate *fdw_tuplestore;    /* foreign tuples for said events */
    3825             :     List       *tables;         /* list of AfterTriggersTableData, see below */
    3826             : };
    3827             : 
    3828             : struct AfterTriggersTransData
    3829             : {
    3830             :     /* these fields are just for resetting at subtrans abort: */
    3831             :     SetConstraintState state;   /* saved S C state, or NULL if not yet saved */
    3832             :     AfterTriggerEventList events;   /* saved list pointer */
    3833             :     int         query_depth;    /* saved query_depth */
    3834             :     CommandId   firing_counter; /* saved firing_counter */
    3835             : };
    3836             : 
    3837             : struct AfterTriggersTableData
    3838             : {
    3839             :     /* relid + cmdType form the lookup key for these structs: */
    3840             :     Oid         relid;          /* target table's OID */
    3841             :     CmdType     cmdType;        /* event type, CMD_INSERT/UPDATE/DELETE */
    3842             :     bool        closed;         /* true when no longer OK to add tuples */
    3843             :     bool        before_trig_done;   /* did we already queue BS triggers? */
    3844             :     bool        after_trig_done;    /* did we already queue AS triggers? */
    3845             :     AfterTriggerEventList after_trig_events;    /* if so, saved list pointer */
    3846             : 
    3847             :     /*
    3848             :      * We maintain separate transition tables for UPDATE/INSERT/DELETE since
    3849             :      * MERGE can run all three actions in a single statement. Note that UPDATE
    3850             :      * needs both old and new transition tables whereas INSERT needs only new,
    3851             :      * and DELETE needs only old.
    3852             :      */
    3853             : 
    3854             :     /* "old" transition table for UPDATE, if any */
    3855             :     Tuplestorestate *old_upd_tuplestore;
    3856             :     /* "new" transition table for UPDATE, if any */
    3857             :     Tuplestorestate *new_upd_tuplestore;
    3858             :     /* "old" transition table for DELETE, if any */
    3859             :     Tuplestorestate *old_del_tuplestore;
    3860             :     /* "new" transition table for INSERT, if any */
    3861             :     Tuplestorestate *new_ins_tuplestore;
    3862             : 
    3863             :     TupleTableSlot *storeslot;  /* for converting to tuplestore's format */
    3864             : };
    3865             : 
    3866             : static AfterTriggersData afterTriggers;
    3867             : 
    3868             : static void AfterTriggerExecute(EState *estate,
    3869             :                                 AfterTriggerEvent event,
    3870             :                                 ResultRelInfo *relInfo,
    3871             :                                 ResultRelInfo *src_relInfo,
    3872             :                                 ResultRelInfo *dst_relInfo,
    3873             :                                 TriggerDesc *trigdesc,
    3874             :                                 FmgrInfo *finfo,
    3875             :                                 Instrumentation *instr,
    3876             :                                 MemoryContext per_tuple_context,
    3877             :                                 TupleTableSlot *trig_tuple_slot1,
    3878             :                                 TupleTableSlot *trig_tuple_slot2);
    3879             : static AfterTriggersTableData *GetAfterTriggersTableData(Oid relid,
    3880             :                                                          CmdType cmdType);
    3881             : static TupleTableSlot *GetAfterTriggersStoreSlot(AfterTriggersTableData *table,
    3882             :                                                  TupleDesc tupdesc);
    3883             : static Tuplestorestate *GetAfterTriggersTransitionTable(int event,
    3884             :                                                         TupleTableSlot *oldslot,
    3885             :                                                         TupleTableSlot *newslot,
    3886             :                                                         TransitionCaptureState *transition_capture);
    3887             : static void TransitionTableAddTuple(EState *estate,
    3888             :                                     TransitionCaptureState *transition_capture,
    3889             :                                     ResultRelInfo *relinfo,
    3890             :                                     TupleTableSlot *slot,
    3891             :                                     TupleTableSlot *original_insert_tuple,
    3892             :                                     Tuplestorestate *tuplestore);
    3893             : static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs);
    3894             : static SetConstraintState SetConstraintStateCreate(int numalloc);
    3895             : static SetConstraintState SetConstraintStateCopy(SetConstraintState origstate);
    3896             : static SetConstraintState SetConstraintStateAddItem(SetConstraintState state,
    3897             :                                                     Oid tgoid, bool tgisdeferred);
    3898             : static void cancel_prior_stmt_triggers(Oid relid, CmdType cmdType, int tgevent);
    3899             : 
    3900             : 
    3901             : /*
    3902             :  * Get the FDW tuplestore for the current trigger query level, creating it
    3903             :  * if necessary.
    3904             :  */
    3905             : static Tuplestorestate *
    3906         100 : GetCurrentFDWTuplestore(void)
    3907             : {
    3908             :     Tuplestorestate *ret;
    3909             : 
    3910         100 :     ret = afterTriggers.query_stack[afterTriggers.query_depth].fdw_tuplestore;
    3911         100 :     if (ret == NULL)
    3912             :     {
    3913             :         MemoryContext oldcxt;
    3914             :         ResourceOwner saveResourceOwner;
    3915             : 
    3916             :         /*
    3917             :          * Make the tuplestore valid until end of subtransaction.  We really
    3918             :          * only need it until AfterTriggerEndQuery().
    3919             :          */
    3920          36 :         oldcxt = MemoryContextSwitchTo(CurTransactionContext);
    3921          36 :         saveResourceOwner = CurrentResourceOwner;
    3922          36 :         CurrentResourceOwner = CurTransactionResourceOwner;
    3923             : 
    3924          36 :         ret = tuplestore_begin_heap(false, false, work_mem);
    3925             : 
    3926          36 :         CurrentResourceOwner = saveResourceOwner;
    3927          36 :         MemoryContextSwitchTo(oldcxt);
    3928             : 
    3929          36 :         afterTriggers.query_stack[afterTriggers.query_depth].fdw_tuplestore = ret;
    3930             :     }
    3931             : 
    3932         100 :     return ret;
    3933             : }
    3934             : 
    3935             : /* ----------
    3936             :  * afterTriggerCheckState()
    3937             :  *
    3938             :  *  Returns true if the trigger event is actually in state DEFERRED.
    3939             :  * ----------
    3940             :  */
    3941             : static bool
    3942       10864 : afterTriggerCheckState(AfterTriggerShared evtshared)
    3943             : {
    3944       10864 :     Oid         tgoid = evtshared->ats_tgoid;
    3945       10864 :     SetConstraintState state = afterTriggers.state;
    3946             :     int         i;
    3947             : 
    3948             :     /*
    3949             :      * For not-deferrable triggers (i.e. normal AFTER ROW triggers and
    3950             :      * constraints declared NOT DEFERRABLE), the state is always false.
    3951             :      */
    3952       10864 :     if ((evtshared->ats_event & AFTER_TRIGGER_DEFERRABLE) == 0)
    3953       10218 :         return false;
    3954             : 
    3955             :     /*
    3956             :      * If constraint state exists, SET CONSTRAINTS might have been executed
    3957             :      * either for this trigger or for all triggers.
    3958             :      */
    3959         646 :     if (state != NULL)
    3960             :     {
    3961             :         /* Check for SET CONSTRAINTS for this specific trigger. */
    3962         312 :         for (i = 0; i < state->numstates; i++)
    3963             :         {
    3964         246 :             if (state->trigstates[i].sct_tgoid == tgoid)
    3965          60 :                 return state->trigstates[i].sct_tgisdeferred;
    3966             :         }
    3967             : 
    3968             :         /* Check for SET CONSTRAINTS ALL. */
    3969          66 :         if (state->all_isset)
    3970          54 :             return state->all_isdeferred;
    3971             :     }
    3972             : 
    3973             :     /*
    3974             :      * Otherwise return the default state for the trigger.
    3975             :      */
    3976         532 :     return ((evtshared->ats_event & AFTER_TRIGGER_INITDEFERRED) != 0);
    3977             : }
    3978             : 
    3979             : 
    3980             : /* ----------
    3981             :  * afterTriggerAddEvent()
    3982             :  *
    3983             :  *  Add a new trigger event to the specified queue.
    3984             :  *  The passed-in event data is copied.
    3985             :  * ----------
    3986             :  */
    3987             : static void
    3988       11434 : afterTriggerAddEvent(AfterTriggerEventList *events,
    3989             :                      AfterTriggerEvent event, AfterTriggerShared evtshared)
    3990             : {
    3991       11434 :     Size        eventsize = SizeofTriggerEvent(event);
    3992       11434 :     Size        needed = eventsize + sizeof(AfterTriggerSharedData);
    3993             :     AfterTriggerEventChunk *chunk;
    3994             :     AfterTriggerShared newshared;
    3995             :     AfterTriggerEvent newevent;
    3996             : 
    3997             :     /*
    3998             :      * If empty list or not enough room in the tail chunk, make a new chunk.
    3999             :      * We assume here that a new shared record will always be needed.
    4000             :      */
    4001       11434 :     chunk = events->tail;
    4002       11434 :     if (chunk == NULL ||
    4003        4470 :         chunk->endfree - chunk->freeptr < needed)
    4004             :     {
    4005             :         Size        chunksize;
    4006             : 
    4007             :         /* Create event context if we didn't already */
    4008        6964 :         if (afterTriggers.event_cxt == NULL)
    4009        5836 :             afterTriggers.event_cxt =
    4010        5836 :                 AllocSetContextCreate(TopTransactionContext,
    4011             :                                       "AfterTriggerEvents",
    4012             :                                       ALLOCSET_DEFAULT_SIZES);
    4013             : 
    4014             :         /*
    4015             :          * Chunk size starts at 1KB and is allowed to increase up to 1MB.
    4016             :          * These numbers are fairly arbitrary, though there is a hard limit at
    4017             :          * AFTER_TRIGGER_OFFSET; else we couldn't link event records to their
    4018             :          * shared records using the available space in ate_flags.  Another
    4019             :          * constraint is that if the chunk size gets too huge, the search loop
    4020             :          * below would get slow given a (not too common) usage pattern with
    4021             :          * many distinct event types in a chunk.  Therefore, we double the
    4022             :          * preceding chunk size only if there weren't too many shared records
    4023             :          * in the preceding chunk; otherwise we halve it.  This gives us some
    4024             :          * ability to adapt to the actual usage pattern of the current query
    4025             :          * while still having large chunk sizes in typical usage.  All chunk
    4026             :          * sizes used should be MAXALIGN multiples, to ensure that the shared
    4027             :          * records will be aligned safely.
    4028             :          */
    4029             : #define MIN_CHUNK_SIZE 1024
    4030             : #define MAX_CHUNK_SIZE (1024*1024)
    4031             : 
    4032             : #if MAX_CHUNK_SIZE > (AFTER_TRIGGER_OFFSET+1)
    4033             : #error MAX_CHUNK_SIZE must not exceed AFTER_TRIGGER_OFFSET
    4034             : #endif
    4035             : 
    4036        6964 :         if (chunk == NULL)
    4037        6964 :             chunksize = MIN_CHUNK_SIZE;
    4038             :         else
    4039             :         {
    4040             :             /* preceding chunk size... */
    4041           0 :             chunksize = chunk->endptr - (char *) chunk;
    4042             :             /* check number of shared records in preceding chunk */
    4043           0 :             if ((chunk->endptr - chunk->endfree) <=
    4044             :                 (100 * sizeof(AfterTriggerSharedData)))
    4045           0 :                 chunksize *= 2; /* okay, double it */
    4046             :             else
    4047           0 :                 chunksize /= 2; /* too many shared records */
    4048           0 :             chunksize = Min(chunksize, MAX_CHUNK_SIZE);
    4049             :         }
    4050        6964 :         chunk = MemoryContextAlloc(afterTriggers.event_cxt, chunksize);
    4051        6964 :         chunk->next = NULL;
    4052        6964 :         chunk->freeptr = CHUNK_DATA_START(chunk);
    4053        6964 :         chunk->endptr = chunk->endfree = (char *) chunk + chunksize;
    4054             :         Assert(chunk->endfree - chunk->freeptr >= needed);
    4055             : 
    4056        6964 :         if (events->head == NULL)
    4057        6964 :             events->head = chunk;
    4058             :         else
    4059           0 :             events->tail->next = chunk;
    4060        6964 :         events->tail = chunk;
    4061             :         /* events->tailfree is now out of sync, but we'll fix it below */
    4062             :     }
    4063             : 
    4064             :     /*
    4065             :      * Try to locate a matching shared-data record already in the chunk. If
    4066             :      * none, make a new one.
    4067             :      */
    4068       11434 :     for (newshared = ((AfterTriggerShared) chunk->endptr) - 1;
    4069       16498 :          (char *) newshared >= chunk->endfree;
    4070        5064 :          newshared--)
    4071             :     {
    4072        6492 :         if (newshared->ats_tgoid == evtshared->ats_tgoid &&
    4073        1608 :             newshared->ats_relid == evtshared->ats_relid &&
    4074        1608 :             newshared->ats_event == evtshared->ats_event &&
    4075        1602 :             newshared->ats_table == evtshared->ats_table &&
    4076        1566 :             newshared->ats_firing_id == 0)
    4077        1428 :             break;
    4078             :     }
    4079       11434 :     if ((char *) newshared < chunk->endfree)
    4080             :     {
    4081       10006 :         *newshared = *evtshared;
    4082       10006 :         newshared->ats_firing_id = 0;    /* just to be sure */
    4083       10006 :         chunk->endfree = (char *) newshared;
    4084             :     }
    4085             : 
    4086             :     /* Insert the data */
    4087       11434 :     newevent = (AfterTriggerEvent) chunk->freeptr;
    4088       11434 :     memcpy(newevent, event, eventsize);
    4089             :     /* ... and link the new event to its shared record */
    4090       11434 :     newevent->ate_flags &= ~AFTER_TRIGGER_OFFSET;
    4091       11434 :     newevent->ate_flags |= (char *) newshared - (char *) newevent;
    4092             : 
    4093       11434 :     chunk->freeptr += eventsize;
    4094       11434 :     events->tailfree = chunk->freeptr;
    4095       11434 : }
    4096             : 
    4097             : /* ----------
    4098             :  * afterTriggerFreeEventList()
    4099             :  *
    4100             :  *  Free all the event storage in the given list.
    4101             :  * ----------
    4102             :  */
    4103             : static void
    4104       16068 : afterTriggerFreeEventList(AfterTriggerEventList *events)
    4105             : {
    4106             :     AfterTriggerEventChunk *chunk;
    4107             : 
    4108       21828 :     while ((chunk = events->head) != NULL)
    4109             :     {
    4110        5760 :         events->head = chunk->next;
    4111        5760 :         pfree(chunk);
    4112             :     }
    4113       16068 :     events->tail = NULL;
    4114       16068 :     events->tailfree = NULL;
    4115       16068 : }
    4116             : 
    4117             : /* ----------
    4118             :  * afterTriggerRestoreEventList()
    4119             :  *
    4120             :  *  Restore an event list to its prior length, removing all the events
    4121             :  *  added since it had the value old_events.
    4122             :  * ----------
    4123             :  */
    4124             : static void
    4125        8960 : afterTriggerRestoreEventList(AfterTriggerEventList *events,
    4126             :                              const AfterTriggerEventList *old_events)
    4127             : {
    4128             :     AfterTriggerEventChunk *chunk;
    4129             :     AfterTriggerEventChunk *next_chunk;
    4130             : 
    4131        8960 :     if (old_events->tail == NULL)
    4132             :     {
    4133             :         /* restoring to a completely empty state, so free everything */
    4134        8938 :         afterTriggerFreeEventList(events);
    4135             :     }
    4136             :     else
    4137             :     {
    4138          22 :         *events = *old_events;
    4139             :         /* free any chunks after the last one we want to keep */
    4140          22 :         for (chunk = events->tail->next; chunk != NULL; chunk = next_chunk)
    4141             :         {
    4142           0 :             next_chunk = chunk->next;
    4143           0 :             pfree(chunk);
    4144             :         }
    4145             :         /* and clean up the tail chunk to be the right length */
    4146          22 :         events->tail->next = NULL;
    4147          22 :         events->tail->freeptr = events->tailfree;
    4148             : 
    4149             :         /*
    4150             :          * We don't make any effort to remove now-unused shared data records.
    4151             :          * They might still be useful, anyway.
    4152             :          */
    4153             :     }
    4154        8960 : }
    4155             : 
    4156             : /* ----------
    4157             :  * afterTriggerDeleteHeadEventChunk()
    4158             :  *
    4159             :  *  Remove the first chunk of events from the query level's event list.
    4160             :  *  Keep any event list pointers elsewhere in the query level's data
    4161             :  *  structures in sync.
    4162             :  * ----------
    4163             :  */
    4164             : static void
    4165           0 : afterTriggerDeleteHeadEventChunk(AfterTriggersQueryData *qs)
    4166             : {
    4167           0 :     AfterTriggerEventChunk *target = qs->events.head;
    4168             :     ListCell   *lc;
    4169             : 
    4170             :     Assert(target && target->next);
    4171             : 
    4172             :     /*
    4173             :      * First, update any pointers in the per-table data, so that they won't be
    4174             :      * dangling.  Resetting obsoleted pointers to NULL will make
    4175             :      * cancel_prior_stmt_triggers start from the list head, which is fine.
    4176             :      */
    4177           0 :     foreach(lc, qs->tables)
    4178             :     {
    4179           0 :         AfterTriggersTableData *table = (AfterTriggersTableData *) lfirst(lc);
    4180             : 
    4181           0 :         if (table->after_trig_done &&
    4182           0 :             table->after_trig_events.tail == target)
    4183             :         {
    4184           0 :             table->after_trig_events.head = NULL;
    4185           0 :             table->after_trig_events.tail = NULL;
    4186           0 :             table->after_trig_events.tailfree = NULL;
    4187             :         }
    4188             :     }
    4189             : 
    4190             :     /* Now we can flush the head chunk */
    4191           0 :     qs->events.head = target->next;
    4192           0 :     pfree(target);
    4193           0 : }
    4194             : 
    4195             : 
    4196             : /* ----------
    4197             :  * AfterTriggerExecute()
    4198             :  *
    4199             :  *  Fetch the required tuples back from the heap and fire one
    4200             :  *  single trigger function.
    4201             :  *
    4202             :  *  Frequently, this will be fired many times in a row for triggers of
    4203             :  *  a single relation.  Therefore, we cache the open relation and provide
    4204             :  *  fmgr lookup cache space at the caller level.  (For triggers fired at
    4205             :  *  the end of a query, we can even piggyback on the executor's state.)
    4206             :  *
    4207             :  *  When fired for a cross-partition update of a partitioned table, the old
    4208             :  *  tuple is fetched using 'src_relInfo' (the source leaf partition) and
    4209             :  *  the new tuple using 'dst_relInfo' (the destination leaf partition), though
    4210             :  *  both are converted into the root partitioned table's format before passing
    4211             :  *  to the trigger function.
    4212             :  *
    4213             :  *  event: event currently being fired.
    4214             :  *  relInfo: result relation for event.
    4215             :  *  src_relInfo: source partition of a cross-partition update
    4216             :  *  dst_relInfo: its destination partition
    4217             :  *  trigdesc: working copy of rel's trigger info.
    4218             :  *  finfo: array of fmgr lookup cache entries (one per trigger in trigdesc).
    4219             :  *  instr: array of EXPLAIN ANALYZE instrumentation nodes (one per trigger),
    4220             :  *      or NULL if no instrumentation is wanted.
    4221             :  *  per_tuple_context: memory context to call trigger function in.
    4222             :  *  trig_tuple_slot1: scratch slot for tg_trigtuple (foreign tables only)
    4223             :  *  trig_tuple_slot2: scratch slot for tg_newtuple (foreign tables only)
    4224             :  * ----------
    4225             :  */
    4226             : static void
    4227       10600 : AfterTriggerExecute(EState *estate,
    4228             :                     AfterTriggerEvent event,
    4229             :                     ResultRelInfo *relInfo,
    4230             :                     ResultRelInfo *src_relInfo,
    4231             :                     ResultRelInfo *dst_relInfo,
    4232             :                     TriggerDesc *trigdesc,
    4233             :                     FmgrInfo *finfo, Instrumentation *instr,
    4234             :                     MemoryContext per_tuple_context,
    4235             :                     TupleTableSlot *trig_tuple_slot1,
    4236             :                     TupleTableSlot *trig_tuple_slot2)
    4237             : {
    4238       10600 :     Relation    rel = relInfo->ri_RelationDesc;
    4239       10600 :     Relation    src_rel = src_relInfo->ri_RelationDesc;
    4240       10600 :     Relation    dst_rel = dst_relInfo->ri_RelationDesc;
    4241       10600 :     AfterTriggerShared evtshared = GetTriggerSharedData(event);
    4242       10600 :     Oid         tgoid = evtshared->ats_tgoid;
    4243       10600 :     TriggerData LocTriggerData = {0};
    4244             :     HeapTuple   rettuple;
    4245             :     int         tgindx;
    4246       10600 :     bool        should_free_trig = false;
    4247       10600 :     bool        should_free_new = false;
    4248             : 
    4249             :     /*
    4250             :      * Locate trigger in trigdesc.
    4251             :      */
    4252       24342 :     for (tgindx = 0; tgindx < trigdesc->numtriggers; tgindx++)
    4253             :     {
    4254       24342 :         if (trigdesc->triggers[tgindx].tgoid == tgoid)
    4255             :         {
    4256       10600 :             LocTriggerData.tg_trigger = &(trigdesc->triggers[tgindx]);
    4257       10600 :             break;
    4258             :         }
    4259             :     }
    4260       10600 :     if (LocTriggerData.tg_trigger == NULL)
    4261           0 :         elog(ERROR, "could not find trigger %u", tgoid);
    4262             : 
    4263             :     /*
    4264             :      * If doing EXPLAIN ANALYZE, start charging time to this trigger. We want
    4265             :      * to include time spent re-fetching tuples in the trigger cost.
    4266             :      */
    4267       10600 :     if (instr)
    4268           0 :         InstrStartNode(instr + tgindx);
    4269             : 
    4270             :     /*
    4271             :      * Fetch the required tuple(s).
    4272             :      */
    4273       10600 :     switch (event->ate_flags & AFTER_TRIGGER_TUP_BITS)
    4274             :     {
    4275          50 :         case AFTER_TRIGGER_FDW_FETCH:
    4276             :             {
    4277          50 :                 Tuplestorestate *fdw_tuplestore = GetCurrentFDWTuplestore();
    4278             : 
    4279          50 :                 if (!tuplestore_gettupleslot(fdw_tuplestore, true, false,
    4280             :                                              trig_tuple_slot1))
    4281           0 :                     elog(ERROR, "failed to fetch tuple1 for AFTER trigger");
    4282             : 
    4283          50 :                 if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) ==
    4284          18 :                     TRIGGER_EVENT_UPDATE &&
    4285          18 :                     !tuplestore_gettupleslot(fdw_tuplestore, true, false,
    4286             :                                              trig_tuple_slot2))
    4287           0 :                     elog(ERROR, "failed to fetch tuple2 for AFTER trigger");
    4288             :             }
    4289             :             /* fall through */
    4290             :         case AFTER_TRIGGER_FDW_REUSE:
    4291             : 
    4292             :             /*
    4293             :              * Store tuple in the slot so that tg_trigtuple does not reference
    4294             :              * tuplestore memory.  (It is formally possible for the trigger
    4295             :              * function to queue trigger events that add to the same
    4296             :              * tuplestore, which can push other tuples out of memory.)  The
    4297             :              * distinction is academic, because we start with a minimal tuple
    4298             :              * that is stored as a heap tuple, constructed in different memory
    4299             :              * context, in the slot anyway.
    4300             :              */
    4301          58 :             LocTriggerData.tg_trigslot = trig_tuple_slot1;
    4302          58 :             LocTriggerData.tg_trigtuple =
    4303          58 :                 ExecFetchSlotHeapTuple(trig_tuple_slot1, true, &should_free_trig);
    4304             : 
    4305          58 :             if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) ==
    4306             :                 TRIGGER_EVENT_UPDATE)
    4307             :             {
    4308          22 :                 LocTriggerData.tg_newslot = trig_tuple_slot2;
    4309          22 :                 LocTriggerData.tg_newtuple =
    4310          22 :                     ExecFetchSlotHeapTuple(trig_tuple_slot2, true, &should_free_new);
    4311             :             }
    4312             :             else
    4313             :             {
    4314          36 :                 LocTriggerData.tg_newtuple = NULL;
    4315             :             }
    4316          58 :             break;
    4317             : 
    4318       10542 :         default:
    4319       10542 :             if (ItemPointerIsValid(&(event->ate_ctid1)))
    4320             :             {
    4321        9568 :                 TupleTableSlot *src_slot = ExecGetTriggerOldSlot(estate,
    4322             :                                                                  src_relInfo);
    4323             : 
    4324        9568 :                 if (!table_tuple_fetch_row_version(src_rel,
    4325             :                                                    &(event->ate_ctid1),
    4326             :                                                    SnapshotAny,
    4327             :                                                    src_slot))
    4328           0 :                     elog(ERROR, "failed to fetch tuple1 for AFTER trigger");
    4329             : 
    4330             :                 /*
    4331             :                  * Store the tuple fetched from the source partition into the
    4332             :                  * target (root partitioned) table slot, converting if needed.
    4333             :                  */
    4334        9568 :                 if (src_relInfo != relInfo)
    4335             :                 {
    4336         144 :                     TupleConversionMap *map = ExecGetChildToRootMap(src_relInfo);
    4337             : 
    4338         144 :                     LocTriggerData.tg_trigslot = ExecGetTriggerOldSlot(estate, relInfo);
    4339         144 :                     if (map)
    4340             :                     {
    4341          36 :                         execute_attr_map_slot(map->attrMap,
    4342             :                                               src_slot,
    4343             :                                               LocTriggerData.tg_trigslot);
    4344             :                     }
    4345             :                     else
    4346         108 :                         ExecCopySlot(LocTriggerData.tg_trigslot, src_slot);
    4347             :                 }
    4348             :                 else
    4349        9424 :                     LocTriggerData.tg_trigslot = src_slot;
    4350        9568 :                 LocTriggerData.tg_trigtuple =
    4351        9568 :                     ExecFetchSlotHeapTuple(LocTriggerData.tg_trigslot, false, &should_free_trig);
    4352             :             }
    4353             :             else
    4354             :             {
    4355         974 :                 LocTriggerData.tg_trigtuple = NULL;
    4356             :             }
    4357             : 
    4358             :             /* don't touch ctid2 if not there */
    4359       10542 :             if (((event->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_2CTID ||
    4360       10686 :                  (event->ate_flags & AFTER_TRIGGER_CP_UPDATE)) &&
    4361        2820 :                 ItemPointerIsValid(&(event->ate_ctid2)))
    4362        2820 :             {
    4363        2820 :                 TupleTableSlot *dst_slot = ExecGetTriggerNewSlot(estate,
    4364             :                                                                  dst_relInfo);
    4365             : 
    4366        2820 :                 if (!table_tuple_fetch_row_version(dst_rel,
    4367             :                                                    &(event->ate_ctid2),
    4368             :                                                    SnapshotAny,
    4369             :                                                    dst_slot))
    4370           0 :                     elog(ERROR, "failed to fetch tuple2 for AFTER trigger");
    4371             : 
    4372             :                 /*
    4373             :                  * Store the tuple fetched from the destination partition into
    4374             :                  * the target (root partitioned) table slot, converting if
    4375             :                  * needed.
    4376             :                  */
    4377        2820 :                 if (dst_relInfo != relInfo)
    4378             :                 {
    4379         144 :                     TupleConversionMap *map = ExecGetChildToRootMap(dst_relInfo);
    4380             : 
    4381         144 :                     LocTriggerData.tg_newslot = ExecGetTriggerNewSlot(estate, relInfo);
    4382         144 :                     if (map)
    4383             :                     {
    4384          36 :                         execute_attr_map_slot(map->attrMap,
    4385             :                                               dst_slot,
    4386             :                                               LocTriggerData.tg_newslot);
    4387             :                     }
    4388             :                     else
    4389         108 :                         ExecCopySlot(LocTriggerData.tg_newslot, dst_slot);
    4390             :                 }
    4391             :                 else
    4392        2676 :                     LocTriggerData.tg_newslot = dst_slot;
    4393        2820 :                 LocTriggerData.tg_newtuple =
    4394        2820 :                     ExecFetchSlotHeapTuple(LocTriggerData.tg_newslot, false, &should_free_new);
    4395             :             }
    4396             :             else
    4397             :             {
    4398        7722 :                 LocTriggerData.tg_newtuple = NULL;
    4399             :             }
    4400             :     }
    4401             : 
    4402             :     /*
    4403             :      * Set up the tuplestore information to let the trigger have access to
    4404             :      * transition tables.  When we first make a transition table available to
    4405             :      * a trigger, mark it "closed" so that it cannot change anymore.  If any
    4406             :      * additional events of the same type get queued in the current trigger
    4407             :      * query level, they'll go into new transition tables.
    4408             :      */
    4409       10600 :     LocTriggerData.tg_oldtable = LocTriggerData.tg_newtable = NULL;
    4410       10600 :     if (evtshared->ats_table)
    4411             :     {
    4412         534 :         if (LocTriggerData.tg_trigger->tgoldtable)
    4413             :         {
    4414         300 :             if (TRIGGER_FIRED_BY_UPDATE(evtshared->ats_event))
    4415         156 :                 LocTriggerData.tg_oldtable = evtshared->ats_table->old_upd_tuplestore;
    4416             :             else
    4417         144 :                 LocTriggerData.tg_oldtable = evtshared->ats_table->old_del_tuplestore;
    4418         300 :             evtshared->ats_table->closed = true;
    4419             :         }
    4420             : 
    4421         534 :         if (LocTriggerData.tg_trigger->tgnewtable)
    4422             :         {
    4423         384 :             if (TRIGGER_FIRED_BY_INSERT(evtshared->ats_event))
    4424         210 :                 LocTriggerData.tg_newtable = evtshared->ats_table->new_ins_tuplestore;
    4425             :             else
    4426         174 :                 LocTriggerData.tg_newtable = evtshared->ats_table->new_upd_tuplestore;
    4427         384 :             evtshared->ats_table->closed = true;
    4428             :         }
    4429             :     }
    4430             : 
    4431             :     /*
    4432             :      * Setup the remaining trigger information
    4433             :      */
    4434       10600 :     LocTriggerData.type = T_TriggerData;
    4435       10600 :     LocTriggerData.tg_event =
    4436       10600 :         evtshared->ats_event & (TRIGGER_EVENT_OPMASK | TRIGGER_EVENT_ROW);
    4437       10600 :     LocTriggerData.tg_relation = rel;
    4438       10600 :     if (TRIGGER_FOR_UPDATE(LocTriggerData.tg_trigger->tgtype))
    4439        5056 :         LocTriggerData.tg_updatedcols = evtshared->ats_modifiedcols;
    4440             : 
    4441       10600 :     MemoryContextReset(per_tuple_context);
    4442             : 
    4443             :     /*
    4444             :      * Call the trigger and throw away any possibly returned updated tuple.
    4445             :      * (Don't let ExecCallTriggerFunc measure EXPLAIN time.)
    4446             :      */
    4447       10600 :     rettuple = ExecCallTriggerFunc(&LocTriggerData,
    4448             :                                    tgindx,
    4449             :                                    finfo,
    4450             :                                    NULL,
    4451             :                                    per_tuple_context);
    4452        9602 :     if (rettuple != NULL &&
    4453        3298 :         rettuple != LocTriggerData.tg_trigtuple &&
    4454        1408 :         rettuple != LocTriggerData.tg_newtuple)
    4455           0 :         heap_freetuple(rettuple);
    4456             : 
    4457             :     /*
    4458             :      * Release resources
    4459             :      */
    4460        9602 :     if (should_free_trig)
    4461         172 :         heap_freetuple(LocTriggerData.tg_trigtuple);
    4462        9602 :     if (should_free_new)
    4463         136 :         heap_freetuple(LocTriggerData.tg_newtuple);
    4464             : 
    4465             :     /* don't clear slots' contents if foreign table */
    4466        9602 :     if (trig_tuple_slot1 == NULL)
    4467             :     {
    4468        9532 :         if (LocTriggerData.tg_trigslot)
    4469        8612 :             ExecClearTuple(LocTriggerData.tg_trigslot);
    4470        9532 :         if (LocTriggerData.tg_newslot)
    4471        2594 :             ExecClearTuple(LocTriggerData.tg_newslot);
    4472             :     }
    4473             : 
    4474             :     /*
    4475             :      * If doing EXPLAIN ANALYZE, stop charging time to this trigger, and count
    4476             :      * one "tuple returned" (really the number of firings).
    4477             :      */
    4478        9602 :     if (instr)
    4479           0 :         InstrStopNode(instr + tgindx, 1);
    4480        9602 : }
    4481             : 
    4482             : 
    4483             : /*
    4484             :  * afterTriggerMarkEvents()
    4485             :  *
    4486             :  *  Scan the given event list for not yet invoked events.  Mark the ones
    4487             :  *  that can be invoked now with the current firing ID.
    4488             :  *
    4489             :  *  If move_list isn't NULL, events that are not to be invoked now are
    4490             :  *  transferred to move_list.
    4491             :  *
    4492             :  *  When immediate_only is true, do not invoke currently-deferred triggers.
    4493             :  *  (This will be false only at main transaction exit.)
    4494             :  *
    4495             :  *  Returns true if any invokable events were found.
    4496             :  */
    4497             : static bool
    4498      957636 : afterTriggerMarkEvents(AfterTriggerEventList *events,
    4499             :                        AfterTriggerEventList *move_list,
    4500             :                        bool immediate_only)
    4501             : {
    4502      957636 :     bool        found = false;
    4503      957636 :     bool        deferred_found = false;
    4504             :     AfterTriggerEvent event;
    4505             :     AfterTriggerEventChunk *chunk;
    4506             : 
    4507      976978 :     for_each_event_chunk(event, chunk, *events)
    4508             :     {
    4509       12134 :         AfterTriggerShared evtshared = GetTriggerSharedData(event);
    4510       12134 :         bool        defer_it = false;
    4511             : 
    4512       12134 :         if (!(event->ate_flags &
    4513             :               (AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS)))
    4514             :         {
    4515             :             /*
    4516             :              * This trigger hasn't been called or scheduled yet. Check if we
    4517             :              * should call it now.
    4518             :              */
    4519       11294 :             if (immediate_only && afterTriggerCheckState(evtshared))
    4520             :             {
    4521         526 :                 defer_it = true;
    4522             :             }
    4523             :             else
    4524             :             {
    4525             :                 /*
    4526             :                  * Mark it as to be fired in this firing cycle.
    4527             :                  */
    4528       10768 :                 evtshared->ats_firing_id = afterTriggers.firing_counter;
    4529       10768 :                 event->ate_flags |= AFTER_TRIGGER_IN_PROGRESS;
    4530       10768 :                 found = true;
    4531             :             }
    4532             :         }
    4533             : 
    4534             :         /*
    4535             :          * If it's deferred, move it to move_list, if requested.
    4536             :          */
    4537       12134 :         if (defer_it && move_list != NULL)
    4538             :         {
    4539         526 :             deferred_found = true;
    4540             :             /* add it to move_list */
    4541         526 :             afterTriggerAddEvent(move_list, event, evtshared);
    4542             :             /* mark original copy "done" so we don't do it again */
    4543         526 :             event->ate_flags |= AFTER_TRIGGER_DONE;
    4544             :         }
    4545             :     }
    4546             : 
    4547             :     /*
    4548             :      * We could allow deferred triggers if, before the end of the
    4549             :      * security-restricted operation, we were to verify that a SET CONSTRAINTS
    4550             :      * ... IMMEDIATE has fired all such triggers.  For now, don't bother.
    4551             :      */
    4552      957636 :     if (deferred_found && InSecurityRestrictedOperation())
    4553          12 :         ereport(ERROR,
    4554             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    4555             :                  errmsg("cannot fire deferred trigger within security-restricted operation")));
    4556             : 
    4557      957624 :     return found;
    4558             : }
    4559             : 
    4560             : /*
    4561             :  * afterTriggerInvokeEvents()
    4562             :  *
    4563             :  *  Scan the given event list for events that are marked as to be fired
    4564             :  *  in the current firing cycle, and fire them.
    4565             :  *
    4566             :  *  If estate isn't NULL, we use its result relation info to avoid repeated
    4567             :  *  openings and closing of trigger target relations.  If it is NULL, we
    4568             :  *  make one locally to cache the info in case there are multiple trigger
    4569             :  *  events per rel.
    4570             :  *
    4571             :  *  When delete_ok is true, it's safe to delete fully-processed events.
    4572             :  *  (We are not very tense about that: we simply reset a chunk to be empty
    4573             :  *  if all its events got fired.  The objective here is just to avoid useless
    4574             :  *  rescanning of events when a trigger queues new events during transaction
    4575             :  *  end, so it's not necessary to worry much about the case where only
    4576             :  *  some events are fired.)
    4577             :  *
    4578             :  *  Returns true if no unfired events remain in the list (this allows us
    4579             :  *  to avoid repeating afterTriggerMarkEvents).
    4580             :  */
    4581             : static bool
    4582        6820 : afterTriggerInvokeEvents(AfterTriggerEventList *events,
    4583             :                          CommandId firing_id,
    4584             :                          EState *estate,
    4585             :                          bool delete_ok)
    4586             : {
    4587        6820 :     bool        all_fired = true;
    4588             :     AfterTriggerEventChunk *chunk;
    4589             :     MemoryContext per_tuple_context;
    4590        6820 :     bool        local_estate = false;
    4591        6820 :     ResultRelInfo *rInfo = NULL;
    4592        6820 :     Relation    rel = NULL;
    4593        6820 :     TriggerDesc *trigdesc = NULL;
    4594        6820 :     FmgrInfo   *finfo = NULL;
    4595        6820 :     Instrumentation *instr = NULL;
    4596        6820 :     TupleTableSlot *slot1 = NULL,
    4597        6820 :                *slot2 = NULL;
    4598             : 
    4599             :     /* Make a local EState if need be */
    4600        6820 :     if (estate == NULL)
    4601             :     {
    4602         290 :         estate = CreateExecutorState();
    4603         290 :         local_estate = true;
    4604             :     }
    4605             : 
    4606             :     /* Make a per-tuple memory context for trigger function calls */
    4607             :     per_tuple_context =
    4608        6820 :         AllocSetContextCreate(CurrentMemoryContext,
    4609             :                               "AfterTriggerTupleContext",
    4610             :                               ALLOCSET_DEFAULT_SIZES);
    4611             : 
    4612       12642 :     for_each_chunk(chunk, *events)
    4613             :     {
    4614             :         AfterTriggerEvent event;
    4615        6820 :         bool        all_fired_in_chunk = true;
    4616             : 
    4617       17904 :         for_each_event(event, chunk)
    4618             :         {
    4619       12082 :             AfterTriggerShared evtshared = GetTriggerSharedData(event);
    4620             : 
    4621             :             /*
    4622             :              * Is it one for me to fire?
    4623             :              */
    4624       12082 :             if ((event->ate_flags & AFTER_TRIGGER_IN_PROGRESS) &&
    4625       10600 :                 evtshared->ats_firing_id == firing_id)
    4626        9602 :             {
    4627             :                 ResultRelInfo *src_rInfo,
    4628             :                            *dst_rInfo;
    4629             : 
    4630             :                 /*
    4631             :                  * So let's fire it... but first, find the correct relation if
    4632             :                  * this is not the same relation as before.
    4633             :                  */
    4634       10600 :                 if (rel == NULL || RelationGetRelid(rel) != evtshared->ats_relid)
    4635             :                 {
    4636        7086 :                     rInfo = ExecGetTriggerResultRel(estate, evtshared->ats_relid,
    4637             :                                                     NULL);
    4638        7086 :                     rel = rInfo->ri_RelationDesc;
    4639             :                     /* Catch calls with insufficient relcache refcounting */
    4640             :                     Assert(!RelationHasReferenceCountZero(rel));
    4641        7086 :                     trigdesc = rInfo->ri_TrigDesc;
    4642        7086 :                     finfo = rInfo->ri_TrigFunctions;
    4643        7086 :                     instr = rInfo->ri_TrigInstrument;
    4644        7086 :                     if (slot1 != NULL)
    4645             :                     {
    4646           0 :                         ExecDropSingleTupleTableSlot(slot1);
    4647           0 :                         ExecDropSingleTupleTableSlot(slot2);
    4648           0 :                         slot1 = slot2 = NULL;
    4649             :                     }
    4650        7086 :                     if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
    4651             :                     {
    4652          38 :                         slot1 = MakeSingleTupleTableSlot(rel->rd_att,
    4653             :                                                          &TTSOpsMinimalTuple);
    4654          38 :                         slot2 = MakeSingleTupleTableSlot(rel->rd_att,
    4655             :                                                          &TTSOpsMinimalTuple);
    4656             :                     }
    4657        7086 :                     if (trigdesc == NULL)   /* should not happen */
    4658           0 :                         elog(ERROR, "relation %u has no triggers",
    4659             :                              evtshared->ats_relid);
    4660             :                 }
    4661             : 
    4662             :                 /*
    4663             :                  * Look up source and destination partition result rels of a
    4664             :                  * cross-partition update event.
    4665             :                  */
    4666       10600 :                 if ((event->ate_flags & AFTER_TRIGGER_TUP_BITS) ==
    4667             :                     AFTER_TRIGGER_CP_UPDATE)
    4668             :                 {
    4669             :                     Assert(OidIsValid(event->ate_src_part) &&
    4670             :                            OidIsValid(event->ate_dst_part));
    4671         144 :                     src_rInfo = ExecGetTriggerResultRel(estate,
    4672             :                                                         event->ate_src_part,
    4673             :                                                         rInfo);
    4674         144 :                     dst_rInfo = ExecGetTriggerResultRel(estate,
    4675             :                                                         event->ate_dst_part,
    4676             :                                                         rInfo);
    4677             :                 }
    4678             :                 else
    4679       10456 :                     src_rInfo = dst_rInfo = rInfo;
    4680             : 
    4681             :                 /*
    4682             :                  * Fire it.  Note that the AFTER_TRIGGER_IN_PROGRESS flag is
    4683             :                  * still set, so recursive examinations of the event list
    4684             :                  * won't try to re-fire it.
    4685             :                  */
    4686       10600 :                 AfterTriggerExecute(estate, event, rInfo,
    4687             :                                     src_rInfo, dst_rInfo,
    4688             :                                     trigdesc, finfo, instr,
    4689             :                                     per_tuple_context, slot1, slot2);
    4690             : 
    4691             :                 /*
    4692             :                  * Mark the event as done.
    4693             :                  */
    4694        9602 :                 event->ate_flags &= ~AFTER_TRIGGER_IN_PROGRESS;
    4695        9602 :                 event->ate_flags |= AFTER_TRIGGER_DONE;
    4696             :             }
    4697        1482 :             else if (!(event->ate_flags & AFTER_TRIGGER_DONE))
    4698             :             {
    4699             :                 /* something remains to be done */
    4700         516 :                 all_fired = all_fired_in_chunk = false;
    4701             :             }
    4702             :         }
    4703             : 
    4704             :         /* Clear the chunk if delete_ok and nothing left of interest */
    4705        5822 :         if (delete_ok && all_fired_in_chunk)
    4706             :         {
    4707         162 :             chunk->freeptr = CHUNK_DATA_START(chunk);
    4708         162 :             chunk->endfree = chunk->endptr;
    4709             : 
    4710             :             /*
    4711             :              * If it's last chunk, must sync event list's tailfree too.  Note
    4712             :              * that delete_ok must NOT be passed as true if there could be
    4713             :              * additional AfterTriggerEventList values pointing at this event
    4714             :              * list, since we'd fail to fix their copies of tailfree.
    4715             :              */
    4716         162 :             if (chunk == events->tail)
    4717         162 :                 events->tailfree = chunk->freeptr;
    4718             :         }
    4719             :     }
    4720        5822 :     if (slot1 != NULL)
    4721             :     {
    4722          38 :         ExecDropSingleTupleTableSlot(slot1);
    4723          38 :         ExecDropSingleTupleTableSlot(slot2);
    4724             :     }
    4725             : 
    4726             :     /* Release working resources */
    4727        5822 :     MemoryContextDelete(per_tuple_context);
    4728             : 
    4729        5822 :     if (local_estate)
    4730             :     {
    4731         162 :         ExecCloseResultRelations(estate);
    4732         162 :         ExecResetTupleTable(estate->es_tupleTable, false);
    4733         162 :         FreeExecutorState(estate);
    4734             :     }
    4735             : 
    4736        5822 :     return all_fired;
    4737             : }
    4738             : 
    4739             : 
    4740             : /*
    4741             :  * GetAfterTriggersTableData
    4742             :  *
    4743             :  * Find or create an AfterTriggersTableData struct for the specified
    4744             :  * trigger event (relation + operation type).  Ignore existing structs
    4745             :  * marked "closed"; we don't want to put any additional tuples into them,
    4746             :  * nor change their stmt-triggers-fired state.
    4747             :  *
    4748             :  * Note: the AfterTriggersTableData list is allocated in the current
    4749             :  * (sub)transaction's CurTransactionContext.  This is OK because
    4750             :  * we don't need it to live past AfterTriggerEndQuery.
    4751             :  */
    4752             : static AfterTriggersTableData *
    4753        2046 : GetAfterTriggersTableData(Oid relid, CmdType cmdType)
    4754             : {
    4755             :     AfterTriggersTableData *table;
    4756             :     AfterTriggersQueryData *qs;
    4757             :     MemoryContext oldcxt;
    4758             :     ListCell   *lc;
    4759             : 
    4760             :     /* Caller should have ensured query_depth is OK. */
    4761             :     Assert(afterTriggers.query_depth >= 0 &&
    4762             :            afterTriggers.query_depth < afterTriggers.maxquerydepth);
    4763        2046 :     qs = &afterTriggers.query_stack[afterTriggers.query_depth];
    4764             : 
    4765        2358 :     foreach(lc, qs->tables)
    4766             :     {
    4767        1342 :         table = (AfterTriggersTableData *) lfirst(lc);
    4768        1342 :         if (table->relid == relid && table->cmdType == cmdType &&
    4769        1066 :             !table->closed)
    4770        1030 :             return table;
    4771             :     }
    4772             : 
    4773        1016 :     oldcxt = MemoryContextSwitchTo(CurTransactionContext);
    4774             : 
    4775        1016 :     table = (AfterTriggersTableData *) palloc0(sizeof(AfterTriggersTableData));
    4776        1016 :     table->relid = relid;
    4777        1016 :     table->cmdType = cmdType;
    4778        1016 :     qs->tables = lappend(qs->tables, table);
    4779             : 
    4780        1016 :     MemoryContextSwitchTo(oldcxt);
    4781             : 
    4782        1016 :     return table;
    4783             : }
    4784             : 
    4785             : /*
    4786             :  * Returns a TupleTableSlot suitable for holding the tuples to be put
    4787             :  * into AfterTriggersTableData's transition table tuplestores.
    4788             :  */
    4789             : static TupleTableSlot *
    4790         294 : GetAfterTriggersStoreSlot(AfterTriggersTableData *table,
    4791             :                           TupleDesc tupdesc)
    4792             : {
    4793             :     /* Create it if not already done. */
    4794         294 :     if (!table->storeslot)
    4795             :     {
    4796             :         MemoryContext oldcxt;
    4797             : 
    4798             :         /*
    4799             :          * We need this slot only until AfterTriggerEndQuery, but making it
    4800             :          * last till end-of-subxact is good enough.  It'll be freed by
    4801             :          * AfterTriggerFreeQuery().  However, the passed-in tupdesc might have
    4802             :          * a different lifespan, so we'd better make a copy of that.
    4803             :          */
    4804          84 :         oldcxt = MemoryContextSwitchTo(CurTransactionContext);
    4805          84 :         tupdesc = CreateTupleDescCopy(tupdesc);
    4806          84 :         table->storeslot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
    4807          84 :         MemoryContextSwitchTo(oldcxt);
    4808             :     }
    4809             : 
    4810         294 :     return table->storeslot;
    4811             : }
    4812             : 
    4813             : /*
    4814             :  * MakeTransitionCaptureState
    4815             :  *
    4816             :  * Make a TransitionCaptureState object for the given TriggerDesc, target
    4817             :  * relation, and operation type.  The TCS object holds all the state needed
    4818             :  * to decide whether to capture tuples in transition tables.
    4819             :  *
    4820             :  * If there are no triggers in 'trigdesc' that request relevant transition
    4821             :  * tables, then return NULL.
    4822             :  *
    4823             :  * The resulting object can be passed to the ExecAR* functions.  When
    4824             :  * dealing with child tables, the caller can set tcs_original_insert_tuple
    4825             :  * to avoid having to reconstruct the original tuple in the root table's
    4826             :  * format.
    4827             :  *
    4828             :  * Note that we copy the flags from a parent table into this struct (rather
    4829             :  * than subsequently using the relation's TriggerDesc directly) so that we can
    4830             :  * use it to control collection of transition tuples from child tables.
    4831             :  *
    4832             :  * Per SQL spec, all operations of the same kind (INSERT/UPDATE/DELETE)
    4833             :  * on the same table during one query should share one transition table.
    4834             :  * Therefore, the Tuplestores are owned by an AfterTriggersTableData struct
    4835             :  * looked up using the table OID + CmdType, and are merely referenced by
    4836             :  * the TransitionCaptureState objects we hand out to callers.
    4837             :  */
    4838             : TransitionCaptureState *
    4839      136620 : MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
    4840             : {
    4841             :     TransitionCaptureState *state;
    4842             :     bool        need_old_upd,
    4843             :                 need_new_upd,
    4844             :                 need_old_del,
    4845             :                 need_new_ins;
    4846             :     AfterTriggersTableData *table;
    4847             :     MemoryContext oldcxt;
    4848             :     ResourceOwner saveResourceOwner;
    4849             : 
    4850      136620 :     if (trigdesc == NULL)
    4851      125032 :         return NULL;
    4852             : 
    4853             :     /* Detect which table(s) we need. */
    4854       11588 :     switch (cmdType)
    4855             :     {
    4856        6520 :         case CMD_INSERT:
    4857        6520 :             need_old_upd = need_old_del = need_new_upd = false;
    4858        6520 :             need_new_ins = trigdesc->trig_insert_new_table;
    4859        6520 :             break;
    4860        3562 :         case CMD_UPDATE:
    4861        3562 :             need_old_upd = trigdesc->trig_update_old_table;
    4862        3562 :             need_new_upd = trigdesc->trig_update_new_table;
    4863        3562 :             need_old_del = need_new_ins = false;
    4864        3562 :             break;
    4865        1310 :         case CMD_DELETE:
    4866        1310 :             need_old_del = trigdesc->trig_delete_old_table;
    4867        1310 :             need_old_upd = need_new_upd = need_new_ins = false;
    4868        1310 :             break;
    4869         196 :         case CMD_MERGE:
    4870         196 :             need_old_upd = trigdesc->trig_update_old_table;
    4871         196 :             need_new_upd = trigdesc->trig_update_new_table;
    4872         196 :             need_old_del = trigdesc->trig_delete_old_table;
    4873         196 :             need_new_ins = trigdesc->trig_insert_new_table;
    4874         196 :             break;
    4875           0 :         default:
    4876           0 :             elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
    4877             :             /* keep compiler quiet */
    4878             :             need_old_upd = need_new_upd = need_old_del = need_new_ins = false;
    4879             :             break;
    4880             :     }
    4881       11588 :     if (!need_old_upd && !need_new_upd && !need_new_ins && !need_old_del)
    4882       11036 :         return NULL;
    4883             : 
    4884             :     /* Check state, like AfterTriggerSaveEvent. */
    4885         552 :     if (afterTriggers.query_depth < 0)
    4886           0 :         elog(ERROR, "MakeTransitionCaptureState() called outside of query");
    4887             : 
    4888             :     /* Be sure we have enough space to record events at this query depth. */
    4889         552 :     if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
    4890         408 :         AfterTriggerEnlargeQueryState();
    4891             : 
    4892             :     /*
    4893             :      * Find or create an AfterTriggersTableData struct to hold the
    4894             :      * tuplestore(s).  If there's a matching struct but it's marked closed,
    4895             :      * ignore it; we need a newer one.
    4896             :      *
    4897             :      * Note: the AfterTriggersTableData list, as well as the tuplestores, are
    4898             :      * allocated in the current (sub)transaction's CurTransactionContext, and
    4899             :      * the tuplestores are managed by the (sub)transaction's resource owner.
    4900             :      * This is sufficient lifespan because we do not allow triggers using
    4901             :      * transition tables to be deferrable; they will be fired during
    4902             :      * AfterTriggerEndQuery, after which it's okay to delete the data.
    4903             :      */
    4904         552 :     table = GetAfterTriggersTableData(relid, cmdType);
    4905             : 
    4906             :     /* Now create required tuplestore(s), if we don't have them already. */
    4907         552 :     oldcxt = MemoryContextSwitchTo(CurTransactionContext);
    4908         552 :     saveResourceOwner = CurrentResourceOwner;
    4909         552 :     CurrentResourceOwner = CurTransactionResourceOwner;
    4910             : 
    4911         552 :     if (need_old_upd && table->old_upd_tuplestore == NULL)
    4912         162 :         table->old_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
    4913         552 :     if (need_new_upd && table->new_upd_tuplestore == NULL)
    4914         174 :         table->new_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
    4915         552 :     if (need_old_del && table->old_del_tuplestore == NULL)
    4916         132 :         table->old_del_tuplestore = tuplestore_begin_heap(false, false, work_mem);
    4917         552 :     if (need_new_ins && table->new_ins_tuplestore == NULL)
    4918         210 :         table->new_ins_tuplestore = tuplestore_begin_heap(false, false, work_mem);
    4919             : 
    4920         552 :     CurrentResourceOwner = saveResourceOwner;
    4921         552 :     MemoryContextSwitchTo(oldcxt);
    4922             : 
    4923             :     /* Now build the TransitionCaptureState struct, in caller's context */
    4924         552 :     state = (TransitionCaptureState *) palloc0(sizeof(TransitionCaptureState));
    4925         552 :     state->tcs_delete_old_table = trigdesc->trig_delete_old_table;
    4926         552 :     state->tcs_update_old_table = trigdesc->trig_update_old_table;
    4927         552 :     state->tcs_update_new_table = trigdesc->trig_update_new_table;
    4928         552 :     state->tcs_insert_new_table = trigdesc->trig_insert_new_table;
    4929         552 :     state->tcs_private = table;
    4930             : 
    4931         552 :     return state;
    4932             : }
    4933             : 
    4934             : 
    4935             : /* ----------
    4936             :  * AfterTriggerBeginXact()
    4937             :  *
    4938             :  *  Called at transaction start (either BEGIN or implicit for single
    4939             :  *  statement outside of transaction block).
    4940             :  * ----------
    4941             :  */
    4942             : void
    4943      975586 : AfterTriggerBeginXact(void)
    4944             : {
    4945             :     /*
    4946             :      * Initialize after-trigger state structure to empty
    4947             :      */
    4948      975586 :     afterTriggers.firing_counter = (CommandId) 1;   /* mustn't be 0 */
    4949      975586 :     afterTriggers.query_depth = -1;
    4950             : 
    4951             :     /*
    4952             :      * Verify that there is no leftover state remaining.  If these assertions
    4953             :      * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
    4954             :      * up properly.
    4955             :      */
    4956             :     Assert(afterTriggers.state == NULL);
    4957             :     Assert(afterTriggers.query_stack == NULL);
    4958             :     Assert(afterTriggers.maxquerydepth == 0);
    4959             :     Assert(afterTriggers.event_cxt == NULL);
    4960             :     Assert(afterTriggers.events.head == NULL);
    4961             :     Assert(afterTriggers.trans_stack == NULL);
    4962             :     Assert(afterTriggers.maxtransdepth == 0);
    4963      975586 : }
    4964             : 
    4965             : 
    4966             : /* ----------
    4967             :  * AfterTriggerBeginQuery()
    4968             :  *
    4969             :  *  Called just before we start processing a single query within a
    4970             :  *  transaction (or subtransaction).  Most of the real work gets deferred
    4971             :  *  until somebody actually tries to queue a trigger event.
    4972             :  * ----------
    4973             :  */
    4974             : void
    4975      432600 : AfterTriggerBeginQuery(void)
    4976             : {
    4977             :     /* Increase the query stack depth */
    4978      432600 :     afterTriggers.query_depth++;
    4979      432600 : }
    4980             : 
    4981             : 
    4982             : /* ----------
    4983             :  * AfterTriggerEndQuery()
    4984             :  *
    4985             :  *  Called after one query has been completely processed. At this time
    4986             :  *  we invoke all AFTER IMMEDIATE trigger events queued by the query, and
    4987             :  *  transfer deferred trigger events to the global deferred-trigger list.
    4988             :  *
    4989             :  *  Note that this must be called BEFORE closing down the executor
    4990             :  *  with ExecutorEnd, because we make use of the EState's info about
    4991             :  *  target relations.  Normally it is called from ExecutorFinish.
    4992             :  * ----------
    4993             :  */
    4994             : void
    4995      428682 : AfterTriggerEndQuery(EState *estate)
    4996             : {
    4997             :     AfterTriggersQueryData *qs;
    4998             : 
    4999             :     /* Must be inside a query, too */
    5000             :     Assert(afterTriggers.query_depth >= 0);
    5001             : 
    5002             :     /*
    5003             :      * If we never even got as far as initializing the event stack, there
    5004             :      * certainly won't be any events, so exit quickly.
    5005             :      */
    5006      428682 :     if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
    5007             :     {
    5008      420700 :         afterTriggers.query_depth--;
    5009      420700 :         return;
    5010             :     }
    5011             : 
    5012             :     /*
    5013             :      * Process all immediate-mode triggers queued by the query, and move the
    5014             :      * deferred ones to the main list of deferred events.
    5015             :      *
    5016             :      * Notice that we decide which ones will be fired, and put the deferred
    5017             :      * ones on the main list, before anything is actually fired.  This ensures
    5018             :      * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
    5019             :      * IMMEDIATE: all events we have decided to defer will be available for it
    5020             :      * to fire.
    5021             :      *
    5022             :      * We loop in case a trigger queues more events at the same query level.
    5023             :      * Ordinary trigger functions, including all PL/pgSQL trigger functions,
    5024             :      * will instead fire any triggers in a dedicated query level.  Foreign key
    5025             :      * enforcement triggers do add to the current query level, thanks to their
    5026             :      * passing fire_triggers = false to SPI_execute_snapshot().  Other
    5027             :      * C-language triggers might do likewise.
    5028             :      *
    5029             :      * If we find no firable events, we don't have to increment
    5030             :      * firing_counter.
    5031             :      */
    5032        7982 :     qs = &afterTriggers.query_stack[afterTriggers.query_depth];
    5033             : 
    5034             :     for (;;)
    5035             :     {
    5036        8288 :         if (afterTriggerMarkEvents(&qs->events, &afterTriggers.events, true))
    5037             :         {
    5038        6530 :             CommandId   firing_id = afterTriggers.firing_counter++;
    5039        6530 :             AfterTriggerEventChunk *oldtail = qs->events.tail;
    5040             : 
    5041        6530 :             if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
    5042        5354 :                 break;          /* all fired */
    5043             : 
    5044             :             /*
    5045             :              * Firing a trigger could result in query_stack being repalloc'd,
    5046             :              * so we must recalculate qs after each afterTriggerInvokeEvents
    5047             :              * call.  Furthermore, it's unsafe to pass delete_ok = true here,
    5048             :              * because that could cause afterTriggerInvokeEvents to try to
    5049             :              * access qs->events after the stack has been repalloc'd.
    5050             :              */
    5051         306 :             qs = &afterTriggers.query_stack[afterTriggers.query_depth];
    5052             : 
    5053             :             /*
    5054             :              * We'll need to scan the events list again.  To reduce the cost
    5055             :              * of doing so, get rid of completely-fired chunks.  We know that
    5056             :              * all events were marked IN_PROGRESS or DONE at the conclusion of
    5057             :              * afterTriggerMarkEvents, so any still-interesting events must
    5058             :              * have been added after that, and so must be in the chunk that
    5059             :              * was then the tail chunk, or in later chunks.  So, zap all
    5060             :              * chunks before oldtail.  This is approximately the same set of
    5061             :              * events we would have gotten rid of by passing delete_ok = true.
    5062             :              */
    5063             :             Assert(oldtail != NULL);
    5064         306 :             while (qs->events.head != oldtail)
    5065           0 :                 afterTriggerDeleteHeadEventChunk(qs);
    5066             :         }
    5067             :         else
    5068        1746 :             break;
    5069             :     }
    5070             : 
    5071             :     /* Release query-level-local storage, including tuplestores if any */
    5072        7100 :     AfterTriggerFreeQuery(&afterTriggers.query_stack[afterTriggers.query_depth]);
    5073             : 
    5074        7100 :     afterTriggers.query_depth--;
    5075             : }
    5076             : 
    5077             : 
    5078             : /*
    5079             :  * AfterTriggerFreeQuery
    5080             :  *  Release subsidiary storage for a trigger query level.
    5081             :  *  This includes closing down tuplestores.
    5082             :  *  Note: it's important for this to be safe if interrupted by an error
    5083             :  *  and then called again for the same query level.
    5084             :  */
    5085             : static void
    5086        7130 : AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
    5087             : {
    5088             :     Tuplestorestate *ts;
    5089             :     List       *tables;
    5090             :     ListCell   *lc;
    5091             : 
    5092             :     /* Drop the trigger events */
    5093        7130 :     afterTriggerFreeEventList(&qs->events);
    5094             : 
    5095             :     /* Drop FDW tuplestore if any */
    5096        7130 :     ts = qs->fdw_tuplestore;
    5097        7130 :     qs->fdw_tuplestore = NULL;
    5098        7130 :     if (ts)
    5099          36 :         tuplestore_end(ts);
    5100             : 
    5101             :     /* Release per-table subsidiary storage */
    5102        7130 :     tables = qs->tables;
    5103        8094 :     foreach(lc, tables)
    5104             :     {
    5105         964 :         AfterTriggersTableData *table = (AfterTriggersTableData *) lfirst(lc);
    5106             : 
    5107         964 :         ts = table->old_upd_tuplestore;
    5108         964 :         table->old_upd_tuplestore = NULL;
    5109         964 :         if (ts)
    5110         150 :             tuplestore_end(ts);
    5111         964 :         ts = table->new_upd_tuplestore;
    5112         964 :         table->new_upd_tuplestore = NULL;
    5113         964 :         if (ts)
    5114         156 :             tuplestore_end(ts);
    5115         964 :         ts = table->old_del_tuplestore;
    5116         964 :         table->old_del_tuplestore = NULL;
    5117         964 :         if (ts)
    5118         120 :             tuplestore_end(ts);
    5119         964 :         ts = table->new_ins_tuplestore;
    5120         964 :         table->new_ins_tuplestore = NULL;
    5121         964 :         if (ts)
    5122         204 :             tuplestore_end(ts);
    5123         964 :         if (table->storeslot)
    5124             :         {
    5125          84 :             TupleTableSlot *slot = table->storeslot;
    5126             : 
    5127          84 :             table->storeslot = NULL;
    5128          84 :             ExecDropSingleTupleTableSlot(slot);
    5129             :         }
    5130             :     }
    5131             : 
    5132             :     /*
    5133             :      * Now free the AfterTriggersTableData structs and list cells.  Reset list
    5134             :      * pointer first; if list_free_deep somehow gets an error, better to leak
    5135             :      * that storage than have an infinite loop.
    5136             :      */
    5137        7130 :     qs->tables = NIL;
    5138        7130 :     list_free_deep(tables);
    5139        7130 : }
    5140             : 
    5141             : 
    5142             : /* ----------
    5143             :  * AfterTriggerFireDeferred()
    5144             :  *
    5145             :  *  Called just before the current transaction is committed. At this
    5146             :  *  time we invoke all pending DEFERRED triggers.
    5147             :  *
    5148             :  *  It is possible for other modules to queue additional deferred triggers
    5149             :  *  during pre-commit processing; therefore xact.c may have to call this
    5150             :  *  multiple times.
    5151             :  * ----------
    5152             :  */
    5153             : void
    5154      949314 : AfterTriggerFireDeferred(void)
    5155             : {
    5156             :     AfterTriggerEventList *events;
    5157      949314 :     bool        snap_pushed = false;
    5158             : 
    5159             :     /* Must not be inside a query */
    5160             :     Assert(afterTriggers.query_depth == -1);
    5161             : 
    5162             :     /*
    5163             :      * If there are any triggers to fire, make sure we have set a snapshot for
    5164             :      * them to use.  (Since PortalRunUtility doesn't set a snap for COMMIT, we
    5165             :      * can't assume ActiveSnapshot is valid on entry.)
    5166             :      */
    5167      949314 :     events = &afterTriggers.events;
    5168      949314 :     if (events->head != NULL)
    5169             :     {
    5170         274 :         PushActiveSnapshot(GetTransactionSnapshot());
    5171         274 :         snap_pushed = true;
    5172             :     }
    5173             : 
    5174             :     /*
    5175             :      * Run all the remaining triggers.  Loop until they are all gone, in case
    5176             :      * some trigger queues more for us to do.
    5177             :      */
    5178      949314 :     while (afterTriggerMarkEvents(events, NULL, false))
    5179             :     {
    5180         274 :         CommandId   firing_id = afterTriggers.firing_counter++;
    5181             : 
    5182         274 :         if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
    5183         162 :             break;              /* all fired */
    5184             :     }
    5185             : 
    5186             :     /*
    5187             :      * We don't bother freeing the event list, since it will go away anyway
    5188             :      * (and more efficiently than via pfree) in AfterTriggerEndXact.
    5189             :      */
    5190             : 
    5191      949202 :     if (snap_pushed)
    5192         162 :         PopActiveSnapshot();
    5193      949202 : }
    5194             : 
    5195             : 
    5196             : /* ----------
    5197             :  * AfterTriggerEndXact()
    5198             :  *
    5199             :  *  The current transaction is finishing.
    5200             :  *
    5201             :  *  Any unfired triggers are canceled so we simply throw
    5202             :  *  away anything we know.
    5203             :  *
    5204             :  *  Note: it is possible for this to be called repeatedly in case of
    5205             :  *  error during transaction abort; therefore, do not complain if
    5206             :  *  already closed down.
    5207             :  * ----------
    5208             :  */
    5209             : void
    5210      975996 : AfterTriggerEndXact(bool isCommit)
    5211             : {
    5212             :     /*
    5213             :      * Forget the pending-events list.
    5214             :      *
    5215             :      * Since all the info is in TopTransactionContext or children thereof, we
    5216             :      * don't really need to do anything to reclaim memory.  However, the
    5217             :      * pending-events list could be large, and so it's useful to discard it as
    5218             :      * soon as possible --- especially if we are aborting because we ran out
    5219             :      * of memory for the list!
    5220             :      */
    5221      975996 :     if (afterTriggers.event_cxt)
    5222             :     {
    5223        5836 :         MemoryContextDelete(afterTriggers.event_cxt);
    5224        5836 :         afterTriggers.event_cxt = NULL;
    5225        5836 :         afterTriggers.events.head = NULL;
    5226        5836 :         afterTriggers.events.tail = NULL;
    5227        5836 :         afterTriggers.events.tailfree = NULL;
    5228             :     }
    5229             : 
    5230             :     /*
    5231             :      * Forget any subtransaction state as well.  Since this can't be very
    5232             :      * large, we let the eventual reset of TopTransactionContext free the
    5233             :      * memory instead of doing it here.
    5234             :      */
    5235      975996 :     afterTriggers.trans_stack = NULL;
    5236      975996 :     afterTriggers.maxtransdepth = 0;
    5237             : 
    5238             : 
    5239             :     /*
    5240             :      * Forget the query stack and constraint-related state information.  As
    5241             :      * with the subtransaction state information, we don't bother freeing the
    5242             :      * memory here.
    5243             :      */
    5244      975996 :     afterTriggers.query_stack = NULL;
    5245      975996 :     afterTriggers.maxquerydepth = 0;
    5246      975996 :     afterTriggers.state = NULL;
    5247             : 
    5248             :     /* No more afterTriggers manipulation until next transaction starts. */
    5249      975996 :     afterTriggers.query_depth = -1;
    5250      975996 : }
    5251             : 
    5252             : /*
    5253             :  * AfterTriggerBeginSubXact()
    5254             :  *
    5255             :  *  Start a subtransaction.
    5256             :  */
    5257             : void
    5258       17596 : AfterTriggerBeginSubXact(void)
    5259             : {
    5260       17596 :     int         my_level = GetCurrentTransactionNestLevel();
    5261             : 
    5262             :     /*
    5263             :      * Allocate more space in the trans_stack if needed.  (Note: because the
    5264             :      * minimum nest level of a subtransaction is 2, we waste the first couple
    5265             :      * entries of the array; not worth the notational effort to avoid it.)
    5266             :      */
    5267       20320 :     while (my_level >= afterTriggers.maxtransdepth)
    5268             :     {
    5269        2724 :         if (afterTriggers.maxtransdepth == 0)
    5270             :         {
    5271             :             /* Arbitrarily initialize for max of 8 subtransaction levels */
    5272        2640 :             afterTriggers.trans_stack = (AfterTriggersTransData *)
    5273        2640 :                 MemoryContextAlloc(TopTransactionContext,
    5274             :                                    8 * sizeof(AfterTriggersTransData));
    5275        2640 :             afterTriggers.maxtransdepth = 8;
    5276             :         }
    5277             :         else
    5278             :         {
    5279             :             /* repalloc will keep the stack in the same context */
    5280          84 :             int         new_alloc = afterTriggers.maxtransdepth * 2;
    5281             : 
    5282          84 :             afterTriggers.trans_stack = (AfterTriggersTransData *)
    5283          84 :                 repalloc(afterTriggers.trans_stack,
    5284             :                          new_alloc * sizeof(AfterTriggersTransData));
    5285          84 :             afterTriggers.maxtransdepth = new_alloc;
    5286             :         }
    5287             :     }
    5288             : 
    5289             :     /*
    5290             :      * Push the current information into the stack.  The SET CONSTRAINTS state
    5291             :      * is not saved until/unless changed.  Likewise, we don't make a
    5292             :      * per-subtransaction event context until needed.
    5293             :      */
    5294       17596 :     afterTriggers.trans_stack[my_level].state = NULL;
    5295       17596 :     afterTriggers.trans_stack[my_level].events = afterTriggers.events;
    5296       17596 :     afterTriggers.trans_stack[my_level].query_depth = afterTriggers.query_depth;
    5297       17596 :     afterTriggers.trans_stack[my_level].firing_counter = afterTriggers.firing_counter;
    5298       17596 : }
    5299             : 
    5300             : /*
    5301             :  * AfterTriggerEndSubXact()
    5302             :  *
    5303             :  *  The current subtransaction is ending.
    5304             :  */
    5305             : void
    5306       17596 : AfterTriggerEndSubXact(bool isCommit)
    5307             : {
    5308       17596 :     int         my_level = GetCurrentTransactionNestLevel();
    5309             :     SetConstraintState state;
    5310             :     AfterTriggerEvent event;
    5311             :     AfterTriggerEventChunk *chunk;
    5312             :     CommandId   subxact_firing_id;
    5313             : 
    5314             :     /*
    5315             :      * Pop the prior state if needed.
    5316             :      */
    5317       17596 :     if (isCommit)
    5318             :     {
    5319             :         Assert(my_level < afterTriggers.maxtransdepth);
    5320             :         /* If we saved a prior state, we don't need it anymore */
    5321        8636 :         state = afterTriggers.trans_stack[my_level].state;
    5322        8636 :         if (state != NULL)
    5323           6 :             pfree(state);
    5324             :         /* this avoids double pfree if error later: */
    5325        8636 :         afterTriggers.trans_stack[my_level].state = NULL;
    5326             :         Assert(afterTriggers.query_depth ==
    5327             :                afterTriggers.trans_stack[my_level].query_depth);
    5328             :     }
    5329             :     else
    5330             :     {
    5331             :         /*
    5332             :          * Aborting.  It is possible subxact start failed before calling
    5333             :          * AfterTriggerBeginSubXact, in which case we mustn't risk touching
    5334             :          * trans_stack levels that aren't there.
    5335             :          */
    5336        8960 :         if (my_level >= afterTriggers.maxtransdepth)
    5337           0 :             return;
    5338             : 
    5339             :         /*
    5340             :          * Release query-level storage for queries being aborted, and restore
    5341             :          * query_depth to its pre-subxact value.  This assumes that a
    5342             :          * subtransaction will not add events to query levels started in a
    5343             :          * earlier transaction state.
    5344             :          */
    5345        9050 :         while (afterTriggers.query_depth > afterTriggers.trans_stack[my_level].query_depth)
    5346             :         {
    5347          90 :             if (afterTriggers.query_depth < afterTriggers.maxquerydepth)
    5348          30 :                 AfterTriggerFreeQuery(&afterTriggers.query_stack[afterTriggers.query_depth]);
    5349          90 :             afterTriggers.query_depth--;
    5350             :         }
    5351             :         Assert(afterTriggers.query_depth ==
    5352             :                afterTriggers.trans_stack[my_level].query_depth);
    5353             : 
    5354             :         /*
    5355             :          * Restore the global deferred-event list to its former length,
    5356             :          * discarding any events queued by the subxact.
    5357             :          */
    5358        8960 :         afterTriggerRestoreEventList(&afterTriggers.events,
    5359        8960 :                                      &afterTriggers.trans_stack[my_level].events);
    5360             : 
    5361             :         /*
    5362             :          * Restore the trigger state.  If the saved state is NULL, then this
    5363             :          * subxact didn't save it, so it doesn't need restoring.
    5364             :          */
    5365        8960 :         state = afterTriggers.trans_stack[my_level].state;
    5366        8960 :         if (state != NULL)
    5367             :         {
    5368           4 :             pfree(afterTriggers.state);
    5369           4 :             afterTriggers.state = state;
    5370             :         }
    5371             :         /* this avoids double pfree if error later: */
    5372        8960 :         afterTriggers.trans_stack[my_level].state = NULL;
    5373             : 
    5374             :         /*
    5375             :          * Scan for any remaining deferred events that were marked DONE or IN
    5376             :          * PROGRESS by this subxact or a child, and un-mark them. We can
    5377             :          * recognize such events because they have a firing ID greater than or
    5378             :          * equal to the firing_counter value we saved at subtransaction start.
    5379             :          * (This essentially assumes that the current subxact includes all
    5380             :          * subxacts started after it.)
    5381             :          */
    5382        8960 :         subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
    5383        9004 :         for_each_event_chunk(event, chunk, afterTriggers.events)
    5384             :         {
    5385          22 :             AfterTriggerShared evtshared = GetTriggerSharedData(event);
    5386             : 
    5387          22 :             if (event->ate_flags &
    5388             :                 (AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS))
    5389             :             {
    5390           4 :                 if (evtshared->ats_firing_id >= subxact_firing_id)
    5391           4 :                     event->ate_flags &=
    5392             :                         ~(AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS);
    5393             :             }
    5394             :         }
    5395             :     }
    5396             : }
    5397             : 
    5398             : /*
    5399             :  * Get the transition table for the given event and depending on whether we are
    5400             :  * processing the old or the new tuple.
    5401             :  */
    5402             : static Tuplestorestate *
    5403       66084 : GetAfterTriggersTransitionTable(int event,
    5404             :                                 TupleTableSlot *oldslot,
    5405             :                                 TupleTableSlot *newslot,
    5406             :                                 TransitionCaptureState *transition_capture)
    5407             : {
    5408       66084 :     Tuplestorestate *tuplestore = NULL;
    5409       66084 :     bool        delete_old_table = transition_capture->tcs_delete_old_table;
    5410       66084 :     bool        update_old_table = transition_capture->tcs_update_old_table;
    5411       66084 :     bool        update_new_table = transition_capture->tcs_update_new_table;
    5412       66084 :     bool        insert_new_table = transition_capture->tcs_insert_new_table;
    5413             : 
    5414             :     /*
    5415             :      * For INSERT events NEW should be non-NULL, for DELETE events OLD should
    5416             :      * be non-NULL, whereas for UPDATE events normally both OLD and NEW are
    5417             :      * non-NULL.  But for UPDATE events fired for capturing transition tuples
    5418             :      * during UPDATE partition-key row movement, OLD is NULL when the event is
    5419             :      * for a row being inserted, whereas NEW is NULL when the event is for a
    5420             :      * row being deleted.
    5421             :      */
    5422             :     Assert(!(event == TRIGGER_EVENT_DELETE && delete_old_table &&
    5423             :              TupIsNull(oldslot)));
    5424             :     Assert(!(event == TRIGGER_EVENT_INSERT && insert_new_table &&
    5425             :              TupIsNull(newslot)));
    5426             : 
    5427       66084 :     if (!TupIsNull(oldslot))
    5428             :     {
    5429             :         Assert(TupIsNull(newslot));
    5430        5394 :         if (event == TRIGGER_EVENT_DELETE && delete_old_table)
    5431        5040 :             tuplestore = transition_capture->tcs_private->old_del_tuplestore;
    5432         354 :         else if (event == TRIGGER_EVENT_UPDATE && update_old_table)
    5433         330 :             tuplestore = transition_capture->tcs_private->old_upd_tuplestore;
    5434             :     }
    5435       60690 :     else if (!TupIsNull(newslot))
    5436             :     {
    5437             :         Assert(TupIsNull(oldslot));
    5438       60690 :         if (event == TRIGGER_EVENT_INSERT && insert_new_table)
    5439       60336 :             tuplestore = transition_capture->tcs_private->new_ins_tuplestore;
    5440         354 :         else if (event == TRIGGER_EVENT_UPDATE && update_new_table)
    5441         348 :             tuplestore = transition_capture->tcs_private->new_upd_tuplestore;
    5442             :     }
    5443             : 
    5444       66084 :     return tuplestore;
    5445             : }
    5446             : 
    5447             : /*
    5448             :  * Add the given heap tuple to the given tuplestore, applying the conversion
    5449             :  * map if necessary.
    5450             :  *
    5451             :  * If original_insert_tuple is given, we can add that tuple without conversion.
    5452             :  */
    5453             : static void
    5454       66084 : TransitionTableAddTuple(EState *estate,
    5455             :                         TransitionCaptureState *transition_capture,
    5456             :                         ResultRelInfo *relinfo,
    5457             :                         TupleTableSlot *slot,
    5458             :                         TupleTableSlot *original_insert_tuple,
    5459             :                         Tuplestorestate *tuplestore)
    5460             : {
    5461             :     TupleConversionMap *map;
    5462             : 
    5463             :     /*
    5464             :      * Nothing needs to be done if we don't have a tuplestore.
    5465             :      */
    5466       66084 :     if (tuplestore == NULL)
    5467          30 :         return;
    5468             : 
    5469       66054 :     if (original_insert_tuple)
    5470         126 :         tuplestore_puttupleslot(tuplestore, original_insert_tuple);
    5471       65928 :     else if ((map = ExecGetChildToRootMap(relinfo)) != NULL)
    5472             :     {
    5473         294 :         AfterTriggersTableData *table = transition_capture->tcs_private;
    5474             :         TupleTableSlot *storeslot;
    5475             : 
    5476         294 :         storeslot = GetAfterTriggersStoreSlot(table, map->outdesc);
    5477         294 :         execute_attr_map_slot(map->attrMap, slot, storeslot);
    5478         294 :         tuplestore_puttupleslot(tuplestore, storeslot);
    5479             :     }
    5480             :     else
    5481       65634 :         tuplestore_puttupleslot(tuplestore, slot);
    5482             : }
    5483             : 
    5484             : /* ----------
    5485             :  * AfterTriggerEnlargeQueryState()
    5486             :  *
    5487             :  *  Prepare the necessary state so that we can record AFTER trigger events
    5488             :  *  queued by a query.  It is allowed to have nested queries within a
    5489             :  *  (sub)transaction, so we need to have separate state for each query
    5490             :  *  nesting level.
    5491             :  * ----------
    5492             :  */
    5493             : static void
    5494        6148 : AfterTriggerEnlargeQueryState(void)
    5495             : {
    5496        6148 :     int         init_depth = afterTriggers.maxquerydepth;
    5497             : 
    5498             :     Assert(afterTriggers.query_depth >= afterTriggers.maxquerydepth);
    5499             : 
    5500        6148 :     if (afterTriggers.maxquerydepth == 0)
    5501             :     {
    5502        6148 :         int         new_alloc = Max(afterTriggers.query_depth + 1, 8);
    5503             : 
    5504        6148 :         afterTriggers.query_stack = (AfterTriggersQueryData *)
    5505        6148 :             MemoryContextAlloc(TopTransactionContext,
    5506             :                                new_alloc * sizeof(AfterTriggersQueryData));
    5507        6148 :         afterTriggers.maxquerydepth = new_alloc;
    5508             :     }
    5509             :     else
    5510             :     {
    5511             :         /* repalloc will keep the stack in the same context */
    5512           0 :         int         old_alloc = afterTriggers.maxquerydepth;
    5513           0 :         int         new_alloc = Max(afterTriggers.query_depth + 1,
    5514             :                                     old_alloc * 2);
    5515             : 
    5516           0 :         afterTriggers.query_stack = (AfterTriggersQueryData *)
    5517           0 :             repalloc(afterTriggers.query_stack,
    5518             :                      new_alloc * sizeof(AfterTriggersQueryData));
    5519           0 :         afterTriggers.maxquerydepth = new_alloc;
    5520             :     }
    5521             : 
    5522             :     /* Initialize new array entries to empty */
    5523       55332 :     while (init_depth < afterTriggers.maxquerydepth)
    5524             :     {
    5525       49184 :         AfterTriggersQueryData *qs = &afterTriggers.query_stack[init_depth];
    5526             : 
    5527       49184 :         qs->events.head = NULL;
    5528       49184 :         qs->events.tail = NULL;
    5529       49184 :         qs->events.tailfree = NULL;
    5530       49184 :         qs->fdw_tuplestore = NULL;
    5531       49184 :         qs->tables = NIL;
    5532             : 
    5533       49184 :         ++init_depth;
    5534             :     }
    5535        6148 : }
    5536             : 
    5537             : /*
    5538             :  * Create an empty SetConstraintState with room for numalloc trigstates
    5539             :  */
    5540             : static SetConstraintState
    5541          96 : SetConstraintStateCreate(int numalloc)
    5542             : {
    5543             :     SetConstraintState state;
    5544             : 
    5545             :     /* Behave sanely with numalloc == 0 */
    5546          96 :     if (numalloc <= 0)
    5547          10 :         numalloc = 1;
    5548             : 
    5549             :     /*
    5550             :      * We assume that zeroing will correctly initialize the state values.
    5551             :      */
    5552             :     state = (SetConstraintState)
    5553          96 :         MemoryContextAllocZero(TopTransactionContext,
    5554             :                                offsetof(SetConstraintStateData, trigstates) +
    5555          96 :                                numalloc * sizeof(SetConstraintTriggerData));
    5556             : 
    5557          96 :     state->numalloc = numalloc;
    5558             : 
    5559          96 :     return state;
    5560             : }
    5561             : 
    5562             : /*
    5563             :  * Copy a SetConstraintState
    5564             :  */
    5565             : static SetConstraintState
    5566          10 : SetConstraintStateCopy(SetConstraintState origstate)
    5567             : {
    5568             :     SetConstraintState state;
    5569             : 
    5570          10 :     state = SetConstraintStateCreate(origstate->numstates);
    5571             : 
    5572          10 :     state->all_isset = origstate->all_isset;
    5573          10 :     state->all_isdeferred = origstate->all_isdeferred;
    5574          10 :     state->numstates = origstate->numstates;
    5575          10 :     memcpy(state->trigstates, origstate->trigstates,
    5576          10 :            origstate->numstates * sizeof(SetConstraintTriggerData));
    5577             : 
    5578          10 :     return state;
    5579             : }
    5580             : 
    5581             : /*
    5582             :  * Add a per-trigger item to a SetConstraintState.  Returns possibly-changed
    5583             :  * pointer to the state object (it will change if we have to repalloc).
    5584             :  */
    5585             : static SetConstraintState
    5586         342 : SetConstraintStateAddItem(SetConstraintState state,
    5587             :                           Oid tgoid, bool tgisdeferred)
    5588             : {
    5589         342 :     if (state->numstates >= state->numalloc)
    5590             :     {
    5591          30 :         int         newalloc = state->numalloc * 2;
    5592             : 
    5593          30 :         newalloc = Max(newalloc, 8);    /* in case original has size 0 */
    5594             :         state = (SetConstraintState)
    5595          30 :             repalloc(state,
    5596             :                      offsetof(SetConstraintStateData, trigstates) +
    5597          30 :                      newalloc * sizeof(SetConstraintTriggerData));
    5598          30 :         state->numalloc = newalloc;
    5599             :         Assert(state->numstates < state->numalloc);
    5600             :     }
    5601             : 
    5602         342 :     state->trigstates[state->numstates].sct_tgoid = tgoid;
    5603         342 :     state->trigstates[state->numstates].sct_tgisdeferred = tgisdeferred;
    5604         342 :     state->numstates++;
    5605             : 
    5606         342 :     return state;
    5607             : }
    5608             : 
    5609             : /* ----------
    5610             :  * AfterTriggerSetState()
    5611             :  *
    5612             :  *  Execute the SET CONSTRAINTS ... utility command.
    5613             :  * ----------
    5614             :  */
    5615             : void
    5616         102 : AfterTriggerSetState(ConstraintsSetStmt *stmt)
    5617             : {
    5618         102 :     int         my_level = GetCurrentTransactionNestLevel();
    5619             : 
    5620             :     /* If we haven't already done so, initialize our state. */
    5621         102 :     if (afterTriggers.state == NULL)
    5622          86 :         afterTriggers.state = SetConstraintStateCreate(8);
    5623             : 
    5624             :     /*
    5625             :      * If in a subtransaction, and we didn't save the current state already,
    5626             :      * save it so it can be restored if the subtransaction aborts.
    5627             :      */
    5628         102 :     if (my_level > 1 &&
    5629          10 :         afterTriggers.trans_stack[my_level].state == NULL)
    5630             :     {
    5631          10 :         afterTriggers.trans_stack[my_level].state =
    5632          10 :             SetConstraintStateCopy(afterTriggers.state);
    5633             :     }
    5634             : 
    5635             :     /*
    5636             :      * Handle SET CONSTRAINTS ALL ...
    5637             :      */
    5638         102 :     if (stmt->constraints == NIL)
    5639             :     {
    5640             :         /*
    5641             :          * Forget any previous SET CONSTRAINTS commands in this transaction.
    5642             :          */
    5643          54 :         afterTriggers.state->numstates = 0;
    5644             : 
    5645             :         /*
    5646             :          * Set the per-transaction ALL state to known.
    5647             :          */
    5648          54 :         afterTriggers.state->all_isset = true;
    5649          54 :         afterTriggers.state->all_isdeferred = stmt->deferred;
    5650             :     }
    5651             :     else
    5652             :     {
    5653             :         Relation    conrel;
    5654             :         Relation    tgrel;
    5655          48 :         List       *conoidlist = NIL;
    5656          48 :         List       *tgoidlist = NIL;
    5657             :         ListCell   *lc;
    5658             : 
    5659             :         /*
    5660             :          * Handle SET CONSTRAINTS constraint-name [, ...]
    5661             :          *
    5662             :          * First, identify all the named constraints and make a list of their
    5663             :          * OIDs.  Since, unlike the SQL spec, we allow multiple constraints of
    5664             :          * the same name within a schema, the specifications are not
    5665             :          * necessarily unique.  Our strategy is to target all matching
    5666             :          * constraints within the first search-path schema that has any
    5667             :          * matches, but disregard matches in schemas beyond the first match.
    5668             :          * (This is a bit odd but it's the historical behavior.)
    5669             :          *
    5670             :          * A constraint in a partitioned table may have corresponding
    5671             :          * constraints in the partitions.  Grab those too.
    5672             :          */
    5673          48 :         conrel = table_open(ConstraintRelationId, AccessShareLock);
    5674             : 
    5675          96 :         foreach(lc, stmt->constraints)
    5676             :         {
    5677          48 :             RangeVar   *constraint = lfirst(lc);
    5678             :             bool        found;
    5679             :             List       *namespacelist;
    5680             :             ListCell   *nslc;
    5681             : 
    5682          48 :             if (constraint->catalogname)
    5683             :             {
    5684           0 :                 if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
    5685           0 :                     ereport(ERROR,
    5686             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5687             :                              errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
    5688             :                                     constraint->catalogname, constraint->schemaname,
    5689             :                                     constraint->relname)));
    5690             :             }
    5691             : 
    5692             :             /*
    5693             :              * If we're given the schema name with the constraint, look only
    5694             :              * in that schema.  If given a bare constraint name, use the
    5695             :              * search path to find the first matching constraint.
    5696             :              */
    5697          48 :             if (constraint->schemaname)
    5698             :             {
    5699          12 :                 Oid         namespaceId = LookupExplicitNamespace(constraint->schemaname,
    5700             :                                                                   false);
    5701             : 
    5702          12 :                 namespacelist = list_make1_oid(namespaceId);
    5703             :             }
    5704             :             else
    5705             :             {
    5706          36 :                 namespacelist = fetch_search_path(true);
    5707             :             }
    5708             : 
    5709          48 :             found = false;
    5710         120 :             foreach(nslc, namespacelist)
    5711             :             {
    5712         120 :                 Oid         namespaceId = lfirst_oid(nslc);
    5713             :                 SysScanDesc conscan;
    5714             :                 ScanKeyData skey[2];
    5715             :                 HeapTuple   tup;
    5716             : 
    5717         120 :                 ScanKeyInit(&skey[0],
    5718             :                             Anum_pg_constraint_conname,
    5719             :                             BTEqualStrategyNumber, F_NAMEEQ,
    5720         120 :                             CStringGetDatum(constraint->relname));
    5721         120 :                 ScanKeyInit(&skey[1],
    5722             :                             Anum_pg_constraint_connamespace,
    5723             :                             BTEqualStrategyNumber, F_OIDEQ,
    5724             :                             ObjectIdGetDatum(namespaceId));
    5725             : 
    5726         120 :                 conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
    5727             :                                              true, NULL, 2, skey);
    5728             : 
    5729         216 :                 while (HeapTupleIsValid(tup = systable_getnext(conscan)))
    5730             :                 {
    5731          96 :                     Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
    5732             : 
    5733          96 :                     if (con->condeferrable)
    5734          96 :                         conoidlist = lappend_oid(conoidlist, con->oid);
    5735           0 :                     else if (stmt->deferred)
    5736           0 :                         ereport(ERROR,
    5737             :                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    5738             :                                  errmsg("constraint \"%s\" is not deferrable",
    5739             :                                         constraint->relname)));
    5740          96 :                     found = true;
    5741             :                 }
    5742             : 
    5743         120 :                 systable_endscan(conscan);
    5744             : 
    5745             :                 /*
    5746             :                  * Once we've found a matching constraint we do not search
    5747             :                  * later parts of the search path.
    5748             :                  */
    5749         120 :                 if (found)
    5750          48 :                     break;
    5751             :             }
    5752             : 
    5753          48 :             list_free(namespacelist);
    5754             : 
    5755             :             /*
    5756             :              * Not found ?
    5757             :              */
    5758          48 :             if (!found)
    5759           0 :                 ereport(ERROR,
    5760             :                         (errcode(ERRCODE_UNDEFINED_OBJECT),
    5761             :                          errmsg("constraint \"%s\" does not exist",
    5762             :                                 constraint->relname)));
    5763             :         }
    5764             : 
    5765             :         /*
    5766             :          * Scan for any possible descendants of the constraints.  We append
    5767             :          * whatever we find to the same list that we're scanning; this has the
    5768             :          * effect that we create new scans for those, too, so if there are
    5769             :          * further descendents, we'll also catch them.
    5770             :          */
    5771         258 :         foreach(lc, conoidlist)
    5772             :         {
    5773         210 :             Oid         parent = lfirst_oid(lc);
    5774             :             ScanKeyData key;
    5775             :             SysScanDesc scan;
    5776             :             HeapTuple   tuple;
    5777             : 
    5778         210 :             ScanKeyInit(&key,
    5779             :                         Anum_pg_constraint_conparentid,
    5780             :                         BTEqualStrategyNumber, F_OIDEQ,
    5781             :                         ObjectIdGetDatum(parent));
    5782             : 
    5783         210 :             scan = systable_beginscan(conrel, ConstraintParentIndexId, true, NULL, 1, &key);
    5784             : 
    5785         324 :             while (HeapTupleIsValid(tuple = systable_getnext(scan)))
    5786             :             {
    5787         114 :                 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
    5788             : 
    5789         114 :                 conoidlist = lappend_oid(conoidlist, con->oid);
    5790             :             }
    5791             : 
    5792         210 :             systable_endscan(scan);
    5793             :         }
    5794             : 
    5795          48 :         table_close(conrel, AccessShareLock);
    5796             : 
    5797             :         /*
    5798             :          * Now, locate the trigger(s) implementing each of these constraints,
    5799             :          * and make a list of their OIDs.
    5800             :          */
    5801          48 :         tgrel = table_open(TriggerRelationId, AccessShareLock);
    5802             : 
    5803         258 :         foreach(lc, conoidlist)
    5804             :         {
    5805         210 :             Oid         conoid = lfirst_oid(lc);
    5806             :             ScanKeyData skey;
    5807             :             SysScanDesc tgscan;
    5808             :             HeapTuple   htup;
    5809             : 
    5810         210 :             ScanKeyInit(&skey,
    5811             :                         Anum_pg_trigger_tgconstraint,
    5812             :                         BTEqualStrategyNumber, F_OIDEQ,
    5813             :                         ObjectIdGetDatum(conoid));
    5814             : 
    5815         210 :             tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
    5816             :                                         NULL, 1, &skey);
    5817             : 
    5818         648 :             while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
    5819             :             {
    5820         438 :                 Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
    5821             : 
    5822             :                 /*
    5823             :                  * Silently skip triggers that are marked as non-deferrable in
    5824             :                  * pg_trigger.  This is not an error condition, since a
    5825             :                  * deferrable RI constraint may have some non-deferrable
    5826             :                  * actions.
    5827             :                  */
    5828         438 :                 if (pg_trigger->tgdeferrable)
    5829         438 :                     tgoidlist = lappend_oid(tgoidlist, pg_trigger->oid);
    5830             :             }
    5831             : 
    5832         210 :             systable_endscan(tgscan);
    5833             :         }
    5834             : 
    5835          48 :         table_close(tgrel, AccessShareLock);
    5836             : 
    5837             :         /*
    5838             :          * Now we can set the trigger states of individual triggers for this
    5839             :          * xact.
    5840             :          */
    5841         486 :         foreach(lc, tgoidlist)
    5842             :         {
    5843         438 :             Oid         tgoid = lfirst_oid(lc);
    5844         438 :             SetConstraintState state = afterTriggers.state;
    5845         438 :             bool        found = false;
    5846             :             int         i;
    5847             : 
    5848        2448 :             for (i = 0; i < state->numstates; i++)
    5849             :             {
    5850        2106 :                 if (state->trigstates[i].sct_tgoid == tgoid)
    5851             :                 {
    5852          96 :                     state->trigstates[i].sct_tgisdeferred = stmt->deferred;
    5853          96 :                     found = true;
    5854          96 :                     break;
    5855             :                 }
    5856             :             }
    5857         438 :             if (!found)
    5858             :             {
    5859         342 :                 afterTriggers.state =
    5860         342 :                     SetConstraintStateAddItem(state, tgoid, stmt->deferred);
    5861             :             }
    5862             :         }
    5863             :     }
    5864             : 
    5865             :     /*
    5866             :      * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
    5867             :      * checks against that constraint must be made when the SET CONSTRAINTS
    5868             :      * command is executed -- i.e. the effects of the SET CONSTRAINTS command
    5869             :      * apply retroactively.  We've updated the constraints state, so scan the
    5870             :      * list of previously deferred events to fire any that have now become
    5871             :      * immediate.
    5872             :      *
    5873             :      * Obviously, if this was SET ... DEFERRED then it can't have converted
    5874             :      * any unfired events to immediate, so we need do nothing in that case.
    5875             :      */
    5876         102 :     if (!stmt->deferred)
    5877             :     {
    5878          34 :         AfterTriggerEventList *events = &afterTriggers.events;
    5879          34 :         bool        snapshot_set = false;
    5880             : 
    5881          34 :         while (afterTriggerMarkEvents(events, NULL, true))
    5882             :         {
    5883          16 :             CommandId   firing_id = afterTriggers.firing_counter++;
    5884             : 
    5885             :             /*
    5886             :              * Make sure a snapshot has been established in case trigger
    5887             :              * functions need one.  Note that we avoid setting a snapshot if
    5888             :              * we don't find at least one trigger that has to be fired now.
    5889             :              * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
    5890             :              * ISOLATION LEVEL SERIALIZABLE; ... works properly.  (If we are
    5891             :              * at the start of a transaction it's not possible for any trigger
    5892             :              * events to be queued yet.)
    5893             :              */
    5894          16 :             if (!snapshot_set)
    5895             :             {
    5896          16 :                 PushActiveSnapshot(GetTransactionSnapshot());
    5897          16 :                 snapshot_set = true;
    5898             :             }
    5899             : 
    5900             :             /*
    5901             :              * We can delete fired events if we are at top transaction level,
    5902             :              * but we'd better not if inside a subtransaction, since the
    5903             :              * subtransaction could later get rolled back.
    5904             :              */
    5905           0 :             if (afterTriggerInvokeEvents(events, firing_id, NULL,
    5906          16 :                                          !IsSubTransaction()))
    5907           0 :                 break;          /* all fired */
    5908             :         }
    5909             : 
    5910          18 :         if (snapshot_set)
    5911           0 :             PopActiveSnapshot();
    5912             :     }
    5913          86 : }
    5914             : 
    5915             : /* ----------
    5916             :  * AfterTriggerPendingOnRel()
    5917             :  *      Test to see if there are any pending after-trigger events for rel.
    5918             :  *
    5919             :  * This is used by TRUNCATE, CLUSTER, ALTER TABLE, etc to detect whether
    5920             :  * it is unsafe to perform major surgery on a relation.  Note that only
    5921             :  * local pending events are examined.  We assume that having exclusive lock
    5922             :  * on a rel guarantees there are no unserviced events in other backends ---
    5923             :  * but having a lock does not prevent there being such events in our own.
    5924             :  *
    5925             :  * In some scenarios it'd be reasonable to remove pending events (more
    5926             :  * specifically, mark them DONE by the current subxact) but without a lot
    5927             :  * of knowledge of the trigger semantics we can't do this in general.
    5928             :  * ----------
    5929             :  */
    5930             : bool
    5931      147738 : AfterTriggerPendingOnRel(Oid relid)
    5932             : {
    5933             :     AfterTriggerEvent event;
    5934             :     AfterTriggerEventChunk *chunk;
    5935             :     int         depth;
    5936             : 
    5937             :     /* Scan queued events */
    5938      147762 :     for_each_event_chunk(event, chunk, afterTriggers.events)
    5939             :     {
    5940          30 :         AfterTriggerShared evtshared = GetTriggerSharedData(event);
    5941             : 
    5942             :         /*
    5943             :          * We can ignore completed events.  (Even if a DONE flag is rolled
    5944             :          * back by subxact abort, it's OK because the effects of the TRUNCATE
    5945             :          * or whatever must get rolled back too.)
    5946             :          */
    5947          30 :         if (event->ate_flags & AFTER_TRIGGER_DONE)
    5948           0 :             continue;
    5949             : 
    5950          30 :         if (evtshared->ats_relid == relid)
    5951          18 :             return true;
    5952             :     }
    5953             : 
    5954             :     /*
    5955             :      * Also scan events queued by incomplete queries.  This could only matter
    5956             :      * if TRUNCATE/etc is executed by a function or trigger within an updating
    5957             :      * query on the same relation, which is pretty perverse, but let's check.
    5958             :      */
    5959      147720 :     for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
    5960             :     {
    5961           0 :         for_each_event_chunk(event, chunk, afterTriggers.query_stack[depth].events)
    5962             :         {
    5963           0 :             AfterTriggerShared evtshared = GetTriggerSharedData(event);
    5964             : 
    5965           0 :             if (event->ate_flags & AFTER_TRIGGER_DONE)
    5966           0 :                 continue;
    5967             : 
    5968           0 :             if (evtshared->ats_relid == relid)
    5969           0 :                 return true;
    5970             :         }
    5971             :     }
    5972             : 
    5973      147720 :     return false;
    5974             : }
    5975             : 
    5976             : /* ----------
    5977             :  * AfterTriggerSaveEvent()
    5978             :  *
    5979             :  *  Called by ExecA[RS]...Triggers() to queue up the triggers that should
    5980             :  *  be fired for an event.
    5981             :  *
    5982             :  *  NOTE: this is called whenever there are any triggers associated with
    5983             :  *  the event (even if they are disabled).  This function decides which
    5984             :  *  triggers actually need to be queued.  It is also called after each row,
    5985             :  *  even if there are no triggers for that event, if there are any AFTER
    5986             :  *  STATEMENT triggers for the statement which use transition tables, so that
    5987             :  *  the transition tuplestores can be built.  Furthermore, if the transition
    5988             :  *  capture is happening for UPDATEd rows being moved to another partition due
    5989             :  *  to the partition-key being changed, then this function is called once when
    5990             :  *  the row is deleted (to capture OLD row), and once when the row is inserted
    5991             :  *  into another partition (to capture NEW row).  This is done separately because
    5992             :  *  DELETE and INSERT happen on different tables.
    5993             :  *
    5994             :  *  Transition tuplestores are built now, rather than when events are pulled
    5995             :  *  off of the queue because AFTER ROW triggers are allowed to select from the
    5996             :  *  transition tables for the statement.
    5997             :  *
    5998             :  *  This contains special support to queue the update events for the case where
    5999             :  *  a partitioned table undergoing a cross-partition update may have foreign
    6000             :  *  keys pointing into it.  Normally, a partitioned table's row triggers are
    6001             :  *  not fired because the leaf partition(s) which are modified as a result of
    6002             :  *  the operation on the partitioned table contain the same triggers which are
    6003             :  *  fired instead. But that general scheme can cause problematic behavior with
    6004             :  *  foreign key triggers during cross-partition updates, which are implemented
    6005             :  *  as DELETE on the source partition followed by INSERT into the destination
    6006             :  *  partition.  Specifically, firing DELETE triggers would lead to the wrong
    6007             :  *  foreign key action to be enforced considering that the original command is
    6008             :  *  UPDATE; in this case, this function is called with relinfo as the
    6009             :  *  partitioned table, and src_partinfo and dst_partinfo referring to the
    6010             :  *  source and target leaf partitions, respectively.
    6011             :  *
    6012             :  *  is_crosspart_update is true either when a DELETE event is fired on the
    6013             :  *  source partition (which is to be ignored) or an UPDATE event is fired on
    6014             :  *  the root partitioned table.
    6015             :  * ----------
    6016             :  */
    6017             : static void
    6018       75518 : AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
    6019             :                       ResultRelInfo *src_partinfo,
    6020             :                       ResultRelInfo *dst_partinfo,
    6021             :                       int event, bool row_trigger,
    6022             :                       TupleTableSlot *oldslot, TupleTableSlot *newslot,
    6023             :                       List *recheckIndexes, Bitmapset *modifiedCols,
    6024             :                       TransitionCaptureState *transition_capture,
    6025             :                       bool is_crosspart_update)
    6026             : {
    6027       75518 :     Relation    rel = relinfo->ri_RelationDesc;
    6028       75518 :     TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
    6029             :     AfterTriggerEventData new_event;
    6030             :     AfterTriggerSharedData new_shared;
    6031       75518 :     char        relkind = rel->rd_rel->relkind;
    6032             :     int         tgtype_event;
    6033             :     int         tgtype_level;
    6034             :     int         i;
    6035       75518 :     Tuplestorestate *fdw_tuplestore = NULL;
    6036             : 
    6037             :     /*
    6038             :      * Check state.  We use a normal test not Assert because it is possible to
    6039             :      * reach here in the wrong state given misconfigured RI triggers, in
    6040             :      * particular deferring a cascade action trigger.
    6041             :      */
    6042       75518 :     if (afterTriggers.query_depth < 0)
    6043           0 :         elog(ERROR, "AfterTriggerSaveEvent() called outside of query");
    6044             : 
    6045             :     /* Be sure we have enough space to record events at this query depth. */
    6046       75518 :     if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
    6047        5428 :         AfterTriggerEnlargeQueryState();
    6048             : 
    6049             :     /*
    6050             :      * If the directly named relation has any triggers with transition tables,
    6051             :      * then we need to capture transition tuples.
    6052             :      */
    6053       75518 :     if (row_trigger && transition_capture != NULL)
    6054             :     {
    6055       65772 :         TupleTableSlot *original_insert_tuple = transition_capture->tcs_original_insert_tuple;
    6056             : 
    6057             :         /*
    6058             :          * Capture the old tuple in the appropriate transition table based on
    6059             :          * the event.
    6060             :          */
    6061       65772 :         if (!TupIsNull(oldslot))
    6062             :         {
    6063             :             Tuplestorestate *old_tuplestore;
    6064             : 
    6065        5394 :             old_tuplestore = GetAfterTriggersTransitionTable(event,
    6066             :                                                              oldslot,
    6067             :                                                              NULL,
    6068             :                                                              transition_capture);
    6069        5394 :             TransitionTableAddTuple(estate, transition_capture, relinfo,
    6070             :                                     oldslot, NULL, old_tuplestore);
    6071             :         }
    6072             : 
    6073             :         /*
    6074             :          * Capture the new tuple in the appropriate transition table based on
    6075             :          * the event.
    6076             :          */
    6077       65772 :         if (!TupIsNull(newslot))
    6078             :         {
    6079             :             Tuplestorestate *new_tuplestore;
    6080             : 
    6081       60690 :             new_tuplestore = GetAfterTriggersTransitionTable(event,
    6082             :                                                              NULL,
    6083             :                                                              newslot,
    6084             :                                                              transition_capture);
    6085       60690 :             TransitionTableAddTuple(estate, transition_capture, relinfo,
    6086             :                                     newslot, original_insert_tuple, new_tuplestore);
    6087             :         }
    6088             : 
    6089             :         /*
    6090             :          * If transition tables are the only reason we're here, return. As
    6091             :          * mentioned above, we can also be here during update tuple routing in
    6092             :          * presence of transition tables, in which case this function is
    6093             :          * called separately for OLD and NEW, so we expect exactly one of them
    6094             :          * to be NULL.
    6095             :          */
    6096       65772 :         if (trigdesc == NULL ||
    6097       65568 :             (event == TRIGGER_EVENT_DELETE && !trigdesc->trig_delete_after_row) ||
    6098       60588 :             (event == TRIGGER_EVENT_INSERT && !trigdesc->trig_insert_after_row) ||
    6099         354 :             (event == TRIGGER_EVENT_UPDATE && !trigdesc->trig_update_after_row) ||
    6100          36 :             (event == TRIGGER_EVENT_UPDATE && (TupIsNull(oldslot) ^ TupIsNull(newslot))))
    6101       65658 :             return;
    6102             :     }
    6103             : 
    6104             :     /*
    6105             :      * We normally don't see partitioned tables here for row level triggers
    6106             :      * except in the special case of a cross-partition update.  In that case,
    6107             :      * nodeModifyTable.c:ExecCrossPartitionUpdateForeignKey() calls here to
    6108             :      * queue an update event on the root target partitioned table, also
    6109             :      * passing the source and destination partitions and their tuples.
    6110             :      */
    6111             :     Assert(!row_trigger ||
    6112             :            rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE ||
    6113             :            (is_crosspart_update &&
    6114             :             TRIGGER_FIRED_BY_UPDATE(event) &&
    6115             :             src_partinfo != NULL && dst_partinfo != NULL));
    6116             : 
    6117             :     /*
    6118             :      * Validate the event code and collect the associated tuple CTIDs.
    6119             :      *
    6120             :      * The event code will be used both as a bitmask and an array offset, so
    6121             :      * validation is important to make sure we don't walk off the edge of our
    6122             :      * arrays.
    6123             :      *
    6124             :      * Also, if we're considering statement-level triggers, check whether we
    6125             :      * already queued a set of them for this event, and cancel the prior set
    6126             :      * if so.  This preserves the behavior that statement-level triggers fire
    6127             :      * just once per statement and fire after row-level triggers.
    6128             :      */
    6129        9860 :     switch (event)
    6130             :     {
    6131        5294 :         case TRIGGER_EVENT_INSERT:
    6132        5294 :             tgtype_event = TRIGGER_TYPE_INSERT;
    6133        5294 :             if (row_trigger)
    6134             :             {
    6135             :                 Assert(oldslot == NULL);
    6136             :                 Assert(newslot != NULL);
    6137        4876 :                 ItemPointerCopy(&(newslot->tts_tid), &(new_event.ate_ctid1));
    6138        4876 :                 ItemPointerSetInvalid(&(new_event.ate_ctid2));
    6139             :             }
    6140             :             else
    6141             :             {
    6142             :                 Assert(oldslot == NULL);
    6143             :                 Assert(newslot == NULL);
    6144         418 :                 ItemPointerSetInvalid(&(new_event.ate_ctid1));
    6145         418 :                 ItemPointerSetInvalid(&(new_event.ate_ctid2));
    6146         418 :                 cancel_prior_stmt_triggers(RelationGetRelid(rel),
    6147             :                                            CMD_INSERT, event);
    6148             :             }
    6149        5294 :             break;
    6150        1212 :         case TRIGGER_EVENT_DELETE:
    6151        1212 :             tgtype_event = TRIGGER_TYPE_DELETE;
    6152        1212 :             if (row_trigger)
    6153             :             {
    6154             :                 Assert(oldslot != NULL);
    6155             :                 Assert(newslot == NULL);
    6156         988 :                 ItemPointerCopy(&(oldslot->tts_tid), &(new_event.ate_ctid1));
    6157         988 :                 ItemPointerSetInvalid(&(new_event.ate_ctid2));
    6158             :             }
    6159             :             else
    6160             :             {
    6161             :                 Assert(oldslot == NULL);
    6162             :                 Assert(newslot == NULL);
    6163         224 :                 ItemPointerSetInvalid(&(new_event.ate_ctid1));
    6164         224 :                 ItemPointerSetInvalid(&(new_event.ate_ctid2));
    6165         224 :                 cancel_prior_stmt_triggers(RelationGetRelid(rel),
    6166             :                                            CMD_DELETE, event);
    6167             :             }
    6168        1212 :             break;
    6169        3346 :         case TRIGGER_EVENT_UPDATE:
    6170        3346 :             tgtype_event = TRIGGER_TYPE_UPDATE;
    6171        3346 :             if (row_trigger)
    6172             :             {
    6173             :                 Assert(oldslot != NULL);
    6174             :                 Assert(newslot != NULL);
    6175        2968 :                 ItemPointerCopy(&(oldslot->tts_tid), &(new_event.ate_ctid1));
    6176        2968 :                 ItemPointerCopy(&(newslot->tts_tid), &(new_event.ate_ctid2));
    6177             : 
    6178             :                 /*
    6179             :                  * Also remember the OIDs of partitions to fetch these tuples
    6180             :                  * out of later in AfterTriggerExecute().
    6181             :                  */
    6182        2968 :                 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    6183             :                 {
    6184             :                     Assert(src_partinfo != NULL && dst_partinfo != NULL);
    6185         222 :                     new_event.ate_src_part =
    6186         222 :                         RelationGetRelid(src_partinfo->ri_RelationDesc);
    6187         222 :                     new_event.ate_dst_part =
    6188         222 :                         RelationGetRelid(dst_partinfo->ri_RelationDesc);
    6189             :                 }
    6190             :             }
    6191             :             else
    6192             :             {
    6193             :                 Assert(oldslot == NULL);
    6194             :                 Assert(newslot == NULL);
    6195         378 :                 ItemPointerSetInvalid(&(new_event.ate_ctid1));
    6196         378 :                 ItemPointerSetInvalid(&(new_event.ate_ctid2));
    6197         378 :                 cancel_prior_stmt_triggers(RelationGetRelid(rel),
    6198             :                                            CMD_UPDATE, event);
    6199             :             }
    6200        3346 :             break;
    6201           8 :         case TRIGGER_EVENT_TRUNCATE:
    6202           8 :             tgtype_event = TRIGGER_TYPE_TRUNCATE;
    6203             :             Assert(oldslot == NULL);
    6204             :             Assert(newslot == NULL);
    6205           8 :             ItemPointerSetInvalid(&(new_event.ate_ctid1));
    6206           8 :             ItemPointerSetInvalid(&(new_event.ate_ctid2));
    6207           8 :             break;
    6208           0 :         default:
    6209           0 :             elog(ERROR, "invalid after-trigger event code: %d", event);
    6210             :             tgtype_event = 0;   /* keep compiler quiet */
    6211             :             break;
    6212             :     }
    6213             : 
    6214             :     /* Determine flags */
    6215        9860 :     if (!(relkind == RELKIND_FOREIGN_TABLE && row_trigger))
    6216             :     {
    6217        9804 :         if (row_trigger && event == TRIGGER_EVENT_UPDATE)
    6218             :         {
    6219        2948 :             if (relkind == RELKIND_PARTITIONED_TABLE)
    6220         222 :                 new_event.ate_flags = AFTER_TRIGGER_CP_UPDATE;
    6221             :             else
    6222        2726 :                 new_event.ate_flags = AFTER_TRIGGER_2CTID;
    6223             :         }
    6224             :         else
    6225        6856 :             new_event.ate_flags = AFTER_TRIGGER_1CTID;
    6226             :     }
    6227             : 
    6228             :     /* else, we'll initialize ate_flags for each trigger */
    6229             : 
    6230        9860 :     tgtype_level = (row_trigger ? TRIGGER_TYPE_ROW : TRIGGER_TYPE_STATEMENT);
    6231             : 
    6232             :     /*
    6233             :      * Must convert/copy the source and destination partition tuples into the
    6234             :      * root partitioned table's format/slot, because the processing in the
    6235             :      * loop below expects both oldslot and newslot tuples to be in that form.
    6236             :      */
    6237        9860 :     if (row_trigger && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    6238             :     {
    6239             :         TupleTableSlot *rootslot;
    6240             :         TupleConversionMap *map;
    6241             : 
    6242         222 :         rootslot = ExecGetTriggerOldSlot(estate, relinfo);
    6243         222 :         map = ExecGetChildToRootMap(src_partinfo);
    6244         222 :         if (map)
    6245          36 :             oldslot = execute_attr_map_slot(map->attrMap,
    6246             :                                             oldslot,
    6247             :                                             rootslot);
    6248             :         else
    6249         186 :             oldslot = ExecCopySlot(rootslot, oldslot);
    6250             : 
    6251         222 :         rootslot = ExecGetTriggerNewSlot(estate, relinfo);
    6252         222 :         map = ExecGetChildToRootMap(dst_partinfo);
    6253         222 :         if (map)
    6254          36 :             newslot = execute_attr_map_slot(map->attrMap,
    6255             :                                             newslot,
    6256             :                                             rootslot);
    6257             :         else
    6258         186 :             newslot = ExecCopySlot(rootslot, newslot);
    6259             :     }
    6260             : 
    6261       46198 :     for (i = 0; i < trigdesc->numtriggers; i++)
    6262             :     {
    6263       36338 :         Trigger    *trigger = &trigdesc->triggers[i];
    6264             : 
    6265       36338 :         if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
    6266             :                                   tgtype_level,
    6267             :                                   TRIGGER_TYPE_AFTER,
    6268             :                                   tgtype_event))
    6269       23518 :             continue;
    6270       12820 :         if (!TriggerEnabled(estate, relinfo, trigger, event,
    6271             :                             modifiedCols, oldslot, newslot))
    6272         368 :             continue;
    6273             : 
    6274       12452 :         if (relkind == RELKIND_FOREIGN_TABLE && row_trigger)
    6275             :         {
    6276          58 :             if (fdw_tuplestore == NULL)
    6277             :             {
    6278          50 :                 fdw_tuplestore = GetCurrentFDWTuplestore();
    6279          50 :                 new_event.ate_flags = AFTER_TRIGGER_FDW_FETCH;
    6280             :             }
    6281             :             else
    6282             :                 /* subsequent event for the same tuple */
    6283           8 :                 new_event.ate_flags = AFTER_TRIGGER_FDW_REUSE;
    6284             :         }
    6285             : 
    6286             :         /*
    6287             :          * If the trigger is a foreign key enforcement trigger, there are
    6288             :          * certain cases where we can skip queueing the event because we can
    6289             :          * tell by inspection that the FK constraint will still pass. There
    6290             :          * are also some cases during cross-partition updates of a partitioned
    6291             :          * table where queuing the event can be skipped.
    6292             :          */
    6293       12452 :         if (TRIGGER_FIRED_BY_UPDATE(event) || TRIGGER_FIRED_BY_DELETE(event))
    6294             :         {
    6295        5972 :             switch (RI_FKey_trigger_type(trigger->tgfoid))
    6296             :             {
    6297        2222 :                 case RI_TRIGGER_PK:
    6298             : 
    6299             :                     /*
    6300             :                      * For cross-partitioned updates of partitioned PK table,
    6301             :                      * skip the event fired by the component delete on the
    6302             :                      * source leaf partition unless the constraint originates
    6303             :                      * in the partition itself (!tgisclone), because the
    6304             :                      * update event that will be fired on the root
    6305             :                      * (partitioned) target table will be used to perform the
    6306             :                      * necessary foreign key enforcement action.
    6307             :                      */
    6308        2222 :                     if (is_crosspart_update &&
    6309         498 :                         TRIGGER_FIRED_BY_DELETE(event) &&
    6310         264 :                         trigger->tgisclone)
    6311         246 :                         continue;
    6312             : 
    6313             :                     /* Update or delete on trigger's PK table */
    6314        1976 :                     if (!RI_FKey_pk_upd_check_required(trigger, rel,
    6315             :                                                        oldslot, newslot))
    6316             :                     {
    6317             :                         /* skip queuing this event */
    6318         542 :                         continue;
    6319             :                     }
    6320        1434 :                     break;
    6321             : 
    6322        1080 :                 case RI_TRIGGER_FK:
    6323             : 
    6324             :                     /*
    6325             :                      * Update on trigger's FK table.  We can skip the update
    6326             :                      * event fired on a partitioned table during a
    6327             :                      * cross-partition of that table, because the insert event
    6328             :                      * that is fired on the destination leaf partition would
    6329             :                      * suffice to perform the necessary foreign key check.
    6330             :                      * Moreover, RI_FKey_fk_upd_check_required() expects to be
    6331             :                      * passed a tuple that contains system attributes, most of
    6332             :                      * which are not present in the virtual slot belonging to
    6333             :                      * a partitioned table.
    6334             :                      */
    6335        1080 :                     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
    6336        1014 :                         !RI_FKey_fk_upd_check_required(trigger, rel,
    6337             :                                                        oldslot, newslot))
    6338             :                     {
    6339             :                         /* skip queuing this event */
    6340         650 :                         continue;
    6341             :                     }
    6342         430 :                     break;
    6343             : 
    6344        2670 :                 case RI_TRIGGER_NONE:
    6345             : 
    6346             :                     /*
    6347             :                      * Not an FK trigger.  No need to queue the update event
    6348             :                      * fired during a cross-partitioned update of a
    6349             :                      * partitioned table, because the same row trigger must be
    6350             :                      * present in the leaf partition(s) that are affected as
    6351             :                      * part of this update and the events fired on them are
    6352             :                      * queued instead.
    6353             :                      */
    6354        2670 :                     if (row_trigger &&
    6355        2032 :                         rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    6356          18 :                         continue;
    6357        2652 :                     break;
    6358             :             }
    6359        6480 :         }
    6360             : 
    6361             :         /*
    6362             :          * If the trigger is a deferred unique constraint check trigger, only
    6363             :          * queue it if the unique constraint was potentially violated, which
    6364             :          * we know from index insertion time.
    6365             :          */
    6366       10996 :         if (trigger->tgfoid == F_UNIQUE_KEY_RECHECK)
    6367             :         {
    6368         210 :             if (!list_member_oid(recheckIndexes, trigger->tgconstrindid))
    6369          88 :                 continue;       /* Uniqueness definitely not violated */
    6370             :         }
    6371             : 
    6372             :         /*
    6373             :          * Fill in event structure and add it to the current query's queue.
    6374             :          * Note we set ats_table to NULL whenever this trigger doesn't use
    6375             :          * transition tables, to improve sharability of the shared event data.
    6376             :          */
    6377       10908 :         new_shared.ats_event =
    6378       21816 :             (event & TRIGGER_EVENT_OPMASK) |
    6379       10908 :             (row_trigger ? TRIGGER_EVENT_ROW : 0) |
    6380       10908 :             (trigger->tgdeferrable ? AFTER_TRIGGER_DEFERRABLE : 0) |
    6381       10908 :             (trigger->tginitdeferred ? AFTER_TRIGGER_INITDEFERRED : 0);
    6382       10908 :         new_shared.ats_tgoid = trigger->tgoid;
    6383       10908 :         new_shared.ats_relid = RelationGetRelid(rel);
    6384       10908 :         new_shared.ats_firing_id = 0;
    6385       10908 :         if ((trigger->tgoldtable || trigger->tgnewtable) &&
    6386             :             transition_capture != NULL)
    6387         606 :             new_shared.ats_table = transition_capture->tcs_private;
    6388             :         else
    6389       10302 :             new_shared.ats_table = NULL;
    6390       10908 :         new_shared.ats_modifiedcols = modifiedCols;
    6391             : 
    6392       10908 :         afterTriggerAddEvent(&afterTriggers.query_stack[afterTriggers.query_depth].events,
    6393             :                              &new_event, &new_shared);
    6394             :     }
    6395             : 
    6396             :     /*
    6397             :      * Finally, spool any foreign tuple(s).  The tuplestore squashes them to
    6398             :      * minimal tuples, so this loses any system columns.  The executor lost
    6399             :      * those columns before us, for an unrelated reason, so this is fine.
    6400             :      */
    6401        9860 :     if (fdw_tuplestore)
    6402             :     {
    6403          50 :         if (oldslot != NULL)
    6404          32 :             tuplestore_puttupleslot(fdw_tuplestore, oldslot);
    6405          50 :         if (newslot != NULL)
    6406          36 :             tuplestore_puttupleslot(fdw_tuplestore, newslot);
    6407             :     }
    6408             : }
    6409             : 
    6410             : /*
    6411             :  * Detect whether we already queued BEFORE STATEMENT triggers for the given
    6412             :  * relation + operation, and set the flag so the next call will report "true".
    6413             :  */
    6414             : static bool
    6415         474 : before_stmt_triggers_fired(Oid relid, CmdType cmdType)
    6416             : {
    6417             :     bool        result;
    6418             :     AfterTriggersTableData *table;
    6419             : 
    6420             :     /* Check state, like AfterTriggerSaveEvent. */
    6421         474 :     if (afterTriggers.query_depth < 0)
    6422           0 :         elog(ERROR, "before_stmt_triggers_fired() called outside of query");
    6423             : 
    6424             :     /* Be sure we have enough space to record events at this query depth. */
    6425         474 :     if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
    6426         312 :         AfterTriggerEnlargeQueryState();
    6427             : 
    6428             :     /*
    6429             :      * We keep this state in the AfterTriggersTableData that also holds
    6430             :      * transition tables for the relation + operation.  In this way, if we are
    6431             :      * forced to make a new set of transition tables because more tuples get
    6432             :      * entered after we've already fired triggers, we will allow a new set of
    6433             :      * statement triggers to get queued.
    6434             :      */
    6435         474 :     table = GetAfterTriggersTableData(relid, cmdType);
    6436         474 :     result = table->before_trig_done;
    6437         474 :     table->before_trig_done = true;
    6438         474 :     return result;
    6439             : }
    6440             : 
    6441             : /*
    6442             :  * If we previously queued a set of AFTER STATEMENT triggers for the given
    6443             :  * relation + operation, and they've not been fired yet, cancel them.  The
    6444             :  * caller will queue a fresh set that's after any row-level triggers that may
    6445             :  * have been queued by the current sub-statement, preserving (as much as
    6446             :  * possible) the property that AFTER ROW triggers fire before AFTER STATEMENT
    6447             :  * triggers, and that the latter only fire once.  This deals with the
    6448             :  * situation where several FK enforcement triggers sequentially queue triggers
    6449             :  * for the same table into the same trigger query level.  We can't fully
    6450             :  * prevent odd behavior though: if there are AFTER ROW triggers taking
    6451             :  * transition tables, we don't want to change the transition tables once the
    6452             :  * first such trigger has seen them.  In such a case, any additional events
    6453             :  * will result in creating new transition tables and allowing new firings of
    6454             :  * statement triggers.
    6455             :  *
    6456             :  * This also saves the current event list location so that a later invocation
    6457             :  * of this function can cheaply find the triggers we're about to queue and
    6458             :  * cancel them.
    6459             :  */
    6460             : static void
    6461        1020 : cancel_prior_stmt_triggers(Oid relid, CmdType cmdType, int tgevent)
    6462             : {
    6463             :     AfterTriggersTableData *table;
    6464        1020 :     AfterTriggersQueryData *qs = &afterTriggers.query_stack[afterTriggers.query_depth];
    6465             : 
    6466             :     /*
    6467             :      * We keep this state in the AfterTriggersTableData that also holds
    6468             :      * transition tables for the relation + operation.  In this way, if we are
    6469             :      * forced to make a new set of transition tables because more tuples get
    6470             :      * entered after we've already fired triggers, we will allow a new set of
    6471             :      * statement triggers to get queued without canceling the old ones.
    6472             :      */
    6473        1020 :     table = GetAfterTriggersTableData(relid, cmdType);
    6474             : 
    6475        1020 :     if (table->after_trig_done)
    6476             :     {
    6477             :         /*
    6478             :          * We want to start scanning from the tail location that existed just
    6479             :          * before we inserted any statement triggers.  But the events list
    6480             :          * might've been entirely empty then, in which case scan from the
    6481             :          * current head.
    6482             :          */
    6483             :         AfterTriggerEvent event;
    6484             :         AfterTriggerEventChunk *chunk;
    6485             : 
    6486          66 :         if (table->after_trig_events.tail)
    6487             :         {
    6488          60 :             chunk = table->after_trig_events.tail;
    6489          60 :             event = (AfterTriggerEvent) table->after_trig_events.tailfree;
    6490             :         }
    6491             :         else
    6492             :         {
    6493           6 :             chunk = qs->events.head;
    6494           6 :             event = NULL;
    6495             :         }
    6496             : 
    6497          96 :         for_each_chunk_from(chunk)
    6498             :         {
    6499          66 :             if (event == NULL)
    6500           6 :                 event = (AfterTriggerEvent) CHUNK_DATA_START(chunk);
    6501         138 :             for_each_event_from(event, chunk)
    6502             :             {
    6503         108 :                 AfterTriggerShared evtshared = GetTriggerSharedData(event);
    6504             : 
    6505             :                 /*
    6506             :                  * Exit loop when we reach events that aren't AS triggers for
    6507             :                  * the target relation.
    6508             :                  */
    6509         108 :                 if (evtshared->ats_relid != relid)
    6510           0 :                     goto done;
    6511         108 :                 if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) != tgevent)
    6512           0 :                     goto done;
    6513         108 :                 if (!TRIGGER_FIRED_FOR_STATEMENT(evtshared->ats_event))
    6514          36 :                     goto done;
    6515          72 :                 if (!TRIGGER_FIRED_AFTER(evtshared->ats_event))
    6516           0 :                     goto done;
    6517             :                 /* OK, mark it DONE */
    6518          72 :                 event->ate_flags &= ~AFTER_TRIGGER_IN_PROGRESS;
    6519          72 :                 event->ate_flags |= AFTER_TRIGGER_DONE;
    6520             :             }
    6521             :             /* signal we must reinitialize event ptr for next chunk */
    6522          30 :             event = NULL;
    6523             :         }
    6524             :     }
    6525         984 : done:
    6526             : 
    6527             :     /* In any case, save current insertion point for next time */
    6528        1020 :     table->after_trig_done = true;
    6529        1020 :     table->after_trig_events = qs->events;
    6530        1020 : }
    6531             : 
    6532             : /*
    6533             :  * GUC assign_hook for session_replication_role
    6534             :  */
    6535             : void
    6536        4370 : assign_session_replication_role(int newval, void *extra)
    6537             : {
    6538             :     /*
    6539             :      * Must flush the plan cache when changing replication role; but don't
    6540             :      * flush unnecessarily.
    6541             :      */
    6542        4370 :     if (SessionReplicationRole != newval)
    6543         672 :         ResetPlanCache();
    6544        4370 : }
    6545             : 
    6546             : /*
    6547             :  * SQL function pg_trigger_depth()
    6548             :  */
    6549             : Datum
    6550          90 : pg_trigger_depth(PG_FUNCTION_ARGS)
    6551             : {
    6552          90 :     PG_RETURN_INT32(MyTriggerDepth);
    6553             : }

Generated by: LCOV version 1.14