Coverage Report

Created: 2026-08-14 06:37

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