LCOV - differential code coverage report
Current view: top level - src/backend/commands - trigger.c (source / functions) Coverage Total Hit LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 93.7 % 2056 1927 35 90 4 34 1272 13 608 90 1227 1 57
Current Date: 2023-04-08 15:15:32 Functions: 98.5 % 68 67 1 63 4 1 67
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a