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

Generated by: LCOV version 2.0-1