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

Generated by: LCOV version 1.14