LCOV - code coverage report
Current view: top level - src/backend/commands - trigger.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 94.4 % 2121 2002
Test Date: 2026-08-15 09:15:43 Functions: 98.6 % 73 72
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 79.6 % 1616 1286

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

Generated by: LCOV version 2.0-1