LCOV - differential code coverage report
Current view: top level - src/backend/commands - trigger.c (source / functions) Coverage Total Hit UNC UBC GNC CBC
Current: 77aeca80249c9e640c811e80633a2e334a9320de vs 38afc3dcb25c45b744d4025029ce0a6c90b7059f Lines: 94.5 % 2183 2063 120 4 2059
Current Date: 2026-07-25 19:08:27 +0900 Functions: 98.6 % 73 72 1 2 70
Baseline: lcov-20260725-baseline Branches: 77.0 % 1798 1384 2 412 6 1378
Baseline Date: 2026-07-25 19:09:19 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 4 4 4
(30,360] days: 92.5 % 133 123 10 123
(360..) days: 94.6 % 2046 1936 110 1936
Function coverage date bins:
(30,360] days: 100.0 % 5 5 1 4
(360..) days: 98.5 % 68 67 1 1 66
Branch coverage date bins:
(7,30] days: 75.0 % 8 6 2 6
(30,360] days: 78.4 % 88 69 19 69
(360..) days: 76.9 % 1702 1309 393 1309

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

Generated by: LCOV version 2.0-1