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