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 16242 : 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 16242 : 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 17066 : 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 17066 : HeapTuple tuple = NULL;
197 : Oid funcrettype;
198 17066 : Oid trigoid = InvalidOid;
199 : char internaltrigname[NAMEDATALEN];
200 : char *trigname;
201 17066 : Oid constrrelid = InvalidOid;
202 : ObjectAddress myself,
203 : referenced;
204 17066 : char *oldtablename = NULL;
205 17066 : char *newtablename = NULL;
206 : bool partition_recurse;
207 17066 : bool trigger_exists = false;
208 17066 : Oid existing_constraint_oid = InvalidOid;
209 17066 : bool existing_isInternal = false;
210 17066 : bool existing_isClone = false;
211 :
212 17066 : if (OidIsValid(relOid))
213 13762 : rel = table_open(relOid, ShareRowExclusiveLock);
214 : else
215 3304 : 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 17066 : if (rel->rd_rel->relkind == RELKIND_RELATION)
222 : {
223 : /* Tables can't have INSTEAD OF triggers */
224 13922 : if (stmt->timing != TRIGGER_TYPE_BEFORE &&
225 12548 : 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 3144 : else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
233 : {
234 : /* Partitioned tables can't have INSTEAD OF triggers */
235 2830 : if (stmt->timing != TRIGGER_TYPE_BEFORE &&
236 2728 : 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 2824 : 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 2592 : 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 16982 : 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 16980 : 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 13096 : if (OidIsValid(refRelOid))
332 : {
333 12814 : LockRelationOid(refRelOid, AccessShareLock);
334 12814 : constrrelid = refRelOid;
335 : }
336 282 : else if (stmt->constrrel != NULL)
337 24 : constrrelid = RangeVarGetRelid(stmt->constrrel, AccessShareLock,
338 : false);
339 : }
340 :
341 : /* permission checks */
342 16980 : if (!isInternal)
343 : {
344 4042 : aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
345 : ACL_TRIGGER);
346 4042 : if (aclresult != ACLCHECK_OK)
347 0 : aclcheck_error(aclresult, get_relkind_objtype(rel->rd_rel->relkind),
348 0 : RelationGetRelationName(rel));
349 :
350 4042 : 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 19990 : partition_recurse = !isInternal && stmt->row &&
367 3010 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE;
368 16980 : if (partition_recurse)
369 404 : list_free(find_all_inheritors(RelationGetRelid(rel),
370 : ShareRowExclusiveLock, NULL));
371 :
372 : /* Compute tgtype */
373 16980 : TRIGGER_CLEAR_TYPE(tgtype);
374 16980 : if (stmt->row)
375 15948 : TRIGGER_SETT_ROW(tgtype);
376 16980 : tgtype |= stmt->timing;
377 16980 : tgtype |= stmt->events;
378 :
379 : /* Disallow ROW-level TRUNCATE triggers */
380 16980 : 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 16980 : 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 16962 : if (stmt->transitionRels != NIL)
417 : {
418 464 : List *varList = stmt->transitionRels;
419 : ListCell *lc;
420 :
421 1012 : foreach(lc, varList)
422 : {
423 596 : TriggerTransition *tt = lfirst_node(TriggerTransition, lc);
424 :
425 596 : 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 596 : 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 590 : 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 584 : 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 572 : 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 572 : 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 566 : if (((TRIGGER_FOR_INSERT(tgtype) ? 1 : 0) +
493 566 : (TRIGGER_FOR_UPDATE(tgtype) ? 1 : 0) +
494 566 : (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 560 : 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 554 : if (tt->isNew)
520 : {
521 294 : if (!(TRIGGER_FOR_INSERT(tgtype) ||
522 160 : 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 294 : if (newtablename != NULL)
528 0 : ereport(ERROR,
529 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
530 : errmsg("NEW TABLE cannot be specified multiple times")));
531 :
532 294 : newtablename = tt->name;
533 : }
534 : else
535 : {
536 260 : if (!(TRIGGER_FOR_DELETE(tgtype) ||
537 154 : 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 254 : if (oldtablename != NULL)
543 0 : ereport(ERROR,
544 : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
545 : errmsg("OLD TABLE cannot be specified multiple times")));
546 :
547 254 : oldtablename = tt->name;
548 : }
549 : }
550 :
551 416 : if (newtablename != NULL && oldtablename != NULL &&
552 132 : 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 16914 : if (!whenClause && stmt->whenClause)
567 140 : {
568 : ParseState *pstate;
569 : ParseNamespaceItem *nsitem;
570 : List *varList;
571 : ListCell *lc;
572 :
573 : /* Set up a pstate to parse with */
574 188 : pstate = make_parsestate(NULL);
575 188 : 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 188 : nsitem = addRangeTableEntryForRelation(pstate, rel,
583 : AccessShareLock,
584 : makeAlias("old", NIL),
585 : false, false);
586 188 : addNSItemToQuery(pstate, nsitem, false, true, true);
587 188 : nsitem = addRangeTableEntryForRelation(pstate, rel,
588 : AccessShareLock,
589 : makeAlias("new", NIL),
590 : false, false);
591 188 : addNSItemToQuery(pstate, nsitem, false, true, true);
592 :
593 : /* Transform expression. Copy to be sure we don't modify original */
594 188 : whenClause = transformWhereClause(pstate,
595 188 : copyObject(stmt->whenClause),
596 : EXPR_KIND_TRIGGER_WHEN,
597 : "WHEN");
598 : /* we have to fix its collations too */
599 188 : 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 188 : varList = pull_var_clause(whenClause, 0);
609 372 : foreach(lc, varList)
610 : {
611 232 : Var *var = (Var *) lfirst(lc);
612 :
613 232 : 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 146 : case PRS2_NEW_VARNO:
629 146 : 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 146 : 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 140 : 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 134 : 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 122 : 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 110 : 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 140 : whenRtable = pstate->p_rtable;
673 :
674 140 : qual = nodeToString(whenClause);
675 :
676 140 : free_parsestate(pstate);
677 : }
678 16726 : else if (!whenClause)
679 : {
680 16684 : whenClause = NULL;
681 16684 : whenRtable = NIL;
682 16684 : 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 16866 : if (!OidIsValid(funcoid))
694 16042 : funcoid = LookupFuncName(stmt->funcname, 0, NULL, false);
695 16866 : if (!isInternal)
696 : {
697 3928 : aclresult = object_aclcheck(ProcedureRelationId, funcoid, GetUserId(), ACL_EXECUTE);
698 3928 : if (aclresult != ACLCHECK_OK)
699 0 : aclcheck_error(aclresult, OBJECT_FUNCTION,
700 0 : NameListToString(stmt->funcname));
701 : }
702 16866 : funcrettype = get_func_rettype(funcoid);
703 16866 : 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 16866 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
718 16866 : if (!isInternal)
719 : {
720 : ScanKeyData skeys[2];
721 : SysScanDesc tgscan;
722 :
723 3928 : ScanKeyInit(&skeys[0],
724 : Anum_pg_trigger_tgrelid,
725 : BTEqualStrategyNumber, F_OIDEQ,
726 : ObjectIdGetDatum(RelationGetRelid(rel)));
727 :
728 3928 : ScanKeyInit(&skeys[1],
729 : Anum_pg_trigger_tgname,
730 : BTEqualStrategyNumber, F_NAMEEQ,
731 3928 : CStringGetDatum(stmt->trigname));
732 :
733 3928 : tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
734 : NULL, 2, skeys);
735 :
736 : /* There should be at most one matching tuple */
737 3928 : 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 3928 : systable_endscan(tgscan);
750 : }
751 :
752 16866 : if (!trigger_exists)
753 : {
754 : /* Generate the OID for the new trigger. */
755 16764 : 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 16842 : 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 16842 : if (isInternal)
852 : {
853 12938 : snprintf(internaltrigname, sizeof(internaltrigname),
854 : "%s_%u", stmt->trigname, trigoid);
855 12938 : trigname = internaltrigname;
856 : }
857 : else
858 : {
859 : /* user-defined trigger; use the specified trigger name as-is */
860 3904 : trigname = stmt->trigname;
861 : }
862 :
863 : /*
864 : * Build the new pg_trigger tuple.
865 : */
866 16842 : memset(nulls, false, sizeof(nulls));
867 :
868 16842 : values[Anum_pg_trigger_oid - 1] = ObjectIdGetDatum(trigoid);
869 16842 : values[Anum_pg_trigger_tgrelid - 1] = ObjectIdGetDatum(RelationGetRelid(rel));
870 16842 : values[Anum_pg_trigger_tgparentid - 1] = ObjectIdGetDatum(parentTriggerOid);
871 16842 : values[Anum_pg_trigger_tgname - 1] = DirectFunctionCall1(namein,
872 : CStringGetDatum(trigname));
873 16842 : values[Anum_pg_trigger_tgfoid - 1] = ObjectIdGetDatum(funcoid);
874 16842 : values[Anum_pg_trigger_tgtype - 1] = Int16GetDatum(tgtype);
875 16842 : values[Anum_pg_trigger_tgenabled - 1] = trigger_fires_when;
876 16842 : values[Anum_pg_trigger_tgisinternal - 1] = BoolGetDatum(isInternal);
877 16842 : values[Anum_pg_trigger_tgconstrrelid - 1] = ObjectIdGetDatum(constrrelid);
878 16842 : values[Anum_pg_trigger_tgconstrindid - 1] = ObjectIdGetDatum(indexOid);
879 16842 : values[Anum_pg_trigger_tgconstraint - 1] = ObjectIdGetDatum(constraintOid);
880 16842 : values[Anum_pg_trigger_tgdeferrable - 1] = BoolGetDatum(stmt->deferrable);
881 16842 : values[Anum_pg_trigger_tginitdeferred - 1] = BoolGetDatum(stmt->initdeferred);
882 :
883 16842 : if (stmt->args)
884 : {
885 : ListCell *le;
886 : char *args;
887 498 : int16 nargs = list_length(stmt->args);
888 498 : int len = 0;
889 :
890 1180 : foreach(le, stmt->args)
891 : {
892 682 : char *ar = strVal(lfirst(le));
893 :
894 682 : len += strlen(ar) + 4;
895 5718 : for (; *ar; ar++)
896 : {
897 5036 : if (*ar == '\\')
898 0 : len++;
899 : }
900 : }
901 498 : args = (char *) palloc(len + 1);
902 498 : args[0] = '\0';
903 1180 : foreach(le, stmt->args)
904 : {
905 682 : char *s = strVal(lfirst(le));
906 682 : char *d = args + strlen(args);
907 :
908 5718 : while (*s)
909 : {
910 5036 : if (*s == '\\')
911 0 : *d++ = '\\';
912 5036 : *d++ = *s++;
913 : }
914 682 : strcpy(d, "\\000");
915 : }
916 498 : values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(nargs);
917 498 : values[Anum_pg_trigger_tgargs - 1] = DirectFunctionCall1(byteain,
918 : CStringGetDatum(args));
919 : }
920 : else
921 : {
922 16344 : values[Anum_pg_trigger_tgnargs - 1] = Int16GetDatum(0);
923 16344 : 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 16842 : ncolumns = list_length(stmt->columns);
929 16842 : if (ncolumns == 0)
930 16728 : columns = NULL;
931 : else
932 : {
933 : ListCell *cell;
934 114 : int i = 0;
935 :
936 114 : columns = (int16 *) palloc(ncolumns * sizeof(int16));
937 238 : foreach(cell, stmt->columns)
938 : {
939 130 : char *name = strVal(lfirst(cell));
940 : int16 attnum;
941 : int j;
942 :
943 : /* Lookup column name. System columns are not allowed */
944 130 : attnum = attnameAttNum(rel, name, false);
945 130 : 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 140 : for (j = i - 1; j >= 0; j--)
953 : {
954 16 : 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 124 : columns[i++] = attnum;
962 : }
963 : }
964 16836 : tgattr = buildint2vector(columns, ncolumns);
965 16836 : values[Anum_pg_trigger_tgattr - 1] = PointerGetDatum(tgattr);
966 :
967 : /* set tgqual if trigger has WHEN clause */
968 16836 : if (qual)
969 182 : values[Anum_pg_trigger_tgqual - 1] = CStringGetTextDatum(qual);
970 : else
971 16654 : nulls[Anum_pg_trigger_tgqual - 1] = true;
972 :
973 16836 : if (oldtablename)
974 254 : values[Anum_pg_trigger_tgoldtable - 1] = DirectFunctionCall1(namein,
975 : CStringGetDatum(oldtablename));
976 : else
977 16582 : nulls[Anum_pg_trigger_tgoldtable - 1] = true;
978 16836 : if (newtablename)
979 294 : values[Anum_pg_trigger_tgnewtable - 1] = DirectFunctionCall1(namein,
980 : CStringGetDatum(newtablename));
981 : else
982 16542 : nulls[Anum_pg_trigger_tgnewtable - 1] = true;
983 :
984 : /*
985 : * Insert or replace tuple in pg_trigger.
986 : */
987 16836 : if (!trigger_exists)
988 : {
989 16758 : tuple = heap_form_tuple(tgrel->rd_att, values, nulls);
990 16758 : 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 16836 : heap_freetuple(tuple); /* free either original or new tuple */
1002 16836 : table_close(tgrel, RowExclusiveLock);
1003 :
1004 16836 : pfree(DatumGetPointer(values[Anum_pg_trigger_tgname - 1]));
1005 16836 : pfree(DatumGetPointer(values[Anum_pg_trigger_tgargs - 1]));
1006 16836 : pfree(DatumGetPointer(values[Anum_pg_trigger_tgattr - 1]));
1007 16836 : if (oldtablename)
1008 254 : pfree(DatumGetPointer(values[Anum_pg_trigger_tgoldtable - 1]));
1009 16836 : if (newtablename)
1010 294 : 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 16836 : pgrel = table_open(RelationRelationId, RowExclusiveLock);
1017 16836 : tuple = SearchSysCacheCopy1(RELOID,
1018 : ObjectIdGetDatum(RelationGetRelid(rel)));
1019 16836 : if (!HeapTupleIsValid(tuple))
1020 0 : elog(ERROR, "cache lookup failed for relation %u",
1021 : RelationGetRelid(rel));
1022 16836 : if (!((Form_pg_class) GETSTRUCT(tuple))->relhastriggers)
1023 : {
1024 6334 : ((Form_pg_class) GETSTRUCT(tuple))->relhastriggers = true;
1025 :
1026 6334 : CatalogTupleUpdate(pgrel, &tuple->t_self, tuple);
1027 :
1028 6334 : CommandCounterIncrement();
1029 : }
1030 : else
1031 10502 : CacheInvalidateRelcacheByTuple(tuple);
1032 :
1033 16836 : heap_freetuple(tuple);
1034 16836 : 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 16836 : 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 16836 : myself.classId = TriggerRelationId;
1048 16836 : myself.objectId = trigoid;
1049 16836 : myself.objectSubId = 0;
1050 :
1051 16836 : referenced.classId = ProcedureRelationId;
1052 16836 : referenced.objectId = funcoid;
1053 16836 : referenced.objectSubId = 0;
1054 16836 : recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
1055 :
1056 16836 : 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 12938 : referenced.classId = ConstraintRelationId;
1065 12938 : referenced.objectId = constraintOid;
1066 12938 : referenced.objectSubId = 0;
1067 12938 : 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 3898 : referenced.classId = RelationRelationId;
1077 3898 : referenced.objectId = RelationGetRelid(rel);
1078 3898 : referenced.objectSubId = 0;
1079 3898 : recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
1080 :
1081 3898 : 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 3898 : 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 3898 : if (OidIsValid(parentTriggerOid))
1107 : {
1108 812 : ObjectAddressSet(referenced, TriggerRelationId, parentTriggerOid);
1109 812 : recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_PRI);
1110 812 : ObjectAddressSet(referenced, RelationRelationId, RelationGetRelid(rel));
1111 812 : recordDependencyOn(&myself, &referenced, DEPENDENCY_PARTITION_SEC);
1112 : }
1113 : }
1114 :
1115 : /* If column-specific trigger, add normal dependencies on columns */
1116 16836 : if (columns != NULL)
1117 : {
1118 : int i;
1119 :
1120 108 : referenced.classId = RelationRelationId;
1121 108 : referenced.objectId = RelationGetRelid(rel);
1122 226 : for (i = 0; i < ncolumns; i++)
1123 : {
1124 118 : referenced.objectSubId = columns[i];
1125 118 : 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 16836 : if (whenRtable != NIL)
1134 140 : recordDependencyOnExpr(&myself, whenClause, whenRtable,
1135 : DEPENDENCY_NORMAL);
1136 :
1137 : /* Post creation hook for new trigger */
1138 16836 : InvokeObjectPostCreateHookArg(TriggerRelationId, trigoid, 0,
1139 : isInternal);
1140 :
1141 : /*
1142 : * Lastly, create the trigger on child relations, if needed.
1143 : */
1144 16836 : if (partition_recurse)
1145 : {
1146 392 : PartitionDesc partdesc = RelationGetPartitionDesc(rel, true);
1147 : int i;
1148 : MemoryContext oldcxt,
1149 : perChildCxt;
1150 :
1151 392 : 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 392 : oldcxt = MemoryContextSwitchTo(perChildCxt);
1163 :
1164 : /* Iterate to create the trigger on each existing partition */
1165 1054 : for (i = 0; i < partdesc->nparts; i++)
1166 : {
1167 : CreateTrigStmt *childStmt;
1168 : Relation childTbl;
1169 : Node *qual;
1170 :
1171 668 : 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 668 : childStmt = copyObject(stmt);
1178 668 : childStmt->funcname = NIL;
1179 668 : childStmt->whenClause = NULL;
1180 :
1181 : /* If there is a WHEN clause, create a modified copy of it */
1182 668 : qual = copyObject(whenClause);
1183 : qual = (Node *)
1184 668 : map_partition_varattnos((List *) qual, PRS2_OLD_VARNO,
1185 : childTbl, rel);
1186 : qual = (Node *)
1187 668 : map_partition_varattnos((List *) qual, PRS2_NEW_VARNO,
1188 : childTbl, rel);
1189 :
1190 668 : CreateTriggerFiringOn(childStmt, queryString,
1191 668 : partdesc->oids[i], refRelOid,
1192 : InvalidOid, InvalidOid,
1193 : funcoid, trigoid, qual,
1194 : isInternal, true, trigger_fires_when);
1195 :
1196 662 : table_close(childTbl, NoLock);
1197 :
1198 662 : MemoryContextReset(perChildCxt);
1199 : }
1200 :
1201 386 : MemoryContextSwitchTo(oldcxt);
1202 386 : MemoryContextDelete(perChildCxt);
1203 : }
1204 :
1205 : /* Keep lock on target rel until end of xact */
1206 16830 : table_close(rel, NoLock);
1207 :
1208 16830 : 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 14194 : 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 14194 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1302 :
1303 : /*
1304 : * Find the trigger to delete.
1305 : */
1306 14194 : ScanKeyInit(&skey[0],
1307 : Anum_pg_trigger_oid,
1308 : BTEqualStrategyNumber, F_OIDEQ,
1309 : ObjectIdGetDatum(trigOid));
1310 :
1311 14194 : tgscan = systable_beginscan(tgrel, TriggerOidIndexId, true,
1312 : NULL, 1, skey);
1313 :
1314 14194 : tup = systable_getnext(tgscan);
1315 14194 : 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 14194 : relid = ((Form_pg_trigger) GETSTRUCT(tup))->tgrelid;
1322 :
1323 14194 : rel = table_open(relid, AccessExclusiveLock);
1324 :
1325 14194 : if (rel->rd_rel->relkind != RELKIND_RELATION &&
1326 2642 : rel->rd_rel->relkind != RELKIND_VIEW &&
1327 2506 : rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
1328 2414 : 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 14194 : 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 14194 : CatalogTupleDelete(tgrel, &tup->t_self);
1345 :
1346 14194 : systable_endscan(tgscan);
1347 14194 : 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 14194 : CacheInvalidateRelcache(rel);
1359 :
1360 : /* Keep lock on trigger's rel until end of xact */
1361 14194 : table_close(rel, NoLock);
1362 14194 : }
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 458 : 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 458 : tgrel = table_open(TriggerRelationId, RowExclusiveLock);
1741 :
1742 458 : ScanKeyInit(&keys[0],
1743 : Anum_pg_trigger_tgrelid,
1744 : BTEqualStrategyNumber, F_OIDEQ,
1745 : ObjectIdGetDatum(RelationGetRelid(rel)));
1746 458 : if (tgname)
1747 : {
1748 322 : ScanKeyInit(&keys[1],
1749 : Anum_pg_trigger_tgname,
1750 : BTEqualStrategyNumber, F_NAMEEQ,
1751 : CStringGetDatum(tgname));
1752 322 : nkeys = 2;
1753 : }
1754 : else
1755 136 : nkeys = 1;
1756 :
1757 458 : tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1758 : NULL, nkeys, keys);
1759 :
1760 458 : found = changed = false;
1761 :
1762 1192 : while (HeapTupleIsValid(tuple = systable_getnext(tgscan)))
1763 : {
1764 734 : Form_pg_trigger oldtrig = (Form_pg_trigger) GETSTRUCT(tuple);
1765 :
1766 734 : if (OidIsValid(tgparent) && tgparent != oldtrig->tgparentid)
1767 192 : continue;
1768 :
1769 542 : 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 530 : found = true;
1782 :
1783 530 : if (oldtrig->tgenabled != fires_when)
1784 : {
1785 : /* need to change this one ... make a copy to scribble on */
1786 500 : HeapTuple newtup = heap_copytuple(tuple);
1787 500 : Form_pg_trigger newtrig = (Form_pg_trigger) GETSTRUCT(newtup);
1788 :
1789 500 : newtrig->tgenabled = fires_when;
1790 :
1791 500 : CatalogTupleUpdate(tgrel, &newtup->t_self, newtup);
1792 :
1793 500 : heap_freetuple(newtup);
1794 :
1795 500 : 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 530 : if (recurse &&
1808 502 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE &&
1809 88 : (TRIGGER_FOR_ROW(oldtrig->tgtype)))
1810 : {
1811 76 : PartitionDesc partdesc = RelationGetPartitionDesc(rel, true);
1812 : int i;
1813 :
1814 188 : for (i = 0; i < partdesc->nparts; i++)
1815 : {
1816 : Relation part;
1817 :
1818 112 : part = relation_open(partdesc->oids[i], lockmode);
1819 : /* Match on child triggers' tgparentid, not their name */
1820 112 : EnableDisableTrigger(part, NULL, oldtrig->oid,
1821 : fires_when, skip_system, recurse,
1822 : lockmode);
1823 112 : table_close(part, NoLock); /* keep lock till commit */
1824 : }
1825 : }
1826 :
1827 530 : InvokeObjectPostAlterHook(TriggerRelationId,
1828 : oldtrig->oid, 0);
1829 : }
1830 :
1831 458 : systable_endscan(tgscan);
1832 :
1833 458 : table_close(tgrel, RowExclusiveLock);
1834 :
1835 458 : 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 458 : if (changed)
1847 452 : CacheInvalidateRelcache(rel);
1848 458 : }
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 63416 : 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 63416 : maxtrigs = 16;
1880 63416 : triggers = (Trigger *) palloc(maxtrigs * sizeof(Trigger));
1881 63416 : 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 63416 : ScanKeyInit(&skey,
1890 : Anum_pg_trigger_tgrelid,
1891 : BTEqualStrategyNumber, F_OIDEQ,
1892 : ObjectIdGetDatum(RelationGetRelid(relation)));
1893 :
1894 63416 : tgrel = table_open(TriggerRelationId, AccessShareLock);
1895 63416 : tgscan = systable_beginscan(tgrel, TriggerRelidNameIndexId, true,
1896 : NULL, 1, &skey);
1897 :
1898 180072 : while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
1899 : {
1900 116656 : Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
1901 : Trigger *build;
1902 : Datum datum;
1903 : bool isnull;
1904 :
1905 116656 : if (numtrigs >= maxtrigs)
1906 : {
1907 48 : maxtrigs *= 2;
1908 48 : triggers = (Trigger *) repalloc(triggers, maxtrigs * sizeof(Trigger));
1909 : }
1910 116656 : build = &(triggers[numtrigs]);
1911 :
1912 116656 : build->tgoid = pg_trigger->oid;
1913 116656 : build->tgname = DatumGetCString(DirectFunctionCall1(nameout,
1914 : NameGetDatum(&pg_trigger->tgname)));
1915 116656 : build->tgfoid = pg_trigger->tgfoid;
1916 116656 : build->tgtype = pg_trigger->tgtype;
1917 116656 : build->tgenabled = pg_trigger->tgenabled;
1918 116656 : build->tgisinternal = pg_trigger->tgisinternal;
1919 116656 : build->tgisclone = OidIsValid(pg_trigger->tgparentid);
1920 116656 : build->tgconstrrelid = pg_trigger->tgconstrrelid;
1921 116656 : build->tgconstrindid = pg_trigger->tgconstrindid;
1922 116656 : build->tgconstraint = pg_trigger->tgconstraint;
1923 116656 : build->tgdeferrable = pg_trigger->tgdeferrable;
1924 116656 : build->tginitdeferred = pg_trigger->tginitdeferred;
1925 116656 : build->tgnargs = pg_trigger->tgnargs;
1926 : /* tgattr is first var-width field, so OK to access directly */
1927 116656 : build->tgnattr = pg_trigger->tgattr.dim1;
1928 116656 : if (build->tgnattr > 0)
1929 : {
1930 578 : build->tgattr = (int16 *) palloc(build->tgnattr * sizeof(int16));
1931 578 : memcpy(build->tgattr, &(pg_trigger->tgattr.values),
1932 578 : build->tgnattr * sizeof(int16));
1933 : }
1934 : else
1935 116078 : build->tgattr = NULL;
1936 116656 : if (build->tgnargs > 0)
1937 : {
1938 : bytea *val;
1939 : char *p;
1940 :
1941 3090 : val = DatumGetByteaPP(fastgetattr(htup,
1942 : Anum_pg_trigger_tgargs,
1943 : tgrel->rd_att, &isnull));
1944 3090 : if (isnull)
1945 0 : elog(ERROR, "tgargs is null in trigger for relation \"%s\"",
1946 : RelationGetRelationName(relation));
1947 3090 : p = (char *) VARDATA_ANY(val);
1948 3090 : build->tgargs = (char **) palloc(build->tgnargs * sizeof(char *));
1949 6672 : for (i = 0; i < build->tgnargs; i++)
1950 : {
1951 3582 : build->tgargs[i] = pstrdup(p);
1952 3582 : p += strlen(p) + 1;
1953 : }
1954 : }
1955 : else
1956 113566 : build->tgargs = NULL;
1957 :
1958 116656 : datum = fastgetattr(htup, Anum_pg_trigger_tgoldtable,
1959 : tgrel->rd_att, &isnull);
1960 116656 : if (!isnull)
1961 872 : build->tgoldtable =
1962 872 : DatumGetCString(DirectFunctionCall1(nameout, datum));
1963 : else
1964 115784 : build->tgoldtable = NULL;
1965 :
1966 116656 : datum = fastgetattr(htup, Anum_pg_trigger_tgnewtable,
1967 : tgrel->rd_att, &isnull);
1968 116656 : if (!isnull)
1969 1192 : build->tgnewtable =
1970 1192 : DatumGetCString(DirectFunctionCall1(nameout, datum));
1971 : else
1972 115464 : build->tgnewtable = NULL;
1973 :
1974 116656 : datum = fastgetattr(htup, Anum_pg_trigger_tgqual,
1975 : tgrel->rd_att, &isnull);
1976 116656 : if (!isnull)
1977 938 : build->tgqual = TextDatumGetCString(datum);
1978 : else
1979 115718 : build->tgqual = NULL;
1980 :
1981 116656 : numtrigs++;
1982 : }
1983 :
1984 63416 : systable_endscan(tgscan);
1985 63416 : table_close(tgrel, AccessShareLock);
1986 :
1987 : /* There might not be any triggers */
1988 63416 : if (numtrigs == 0)
1989 : {
1990 14052 : pfree(triggers);
1991 14052 : return;
1992 : }
1993 :
1994 : /* Build trigdesc */
1995 49364 : trigdesc = (TriggerDesc *) palloc0(sizeof(TriggerDesc));
1996 49364 : trigdesc->triggers = triggers;
1997 49364 : trigdesc->numtriggers = numtrigs;
1998 166020 : for (i = 0; i < numtrigs; i++)
1999 116656 : SetTriggerFlags(trigdesc, &(triggers[i]));
2000 :
2001 : /* Copy completed trigdesc into cache storage */
2002 49364 : oldContext = MemoryContextSwitchTo(CacheMemoryContext);
2003 49364 : relation->trigdesc = CopyTriggerDesc(trigdesc);
2004 49364 : MemoryContextSwitchTo(oldContext);
2005 :
2006 : /* Release working memory */
2007 49364 : FreeTriggerDesc(trigdesc);
2008 : }
2009 :
2010 : /*
2011 : * Update the TriggerDesc's hint flags to include the specified trigger
2012 : */
2013 : static void
2014 116656 : SetTriggerFlags(TriggerDesc *trigdesc, Trigger *trigger)
2015 : {
2016 116656 : int16 tgtype = trigger->tgtype;
2017 :
2018 116656 : trigdesc->trig_insert_before_row |=
2019 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2020 : TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT);
2021 116656 : trigdesc->trig_insert_after_row |=
2022 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2023 : TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT);
2024 116656 : trigdesc->trig_insert_instead_row |=
2025 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2026 : TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_INSERT);
2027 116656 : trigdesc->trig_insert_before_statement |=
2028 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2029 : TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_INSERT);
2030 116656 : trigdesc->trig_insert_after_statement |=
2031 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2032 : TRIGGER_TYPE_AFTER, TRIGGER_TYPE_INSERT);
2033 116656 : trigdesc->trig_update_before_row |=
2034 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2035 : TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_UPDATE);
2036 116656 : trigdesc->trig_update_after_row |=
2037 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2038 : TRIGGER_TYPE_AFTER, TRIGGER_TYPE_UPDATE);
2039 116656 : trigdesc->trig_update_instead_row |=
2040 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2041 : TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_UPDATE);
2042 116656 : trigdesc->trig_update_before_statement |=
2043 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2044 : TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_UPDATE);
2045 116656 : trigdesc->trig_update_after_statement |=
2046 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2047 : TRIGGER_TYPE_AFTER, TRIGGER_TYPE_UPDATE);
2048 116656 : trigdesc->trig_delete_before_row |=
2049 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2050 : TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE);
2051 116656 : trigdesc->trig_delete_after_row |=
2052 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2053 : TRIGGER_TYPE_AFTER, TRIGGER_TYPE_DELETE);
2054 116656 : trigdesc->trig_delete_instead_row |=
2055 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_ROW,
2056 : TRIGGER_TYPE_INSTEAD, TRIGGER_TYPE_DELETE);
2057 116656 : trigdesc->trig_delete_before_statement |=
2058 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2059 : TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_DELETE);
2060 116656 : trigdesc->trig_delete_after_statement |=
2061 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2062 : TRIGGER_TYPE_AFTER, TRIGGER_TYPE_DELETE);
2063 : /* there are no row-level truncate triggers */
2064 116656 : trigdesc->trig_truncate_before_statement |=
2065 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2066 : TRIGGER_TYPE_BEFORE, TRIGGER_TYPE_TRUNCATE);
2067 116656 : trigdesc->trig_truncate_after_statement |=
2068 116656 : TRIGGER_TYPE_MATCHES(tgtype, TRIGGER_TYPE_STATEMENT,
2069 : TRIGGER_TYPE_AFTER, TRIGGER_TYPE_TRUNCATE);
2070 :
2071 233312 : trigdesc->trig_insert_new_table |=
2072 154930 : (TRIGGER_FOR_INSERT(tgtype) &&
2073 38274 : TRIGGER_USES_TRANSITION_TABLE(trigger->tgnewtable));
2074 233312 : trigdesc->trig_update_old_table |=
2075 170264 : (TRIGGER_FOR_UPDATE(tgtype) &&
2076 53608 : TRIGGER_USES_TRANSITION_TABLE(trigger->tgoldtable));
2077 233312 : trigdesc->trig_update_new_table |=
2078 170264 : (TRIGGER_FOR_UPDATE(tgtype) &&
2079 53608 : TRIGGER_USES_TRANSITION_TABLE(trigger->tgnewtable));
2080 233312 : trigdesc->trig_delete_old_table |=
2081 149000 : (TRIGGER_FOR_DELETE(tgtype) &&
2082 32344 : TRIGGER_USES_TRANSITION_TABLE(trigger->tgoldtable));
2083 116656 : }
2084 :
2085 : /*
2086 : * Copy a TriggerDesc data structure.
2087 : *
2088 : * The copy is allocated in the current memory context.
2089 : */
2090 : TriggerDesc *
2091 482856 : CopyTriggerDesc(TriggerDesc *trigdesc)
2092 : {
2093 : TriggerDesc *newdesc;
2094 : Trigger *trigger;
2095 : int i;
2096 :
2097 482856 : if (trigdesc == NULL || trigdesc->numtriggers <= 0)
2098 416304 : return NULL;
2099 :
2100 66552 : newdesc = (TriggerDesc *) palloc(sizeof(TriggerDesc));
2101 66552 : memcpy(newdesc, trigdesc, sizeof(TriggerDesc));
2102 :
2103 66552 : trigger = (Trigger *) palloc(trigdesc->numtriggers * sizeof(Trigger));
2104 66552 : memcpy(trigger, trigdesc->triggers,
2105 66552 : trigdesc->numtriggers * sizeof(Trigger));
2106 66552 : newdesc->triggers = trigger;
2107 :
2108 231260 : for (i = 0; i < trigdesc->numtriggers; i++)
2109 : {
2110 164708 : trigger->tgname = pstrdup(trigger->tgname);
2111 164708 : if (trigger->tgnattr > 0)
2112 : {
2113 : int16 *newattr;
2114 :
2115 1064 : newattr = (int16 *) palloc(trigger->tgnattr * sizeof(int16));
2116 1064 : memcpy(newattr, trigger->tgattr,
2117 1064 : trigger->tgnattr * sizeof(int16));
2118 1064 : trigger->tgattr = newattr;
2119 : }
2120 164708 : if (trigger->tgnargs > 0)
2121 : {
2122 : char **newargs;
2123 : int16 j;
2124 :
2125 9252 : newargs = (char **) palloc(trigger->tgnargs * sizeof(char *));
2126 19690 : for (j = 0; j < trigger->tgnargs; j++)
2127 10438 : newargs[j] = pstrdup(trigger->tgargs[j]);
2128 9252 : trigger->tgargs = newargs;
2129 : }
2130 164708 : if (trigger->tgqual)
2131 1508 : trigger->tgqual = pstrdup(trigger->tgqual);
2132 164708 : if (trigger->tgoldtable)
2133 2036 : trigger->tgoldtable = pstrdup(trigger->tgoldtable);
2134 164708 : if (trigger->tgnewtable)
2135 2410 : trigger->tgnewtable = pstrdup(trigger->tgnewtable);
2136 164708 : trigger++;
2137 : }
2138 :
2139 66552 : return newdesc;
2140 : }
2141 :
2142 : /*
2143 : * Free a TriggerDesc data structure.
2144 : */
2145 : void
2146 1298368 : FreeTriggerDesc(TriggerDesc *trigdesc)
2147 : {
2148 : Trigger *trigger;
2149 : int i;
2150 :
2151 1298368 : if (trigdesc == NULL)
2152 1204456 : return;
2153 :
2154 93912 : trigger = trigdesc->triggers;
2155 313118 : for (i = 0; i < trigdesc->numtriggers; i++)
2156 : {
2157 219206 : pfree(trigger->tgname);
2158 219206 : if (trigger->tgnattr > 0)
2159 1066 : pfree(trigger->tgattr);
2160 219206 : if (trigger->tgnargs > 0)
2161 : {
2162 12176 : while (--(trigger->tgnargs) >= 0)
2163 6542 : pfree(trigger->tgargs[trigger->tgnargs]);
2164 5634 : pfree(trigger->tgargs);
2165 : }
2166 219206 : if (trigger->tgqual)
2167 1720 : pfree(trigger->tgqual);
2168 219206 : if (trigger->tgoldtable)
2169 1618 : pfree(trigger->tgoldtable);
2170 219206 : if (trigger->tgnewtable)
2171 2228 : pfree(trigger->tgnewtable);
2172 219206 : trigger++;
2173 : }
2174 93912 : pfree(trigdesc->triggers);
2175 93912 : 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 3088 : FindTriggerIncompatibleWithInheritance(TriggerDesc *trigdesc)
2279 : {
2280 3088 : if (trigdesc != NULL)
2281 : {
2282 : int i;
2283 :
2284 564 : for (i = 0; i < trigdesc->numtriggers; ++i)
2285 : {
2286 402 : Trigger *trigger = &trigdesc->triggers[i];
2287 :
2288 402 : if (trigger->tgoldtable != NULL || trigger->tgnewtable != NULL)
2289 12 : return trigger->tgname;
2290 : }
2291 : }
2292 :
2293 3076 : return NULL;
2294 : }
2295 :
2296 : /*
2297 : * Call a trigger function.
2298 : *
2299 : * trigdata: trigger descriptor.
2300 : * tgindx: trigger's index in finfo and instr arrays.
2301 : * finfo: array of cached trigger function call information.
2302 : * instr: optional array of EXPLAIN ANALYZE instrumentation state.
2303 : * per_tuple_context: memory context to execute the function in.
2304 : *
2305 : * Returns the tuple (or NULL) as returned by the function.
2306 : */
2307 : static HeapTuple
2308 21834 : ExecCallTriggerFunc(TriggerData *trigdata,
2309 : int tgindx,
2310 : FmgrInfo *finfo,
2311 : Instrumentation *instr,
2312 : MemoryContext per_tuple_context)
2313 : {
2314 21834 : LOCAL_FCINFO(fcinfo, 0);
2315 : PgStat_FunctionCallUsage fcusage;
2316 : Datum result;
2317 : MemoryContext oldContext;
2318 :
2319 : /*
2320 : * Protect against code paths that may fail to initialize transition table
2321 : * info.
2322 : */
2323 : Assert(((TRIGGER_FIRED_BY_INSERT(trigdata->tg_event) ||
2324 : TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event) ||
2325 : TRIGGER_FIRED_BY_DELETE(trigdata->tg_event)) &&
2326 : TRIGGER_FIRED_AFTER(trigdata->tg_event) &&
2327 : !(trigdata->tg_event & AFTER_TRIGGER_DEFERRABLE) &&
2328 : !(trigdata->tg_event & AFTER_TRIGGER_INITDEFERRED)) ||
2329 : (trigdata->tg_oldtable == NULL && trigdata->tg_newtable == NULL));
2330 :
2331 21834 : finfo += tgindx;
2332 :
2333 : /*
2334 : * We cache fmgr lookup info, to avoid making the lookup again on each
2335 : * call.
2336 : */
2337 21834 : if (finfo->fn_oid == InvalidOid)
2338 18586 : fmgr_info(trigdata->tg_trigger->tgfoid, finfo);
2339 :
2340 : Assert(finfo->fn_oid == trigdata->tg_trigger->tgfoid);
2341 :
2342 : /*
2343 : * If doing EXPLAIN ANALYZE, start charging time to this trigger.
2344 : */
2345 21834 : if (instr)
2346 0 : InstrStartNode(instr + tgindx);
2347 :
2348 : /*
2349 : * Do the function evaluation in the per-tuple memory context, so that
2350 : * leaked memory will be reclaimed once per tuple. Note in particular that
2351 : * any new tuple created by the trigger function will live till the end of
2352 : * the tuple cycle.
2353 : */
2354 21834 : oldContext = MemoryContextSwitchTo(per_tuple_context);
2355 :
2356 : /*
2357 : * Call the function, passing no arguments but setting a context.
2358 : */
2359 21834 : InitFunctionCallInfoData(*fcinfo, finfo, 0,
2360 : InvalidOid, (Node *) trigdata, NULL);
2361 :
2362 21834 : pgstat_init_function_usage(fcinfo, &fcusage);
2363 :
2364 21834 : MyTriggerDepth++;
2365 21834 : PG_TRY();
2366 : {
2367 21834 : result = FunctionCallInvoke(fcinfo);
2368 : }
2369 1382 : PG_FINALLY();
2370 : {
2371 21834 : MyTriggerDepth--;
2372 : }
2373 21834 : PG_END_TRY();
2374 :
2375 20452 : pgstat_end_function_usage(&fcusage, true);
2376 :
2377 20452 : MemoryContextSwitchTo(oldContext);
2378 :
2379 : /*
2380 : * Trigger protocol allows function to return a null pointer, but NOT to
2381 : * set the isnull result flag.
2382 : */
2383 20452 : if (fcinfo->isnull)
2384 0 : ereport(ERROR,
2385 : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2386 : errmsg("trigger function %u returned null value",
2387 : fcinfo->flinfo->fn_oid)));
2388 :
2389 : /*
2390 : * If doing EXPLAIN ANALYZE, stop charging time to this trigger, and count
2391 : * one "tuple returned" (really the number of firings).
2392 : */
2393 20452 : if (instr)
2394 0 : InstrStopNode(instr + tgindx, 1);
2395 :
2396 20452 : return (HeapTuple) DatumGetPointer(result);
2397 : }
2398 :
2399 : void
2400 91294 : ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
2401 : {
2402 : TriggerDesc *trigdesc;
2403 : int i;
2404 91294 : TriggerData LocTriggerData = {0};
2405 :
2406 91294 : trigdesc = relinfo->ri_TrigDesc;
2407 :
2408 91294 : if (trigdesc == NULL)
2409 91082 : return;
2410 7110 : if (!trigdesc->trig_insert_before_statement)
2411 6898 : return;
2412 :
2413 : /* no-op if we already fired BS triggers in this context */
2414 212 : if (before_stmt_triggers_fired(RelationGetRelid(relinfo->ri_RelationDesc),
2415 : CMD_INSERT))
2416 0 : return;
2417 :
2418 212 : LocTriggerData.type = T_TriggerData;
2419 212 : LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2420 : TRIGGER_EVENT_BEFORE;
2421 212 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2422 1832 : for (i = 0; i < trigdesc->numtriggers; i++)
2423 : {
2424 1632 : Trigger *trigger = &trigdesc->triggers[i];
2425 : HeapTuple newtuple;
2426 :
2427 1632 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2428 : TRIGGER_TYPE_STATEMENT,
2429 : TRIGGER_TYPE_BEFORE,
2430 : TRIGGER_TYPE_INSERT))
2431 1408 : continue;
2432 224 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2433 : NULL, NULL, NULL))
2434 30 : continue;
2435 :
2436 194 : LocTriggerData.tg_trigger = trigger;
2437 194 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
2438 : i,
2439 : relinfo->ri_TrigFunctions,
2440 : relinfo->ri_TrigInstrument,
2441 194 : GetPerTupleMemoryContext(estate));
2442 :
2443 182 : if (newtuple)
2444 0 : ereport(ERROR,
2445 : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2446 : errmsg("BEFORE STATEMENT trigger cannot return a value")));
2447 : }
2448 : }
2449 :
2450 : void
2451 88716 : ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo,
2452 : TransitionCaptureState *transition_capture)
2453 : {
2454 88716 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2455 :
2456 88716 : if (trigdesc && trigdesc->trig_insert_after_statement)
2457 442 : AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2458 : TRIGGER_EVENT_INSERT,
2459 : false, NULL, NULL, NIL, NULL, transition_capture,
2460 : false);
2461 88716 : }
2462 :
2463 : bool
2464 2334 : ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo,
2465 : TupleTableSlot *slot)
2466 : {
2467 2334 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2468 2334 : HeapTuple newtuple = NULL;
2469 : bool should_free;
2470 2334 : TriggerData LocTriggerData = {0};
2471 : int i;
2472 :
2473 2334 : LocTriggerData.type = T_TriggerData;
2474 2334 : LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2475 : TRIGGER_EVENT_ROW |
2476 : TRIGGER_EVENT_BEFORE;
2477 2334 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2478 10886 : for (i = 0; i < trigdesc->numtriggers; i++)
2479 : {
2480 8868 : Trigger *trigger = &trigdesc->triggers[i];
2481 : HeapTuple oldtuple;
2482 :
2483 8868 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2484 : TRIGGER_TYPE_ROW,
2485 : TRIGGER_TYPE_BEFORE,
2486 : TRIGGER_TYPE_INSERT))
2487 4244 : continue;
2488 4624 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2489 : NULL, NULL, slot))
2490 62 : continue;
2491 :
2492 4562 : if (!newtuple)
2493 2300 : newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2494 :
2495 4562 : LocTriggerData.tg_trigslot = slot;
2496 4562 : LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2497 4562 : LocTriggerData.tg_trigger = trigger;
2498 4562 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
2499 : i,
2500 : relinfo->ri_TrigFunctions,
2501 : relinfo->ri_TrigInstrument,
2502 4562 : GetPerTupleMemoryContext(estate));
2503 4488 : if (newtuple == NULL)
2504 : {
2505 218 : if (should_free)
2506 20 : heap_freetuple(oldtuple);
2507 218 : return false; /* "do nothing" */
2508 : }
2509 4270 : else if (newtuple != oldtuple)
2510 : {
2511 744 : newtuple = check_modified_virtual_generated(RelationGetDescr(relinfo->ri_RelationDesc), newtuple);
2512 :
2513 744 : ExecForceStoreHeapTuple(newtuple, slot, false);
2514 :
2515 : /*
2516 : * After a tuple in a partition goes through a trigger, the user
2517 : * could have changed the partition key enough that the tuple no
2518 : * longer fits the partition. Verify that.
2519 : */
2520 744 : if (trigger->tgisclone &&
2521 66 : !ExecPartitionCheck(relinfo, slot, estate, false))
2522 24 : ereport(ERROR,
2523 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2524 : errmsg("moving row to another partition during a BEFORE FOR EACH ROW trigger is not supported"),
2525 : errdetail("Before executing trigger \"%s\", the row was to be in partition \"%s.%s\".",
2526 : trigger->tgname,
2527 : get_namespace_name(RelationGetNamespace(relinfo->ri_RelationDesc)),
2528 : RelationGetRelationName(relinfo->ri_RelationDesc))));
2529 :
2530 720 : if (should_free)
2531 40 : heap_freetuple(oldtuple);
2532 :
2533 : /* signal tuple should be re-fetched if used */
2534 720 : newtuple = NULL;
2535 : }
2536 : }
2537 :
2538 2018 : return true;
2539 : }
2540 :
2541 : void
2542 12600340 : ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo,
2543 : TupleTableSlot *slot, List *recheckIndexes,
2544 : TransitionCaptureState *transition_capture)
2545 : {
2546 12600340 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2547 :
2548 12600340 : if ((trigdesc && trigdesc->trig_insert_after_row) ||
2549 60324 : (transition_capture && transition_capture->tcs_insert_new_table))
2550 65658 : AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2551 : TRIGGER_EVENT_INSERT,
2552 : true, NULL, slot,
2553 : recheckIndexes, NULL,
2554 : transition_capture,
2555 : false);
2556 12600340 : }
2557 :
2558 : bool
2559 180 : ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo,
2560 : TupleTableSlot *slot)
2561 : {
2562 180 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2563 180 : HeapTuple newtuple = NULL;
2564 : bool should_free;
2565 180 : TriggerData LocTriggerData = {0};
2566 : int i;
2567 :
2568 180 : LocTriggerData.type = T_TriggerData;
2569 180 : LocTriggerData.tg_event = TRIGGER_EVENT_INSERT |
2570 : TRIGGER_EVENT_ROW |
2571 : TRIGGER_EVENT_INSTEAD;
2572 180 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2573 546 : for (i = 0; i < trigdesc->numtriggers; i++)
2574 : {
2575 384 : Trigger *trigger = &trigdesc->triggers[i];
2576 : HeapTuple oldtuple;
2577 :
2578 384 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2579 : TRIGGER_TYPE_ROW,
2580 : TRIGGER_TYPE_INSTEAD,
2581 : TRIGGER_TYPE_INSERT))
2582 204 : continue;
2583 180 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2584 : NULL, NULL, slot))
2585 0 : continue;
2586 :
2587 180 : if (!newtuple)
2588 180 : newtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2589 :
2590 180 : LocTriggerData.tg_trigslot = slot;
2591 180 : LocTriggerData.tg_trigtuple = oldtuple = newtuple;
2592 180 : LocTriggerData.tg_trigger = trigger;
2593 180 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
2594 : i,
2595 : relinfo->ri_TrigFunctions,
2596 : relinfo->ri_TrigInstrument,
2597 180 : GetPerTupleMemoryContext(estate));
2598 180 : if (newtuple == NULL)
2599 : {
2600 18 : if (should_free)
2601 18 : heap_freetuple(oldtuple);
2602 18 : return false; /* "do nothing" */
2603 : }
2604 162 : else if (newtuple != oldtuple)
2605 : {
2606 54 : ExecForceStoreHeapTuple(newtuple, slot, false);
2607 :
2608 54 : if (should_free)
2609 54 : heap_freetuple(oldtuple);
2610 :
2611 : /* signal tuple should be re-fetched if used */
2612 54 : newtuple = NULL;
2613 : }
2614 : }
2615 :
2616 162 : return true;
2617 : }
2618 :
2619 : void
2620 12456 : ExecBSDeleteTriggers(EState *estate, ResultRelInfo *relinfo)
2621 : {
2622 : TriggerDesc *trigdesc;
2623 : int i;
2624 12456 : TriggerData LocTriggerData = {0};
2625 :
2626 12456 : trigdesc = relinfo->ri_TrigDesc;
2627 :
2628 12456 : if (trigdesc == NULL)
2629 12378 : return;
2630 1520 : if (!trigdesc->trig_delete_before_statement)
2631 1400 : return;
2632 :
2633 : /* no-op if we already fired BS triggers in this context */
2634 120 : if (before_stmt_triggers_fired(RelationGetRelid(relinfo->ri_RelationDesc),
2635 : CMD_DELETE))
2636 42 : return;
2637 :
2638 78 : LocTriggerData.type = T_TriggerData;
2639 78 : LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2640 : TRIGGER_EVENT_BEFORE;
2641 78 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2642 708 : for (i = 0; i < trigdesc->numtriggers; i++)
2643 : {
2644 630 : Trigger *trigger = &trigdesc->triggers[i];
2645 : HeapTuple newtuple;
2646 :
2647 630 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2648 : TRIGGER_TYPE_STATEMENT,
2649 : TRIGGER_TYPE_BEFORE,
2650 : TRIGGER_TYPE_DELETE))
2651 552 : continue;
2652 78 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2653 : NULL, NULL, NULL))
2654 12 : continue;
2655 :
2656 66 : LocTriggerData.tg_trigger = trigger;
2657 66 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
2658 : i,
2659 : relinfo->ri_TrigFunctions,
2660 : relinfo->ri_TrigInstrument,
2661 66 : GetPerTupleMemoryContext(estate));
2662 :
2663 66 : if (newtuple)
2664 0 : ereport(ERROR,
2665 : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2666 : errmsg("BEFORE STATEMENT trigger cannot return a value")));
2667 : }
2668 : }
2669 :
2670 : void
2671 12314 : ExecASDeleteTriggers(EState *estate, ResultRelInfo *relinfo,
2672 : TransitionCaptureState *transition_capture)
2673 : {
2674 12314 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2675 :
2676 12314 : if (trigdesc && trigdesc->trig_delete_after_statement)
2677 236 : AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2678 : TRIGGER_EVENT_DELETE,
2679 : false, NULL, NULL, NIL, NULL, transition_capture,
2680 : false);
2681 12314 : }
2682 :
2683 : /*
2684 : * Execute BEFORE ROW DELETE triggers.
2685 : *
2686 : * True indicates caller can proceed with the delete. False indicates caller
2687 : * need to suppress the delete and additionally if requested, we need to pass
2688 : * back the concurrently updated tuple if any.
2689 : */
2690 : bool
2691 346 : ExecBRDeleteTriggers(EState *estate, EPQState *epqstate,
2692 : ResultRelInfo *relinfo,
2693 : ItemPointer tupleid,
2694 : HeapTuple fdw_trigtuple,
2695 : TupleTableSlot **epqslot,
2696 : TM_Result *tmresult,
2697 : TM_FailureData *tmfd,
2698 : bool is_merge_delete)
2699 : {
2700 346 : TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2701 346 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2702 346 : bool result = true;
2703 346 : TriggerData LocTriggerData = {0};
2704 : HeapTuple trigtuple;
2705 346 : bool should_free = false;
2706 : int i;
2707 :
2708 : Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2709 346 : if (fdw_trigtuple == NULL)
2710 : {
2711 330 : TupleTableSlot *epqslot_candidate = NULL;
2712 :
2713 : /*
2714 : * Get a copy of the on-disk tuple we are planning to delete. In
2715 : * general, if the tuple has been concurrently updated, we should
2716 : * recheck it using EPQ. However, if this is a MERGE DELETE action,
2717 : * we skip this EPQ recheck and leave it to the caller (it must do
2718 : * additional rechecking, and might end up executing a different
2719 : * action entirely).
2720 : */
2721 324 : if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2722 330 : LockTupleExclusive, slot, !is_merge_delete,
2723 330 : &epqslot_candidate, tmresult, tmfd))
2724 12 : return false;
2725 :
2726 : /*
2727 : * If the tuple was concurrently updated and the caller of this
2728 : * function requested for the updated tuple, skip the trigger
2729 : * execution.
2730 : */
2731 314 : if (epqslot_candidate != NULL && epqslot != NULL)
2732 : {
2733 2 : *epqslot = epqslot_candidate;
2734 2 : return false;
2735 : }
2736 :
2737 312 : trigtuple = ExecFetchSlotHeapTuple(slot, true, &should_free);
2738 : }
2739 : else
2740 : {
2741 16 : trigtuple = fdw_trigtuple;
2742 16 : ExecForceStoreHeapTuple(trigtuple, slot, false);
2743 : }
2744 :
2745 328 : LocTriggerData.type = T_TriggerData;
2746 328 : LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2747 : TRIGGER_EVENT_ROW |
2748 : TRIGGER_EVENT_BEFORE;
2749 328 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2750 1228 : for (i = 0; i < trigdesc->numtriggers; i++)
2751 : {
2752 : HeapTuple newtuple;
2753 962 : Trigger *trigger = &trigdesc->triggers[i];
2754 :
2755 962 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2756 : TRIGGER_TYPE_ROW,
2757 : TRIGGER_TYPE_BEFORE,
2758 : TRIGGER_TYPE_DELETE))
2759 628 : continue;
2760 334 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2761 : NULL, slot, NULL))
2762 14 : continue;
2763 :
2764 320 : LocTriggerData.tg_trigslot = slot;
2765 320 : LocTriggerData.tg_trigtuple = trigtuple;
2766 320 : LocTriggerData.tg_trigger = trigger;
2767 320 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
2768 : i,
2769 : relinfo->ri_TrigFunctions,
2770 : relinfo->ri_TrigInstrument,
2771 320 : GetPerTupleMemoryContext(estate));
2772 310 : if (newtuple == NULL)
2773 : {
2774 52 : result = false; /* tell caller to suppress delete */
2775 52 : break;
2776 : }
2777 258 : if (newtuple != trigtuple)
2778 56 : heap_freetuple(newtuple);
2779 : }
2780 318 : if (should_free)
2781 0 : heap_freetuple(trigtuple);
2782 :
2783 318 : return result;
2784 : }
2785 :
2786 : /*
2787 : * Note: is_crosspart_update must be true if the DELETE is being performed
2788 : * as part of a cross-partition update.
2789 : */
2790 : void
2791 1727774 : ExecARDeleteTriggers(EState *estate,
2792 : ResultRelInfo *relinfo,
2793 : ItemPointer tupleid,
2794 : HeapTuple fdw_trigtuple,
2795 : TransitionCaptureState *transition_capture,
2796 : bool is_crosspart_update)
2797 : {
2798 1727774 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2799 :
2800 1727774 : if ((trigdesc && trigdesc->trig_delete_after_row) ||
2801 5016 : (transition_capture && transition_capture->tcs_delete_old_table))
2802 : {
2803 6180 : TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2804 :
2805 : Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2806 6180 : if (fdw_trigtuple == NULL)
2807 6164 : GetTupleForTrigger(estate,
2808 : NULL,
2809 : relinfo,
2810 : tupleid,
2811 : LockTupleExclusive,
2812 : slot,
2813 : false,
2814 : NULL,
2815 : NULL,
2816 : NULL);
2817 : else
2818 16 : ExecForceStoreHeapTuple(fdw_trigtuple, slot, false);
2819 :
2820 6180 : AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2821 : TRIGGER_EVENT_DELETE,
2822 : true, slot, NULL, NIL, NULL,
2823 : transition_capture,
2824 : is_crosspart_update);
2825 : }
2826 1727774 : }
2827 :
2828 : bool
2829 60 : ExecIRDeleteTriggers(EState *estate, ResultRelInfo *relinfo,
2830 : HeapTuple trigtuple)
2831 : {
2832 60 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2833 60 : TupleTableSlot *slot = ExecGetTriggerOldSlot(estate, relinfo);
2834 60 : TriggerData LocTriggerData = {0};
2835 : int i;
2836 :
2837 60 : LocTriggerData.type = T_TriggerData;
2838 60 : LocTriggerData.tg_event = TRIGGER_EVENT_DELETE |
2839 : TRIGGER_EVENT_ROW |
2840 : TRIGGER_EVENT_INSTEAD;
2841 60 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2842 :
2843 60 : ExecForceStoreHeapTuple(trigtuple, slot, false);
2844 :
2845 354 : for (i = 0; i < trigdesc->numtriggers; i++)
2846 : {
2847 : HeapTuple rettuple;
2848 300 : Trigger *trigger = &trigdesc->triggers[i];
2849 :
2850 300 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2851 : TRIGGER_TYPE_ROW,
2852 : TRIGGER_TYPE_INSTEAD,
2853 : TRIGGER_TYPE_DELETE))
2854 240 : continue;
2855 60 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2856 : NULL, slot, NULL))
2857 0 : continue;
2858 :
2859 60 : LocTriggerData.tg_trigslot = slot;
2860 60 : LocTriggerData.tg_trigtuple = trigtuple;
2861 60 : LocTriggerData.tg_trigger = trigger;
2862 60 : rettuple = ExecCallTriggerFunc(&LocTriggerData,
2863 : i,
2864 : relinfo->ri_TrigFunctions,
2865 : relinfo->ri_TrigInstrument,
2866 60 : GetPerTupleMemoryContext(estate));
2867 60 : if (rettuple == NULL)
2868 6 : return false; /* Delete was suppressed */
2869 54 : if (rettuple != trigtuple)
2870 0 : heap_freetuple(rettuple);
2871 : }
2872 54 : return true;
2873 : }
2874 :
2875 : void
2876 15270 : ExecBSUpdateTriggers(EState *estate, ResultRelInfo *relinfo)
2877 : {
2878 : TriggerDesc *trigdesc;
2879 : int i;
2880 15270 : TriggerData LocTriggerData = {0};
2881 : Bitmapset *updatedCols;
2882 :
2883 15270 : trigdesc = relinfo->ri_TrigDesc;
2884 :
2885 15270 : if (trigdesc == NULL)
2886 15092 : return;
2887 4116 : if (!trigdesc->trig_update_before_statement)
2888 3938 : return;
2889 :
2890 : /* no-op if we already fired BS triggers in this context */
2891 178 : if (before_stmt_triggers_fired(RelationGetRelid(relinfo->ri_RelationDesc),
2892 : CMD_UPDATE))
2893 0 : return;
2894 :
2895 : /* statement-level triggers operate on the parent table */
2896 : Assert(relinfo->ri_RootResultRelInfo == NULL);
2897 :
2898 178 : updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
2899 :
2900 178 : LocTriggerData.type = T_TriggerData;
2901 178 : LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
2902 : TRIGGER_EVENT_BEFORE;
2903 178 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
2904 178 : LocTriggerData.tg_updatedcols = updatedCols;
2905 1600 : for (i = 0; i < trigdesc->numtriggers; i++)
2906 : {
2907 1422 : Trigger *trigger = &trigdesc->triggers[i];
2908 : HeapTuple newtuple;
2909 :
2910 1422 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
2911 : TRIGGER_TYPE_STATEMENT,
2912 : TRIGGER_TYPE_BEFORE,
2913 : TRIGGER_TYPE_UPDATE))
2914 1244 : continue;
2915 178 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
2916 : updatedCols, NULL, NULL))
2917 6 : continue;
2918 :
2919 172 : LocTriggerData.tg_trigger = trigger;
2920 172 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
2921 : i,
2922 : relinfo->ri_TrigFunctions,
2923 : relinfo->ri_TrigInstrument,
2924 172 : GetPerTupleMemoryContext(estate));
2925 :
2926 172 : if (newtuple)
2927 0 : ereport(ERROR,
2928 : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2929 : errmsg("BEFORE STATEMENT trigger cannot return a value")));
2930 : }
2931 : }
2932 :
2933 : void
2934 14364 : ExecASUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
2935 : TransitionCaptureState *transition_capture)
2936 : {
2937 14364 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2938 :
2939 : /* statement-level triggers operate on the parent table */
2940 : Assert(relinfo->ri_RootResultRelInfo == NULL);
2941 :
2942 14364 : if (trigdesc && trigdesc->trig_update_after_statement)
2943 408 : AfterTriggerSaveEvent(estate, relinfo, NULL, NULL,
2944 : TRIGGER_EVENT_UPDATE,
2945 : false, NULL, NULL, NIL,
2946 : ExecGetAllUpdatedCols(relinfo, estate),
2947 : transition_capture,
2948 : false);
2949 14364 : }
2950 :
2951 : bool
2952 2566 : ExecBRUpdateTriggers(EState *estate, EPQState *epqstate,
2953 : ResultRelInfo *relinfo,
2954 : ItemPointer tupleid,
2955 : HeapTuple fdw_trigtuple,
2956 : TupleTableSlot *newslot,
2957 : TM_Result *tmresult,
2958 : TM_FailureData *tmfd,
2959 : bool is_merge_update)
2960 : {
2961 2566 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
2962 2566 : TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
2963 2566 : HeapTuple newtuple = NULL;
2964 : HeapTuple trigtuple;
2965 2566 : bool should_free_trig = false;
2966 2566 : bool should_free_new = false;
2967 2566 : TriggerData LocTriggerData = {0};
2968 : int i;
2969 : Bitmapset *updatedCols;
2970 : LockTupleMode lockmode;
2971 :
2972 : /* Determine lock mode to use */
2973 2566 : lockmode = ExecUpdateLockMode(estate, relinfo);
2974 :
2975 : Assert(HeapTupleIsValid(fdw_trigtuple) ^ ItemPointerIsValid(tupleid));
2976 2566 : if (fdw_trigtuple == NULL)
2977 : {
2978 2528 : TupleTableSlot *epqslot_candidate = NULL;
2979 :
2980 : /*
2981 : * Get a copy of the on-disk tuple we are planning to update. In
2982 : * general, if the tuple has been concurrently updated, we should
2983 : * recheck it using EPQ. However, if this is a MERGE UPDATE action,
2984 : * we skip this EPQ recheck and leave it to the caller (it must do
2985 : * additional rechecking, and might end up executing a different
2986 : * action entirely).
2987 : */
2988 2520 : if (!GetTupleForTrigger(estate, epqstate, relinfo, tupleid,
2989 2528 : lockmode, oldslot, !is_merge_update,
2990 2528 : &epqslot_candidate, tmresult, tmfd))
2991 22 : return false; /* cancel the update action */
2992 :
2993 : /*
2994 : * In READ COMMITTED isolation level it's possible that target tuple
2995 : * was changed due to concurrent update. In that case we have a raw
2996 : * subplan output tuple in epqslot_candidate, and need to form a new
2997 : * insertable tuple using ExecGetUpdateNewTuple to replace the one we
2998 : * received in newslot. Neither we nor our callers have any further
2999 : * interest in the passed-in tuple, so it's okay to overwrite newslot
3000 : * with the newer data.
3001 : */
3002 2498 : if (epqslot_candidate != NULL)
3003 : {
3004 : TupleTableSlot *epqslot_clean;
3005 :
3006 6 : epqslot_clean = ExecGetUpdateNewTuple(relinfo, epqslot_candidate,
3007 : oldslot);
3008 :
3009 : /*
3010 : * Typically, the caller's newslot was also generated by
3011 : * ExecGetUpdateNewTuple, so that epqslot_clean will be the same
3012 : * slot and copying is not needed. But do the right thing if it
3013 : * isn't.
3014 : */
3015 6 : if (unlikely(newslot != epqslot_clean))
3016 0 : ExecCopySlot(newslot, epqslot_clean);
3017 :
3018 : /*
3019 : * At this point newslot contains a virtual tuple that may
3020 : * reference some fields of oldslot's tuple in some disk buffer.
3021 : * If that tuple is in a different page than the original target
3022 : * tuple, then our only pin on that buffer is oldslot's, and we're
3023 : * about to release it. Hence we'd better materialize newslot to
3024 : * ensure it doesn't contain references into an unpinned buffer.
3025 : * (We'd materialize it below anyway, but too late for safety.)
3026 : */
3027 6 : ExecMaterializeSlot(newslot);
3028 : }
3029 :
3030 : /*
3031 : * Here we convert oldslot to a materialized slot holding trigtuple.
3032 : * Neither slot passed to the triggers will hold any buffer pin.
3033 : */
3034 2498 : trigtuple = ExecFetchSlotHeapTuple(oldslot, true, &should_free_trig);
3035 : }
3036 : else
3037 : {
3038 : /* Put the FDW-supplied tuple into oldslot to unify the cases */
3039 38 : ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
3040 38 : trigtuple = fdw_trigtuple;
3041 : }
3042 :
3043 2536 : LocTriggerData.type = T_TriggerData;
3044 2536 : LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
3045 : TRIGGER_EVENT_ROW |
3046 : TRIGGER_EVENT_BEFORE;
3047 2536 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3048 2536 : updatedCols = ExecGetAllUpdatedCols(relinfo, estate);
3049 2536 : LocTriggerData.tg_updatedcols = updatedCols;
3050 11446 : for (i = 0; i < trigdesc->numtriggers; i++)
3051 : {
3052 9058 : Trigger *trigger = &trigdesc->triggers[i];
3053 : HeapTuple oldtuple;
3054 :
3055 9058 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3056 : TRIGGER_TYPE_ROW,
3057 : TRIGGER_TYPE_BEFORE,
3058 : TRIGGER_TYPE_UPDATE))
3059 4462 : continue;
3060 4596 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3061 : updatedCols, oldslot, newslot))
3062 98 : continue;
3063 :
3064 4498 : if (!newtuple)
3065 2524 : newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free_new);
3066 :
3067 4498 : LocTriggerData.tg_trigslot = oldslot;
3068 4498 : LocTriggerData.tg_trigtuple = trigtuple;
3069 4498 : LocTriggerData.tg_newtuple = oldtuple = newtuple;
3070 4498 : LocTriggerData.tg_newslot = newslot;
3071 4498 : LocTriggerData.tg_trigger = trigger;
3072 4498 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
3073 : i,
3074 : relinfo->ri_TrigFunctions,
3075 : relinfo->ri_TrigInstrument,
3076 4498 : GetPerTupleMemoryContext(estate));
3077 :
3078 4482 : if (newtuple == NULL)
3079 : {
3080 132 : if (should_free_trig)
3081 0 : heap_freetuple(trigtuple);
3082 132 : if (should_free_new)
3083 4 : heap_freetuple(oldtuple);
3084 132 : return false; /* "do nothing" */
3085 : }
3086 4350 : else if (newtuple != oldtuple)
3087 : {
3088 1304 : newtuple = check_modified_virtual_generated(RelationGetDescr(relinfo->ri_RelationDesc), newtuple);
3089 :
3090 1304 : ExecForceStoreHeapTuple(newtuple, newslot, false);
3091 :
3092 : /*
3093 : * If the tuple returned by the trigger / being stored, is the old
3094 : * row version, and the heap tuple passed to the trigger was
3095 : * allocated locally, materialize the slot. Otherwise we might
3096 : * free it while still referenced by the slot.
3097 : */
3098 1304 : if (should_free_trig && newtuple == trigtuple)
3099 0 : ExecMaterializeSlot(newslot);
3100 :
3101 1304 : if (should_free_new)
3102 2 : heap_freetuple(oldtuple);
3103 :
3104 : /* signal tuple should be re-fetched if used */
3105 1304 : newtuple = NULL;
3106 : }
3107 : }
3108 2388 : if (should_free_trig)
3109 0 : heap_freetuple(trigtuple);
3110 :
3111 2388 : return true;
3112 : }
3113 :
3114 : /*
3115 : * Note: 'src_partinfo' and 'dst_partinfo', when non-NULL, refer to the source
3116 : * and destination partitions, respectively, of a cross-partition update of
3117 : * the root partitioned table mentioned in the query, given by 'relinfo'.
3118 : * 'tupleid' in that case refers to the ctid of the "old" tuple in the source
3119 : * partition, and 'newslot' contains the "new" tuple in the destination
3120 : * partition. This interface allows to support the requirements of
3121 : * ExecCrossPartitionUpdateForeignKey(); is_crosspart_update must be true in
3122 : * that case.
3123 : */
3124 : void
3125 387482 : ExecARUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
3126 : ResultRelInfo *src_partinfo,
3127 : ResultRelInfo *dst_partinfo,
3128 : ItemPointer tupleid,
3129 : HeapTuple fdw_trigtuple,
3130 : TupleTableSlot *newslot,
3131 : List *recheckIndexes,
3132 : TransitionCaptureState *transition_capture,
3133 : bool is_crosspart_update)
3134 : {
3135 387482 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3136 :
3137 387482 : if ((trigdesc && trigdesc->trig_update_after_row) ||
3138 372 : (transition_capture &&
3139 372 : (transition_capture->tcs_update_old_table ||
3140 18 : transition_capture->tcs_update_new_table)))
3141 : {
3142 : /*
3143 : * Note: if the UPDATE is converted into a DELETE+INSERT as part of
3144 : * update-partition-key operation, then this function is also called
3145 : * separately for DELETE and INSERT to capture transition table rows.
3146 : * In such case, either old tuple or new tuple can be NULL.
3147 : */
3148 : TupleTableSlot *oldslot;
3149 : ResultRelInfo *tupsrc;
3150 :
3151 : Assert((src_partinfo != NULL && dst_partinfo != NULL) ||
3152 : !is_crosspart_update);
3153 :
3154 3722 : tupsrc = src_partinfo ? src_partinfo : relinfo;
3155 3722 : oldslot = ExecGetTriggerOldSlot(estate, tupsrc);
3156 :
3157 3722 : if (fdw_trigtuple == NULL && ItemPointerIsValid(tupleid))
3158 3654 : GetTupleForTrigger(estate,
3159 : NULL,
3160 : tupsrc,
3161 : tupleid,
3162 : LockTupleExclusive,
3163 : oldslot,
3164 : false,
3165 : NULL,
3166 : NULL,
3167 : NULL);
3168 68 : else if (fdw_trigtuple != NULL)
3169 20 : ExecForceStoreHeapTuple(fdw_trigtuple, oldslot, false);
3170 : else
3171 48 : ExecClearTuple(oldslot);
3172 :
3173 3722 : AfterTriggerSaveEvent(estate, relinfo,
3174 : src_partinfo, dst_partinfo,
3175 : TRIGGER_EVENT_UPDATE,
3176 : true,
3177 : oldslot, newslot, recheckIndexes,
3178 : ExecGetAllUpdatedCols(relinfo, estate),
3179 : transition_capture,
3180 : is_crosspart_update);
3181 : }
3182 387482 : }
3183 :
3184 : bool
3185 204 : ExecIRUpdateTriggers(EState *estate, ResultRelInfo *relinfo,
3186 : HeapTuple trigtuple, TupleTableSlot *newslot)
3187 : {
3188 204 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3189 204 : TupleTableSlot *oldslot = ExecGetTriggerOldSlot(estate, relinfo);
3190 204 : HeapTuple newtuple = NULL;
3191 : bool should_free;
3192 204 : TriggerData LocTriggerData = {0};
3193 : int i;
3194 :
3195 204 : LocTriggerData.type = T_TriggerData;
3196 204 : LocTriggerData.tg_event = TRIGGER_EVENT_UPDATE |
3197 : TRIGGER_EVENT_ROW |
3198 : TRIGGER_EVENT_INSTEAD;
3199 204 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3200 :
3201 204 : ExecForceStoreHeapTuple(trigtuple, oldslot, false);
3202 :
3203 756 : for (i = 0; i < trigdesc->numtriggers; i++)
3204 : {
3205 582 : Trigger *trigger = &trigdesc->triggers[i];
3206 : HeapTuple oldtuple;
3207 :
3208 582 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3209 : TRIGGER_TYPE_ROW,
3210 : TRIGGER_TYPE_INSTEAD,
3211 : TRIGGER_TYPE_UPDATE))
3212 378 : continue;
3213 204 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3214 : NULL, oldslot, newslot))
3215 0 : continue;
3216 :
3217 204 : if (!newtuple)
3218 204 : newtuple = ExecFetchSlotHeapTuple(newslot, true, &should_free);
3219 :
3220 204 : LocTriggerData.tg_trigslot = oldslot;
3221 204 : LocTriggerData.tg_trigtuple = trigtuple;
3222 204 : LocTriggerData.tg_newslot = newslot;
3223 204 : LocTriggerData.tg_newtuple = oldtuple = newtuple;
3224 :
3225 204 : LocTriggerData.tg_trigger = trigger;
3226 204 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
3227 : i,
3228 : relinfo->ri_TrigFunctions,
3229 : relinfo->ri_TrigInstrument,
3230 204 : GetPerTupleMemoryContext(estate));
3231 192 : if (newtuple == NULL)
3232 : {
3233 18 : return false; /* "do nothing" */
3234 : }
3235 174 : else if (newtuple != oldtuple)
3236 : {
3237 138 : ExecForceStoreHeapTuple(newtuple, newslot, false);
3238 :
3239 138 : if (should_free)
3240 138 : heap_freetuple(oldtuple);
3241 :
3242 : /* signal tuple should be re-fetched if used */
3243 138 : newtuple = NULL;
3244 : }
3245 : }
3246 :
3247 174 : return true;
3248 : }
3249 :
3250 : void
3251 4974 : ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
3252 : {
3253 : TriggerDesc *trigdesc;
3254 : int i;
3255 4974 : TriggerData LocTriggerData = {0};
3256 :
3257 4974 : trigdesc = relinfo->ri_TrigDesc;
3258 :
3259 4974 : if (trigdesc == NULL)
3260 4962 : return;
3261 748 : if (!trigdesc->trig_truncate_before_statement)
3262 736 : return;
3263 :
3264 12 : LocTriggerData.type = T_TriggerData;
3265 12 : LocTriggerData.tg_event = TRIGGER_EVENT_TRUNCATE |
3266 : TRIGGER_EVENT_BEFORE;
3267 12 : LocTriggerData.tg_relation = relinfo->ri_RelationDesc;
3268 :
3269 36 : for (i = 0; i < trigdesc->numtriggers; i++)
3270 : {
3271 24 : Trigger *trigger = &trigdesc->triggers[i];
3272 : HeapTuple newtuple;
3273 :
3274 24 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
3275 : TRIGGER_TYPE_STATEMENT,
3276 : TRIGGER_TYPE_BEFORE,
3277 : TRIGGER_TYPE_TRUNCATE))
3278 12 : continue;
3279 12 : if (!TriggerEnabled(estate, relinfo, trigger, LocTriggerData.tg_event,
3280 : NULL, NULL, NULL))
3281 0 : continue;
3282 :
3283 12 : LocTriggerData.tg_trigger = trigger;
3284 12 : newtuple = ExecCallTriggerFunc(&LocTriggerData,
3285 : i,
3286 : relinfo->ri_TrigFunctions,
3287 : relinfo->ri_TrigInstrument,
3288 12 : GetPerTupleMemoryContext(estate));
3289 :
3290 12 : if (newtuple)
3291 0 : ereport(ERROR,
3292 : (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
3293 : errmsg("BEFORE STATEMENT trigger cannot return a value")));
3294 : }
3295 : }
3296 :
3297 : void
3298 4966 : ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
3299 : {
3300 4966 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
3301 :
3302 4966 : if (trigdesc && trigdesc->trig_truncate_after_statement)
3303 8 : AfterTriggerSaveEvent(estate, relinfo,
3304 : NULL, NULL,
3305 : TRIGGER_EVENT_TRUNCATE,
3306 : false, NULL, NULL, NIL, NULL, NULL,
3307 : false);
3308 4966 : }
3309 :
3310 :
3311 : /*
3312 : * Fetch tuple into "oldslot", dealing with locking and EPQ if necessary
3313 : */
3314 : static bool
3315 12676 : GetTupleForTrigger(EState *estate,
3316 : EPQState *epqstate,
3317 : ResultRelInfo *relinfo,
3318 : ItemPointer tid,
3319 : LockTupleMode lockmode,
3320 : TupleTableSlot *oldslot,
3321 : bool do_epq_recheck,
3322 : TupleTableSlot **epqslot,
3323 : TM_Result *tmresultp,
3324 : TM_FailureData *tmfdp)
3325 : {
3326 12676 : Relation relation = relinfo->ri_RelationDesc;
3327 :
3328 12676 : if (epqslot != NULL)
3329 : {
3330 : TM_Result test;
3331 : TM_FailureData tmfd;
3332 2858 : int lockflags = 0;
3333 :
3334 2858 : *epqslot = NULL;
3335 :
3336 : /* caller must pass an epqstate if EvalPlanQual is possible */
3337 : Assert(epqstate != NULL);
3338 :
3339 : /*
3340 : * lock tuple for update
3341 : */
3342 2858 : if (!IsolationUsesXactSnapshot())
3343 1994 : lockflags |= TUPLE_LOCK_FLAG_FIND_LAST_VERSION;
3344 2858 : test = table_tuple_lock(relation, tid, estate->es_snapshot, oldslot,
3345 : estate->es_output_cid,
3346 : lockmode, LockWaitBlock,
3347 : lockflags,
3348 : &tmfd);
3349 :
3350 : /* Let the caller know about the status of this operation */
3351 2854 : if (tmresultp)
3352 216 : *tmresultp = test;
3353 2854 : if (tmfdp)
3354 2848 : *tmfdp = tmfd;
3355 :
3356 2854 : switch (test)
3357 : {
3358 6 : case TM_SelfModified:
3359 :
3360 : /*
3361 : * The target tuple was already updated or deleted by the
3362 : * current command, or by a later command in the current
3363 : * transaction. We ignore the tuple in the former case, and
3364 : * throw error in the latter case, for the same reasons
3365 : * enumerated in ExecUpdate and ExecDelete in
3366 : * nodeModifyTable.c.
3367 : */
3368 6 : if (tmfd.cmax != estate->es_output_cid)
3369 6 : ereport(ERROR,
3370 : (errcode(ERRCODE_TRIGGERED_DATA_CHANGE_VIOLATION),
3371 : errmsg("tuple to be updated was already modified by an operation triggered by the current command"),
3372 : errhint("Consider using an AFTER trigger instead of a BEFORE trigger to propagate changes to other rows.")));
3373 :
3374 : /* treat it as deleted; do not process */
3375 32 : return false;
3376 :
3377 2830 : case TM_Ok:
3378 2830 : if (tmfd.traversed)
3379 : {
3380 : /*
3381 : * Recheck the tuple using EPQ, if requested. Otherwise,
3382 : * just return that it was concurrently updated.
3383 : */
3384 26 : if (do_epq_recheck)
3385 : {
3386 12 : *epqslot = EvalPlanQual(epqstate,
3387 : relation,
3388 : relinfo->ri_RangeTableIndex,
3389 : oldslot);
3390 :
3391 : /*
3392 : * If PlanQual failed for updated tuple - we must not
3393 : * process this tuple!
3394 : */
3395 12 : if (TupIsNull(*epqslot))
3396 : {
3397 4 : *epqslot = NULL;
3398 4 : return false;
3399 : }
3400 : }
3401 : else
3402 : {
3403 14 : if (tmresultp)
3404 14 : *tmresultp = TM_Updated;
3405 14 : return false;
3406 : }
3407 : }
3408 2812 : break;
3409 :
3410 2 : case TM_Updated:
3411 2 : if (IsolationUsesXactSnapshot())
3412 2 : ereport(ERROR,
3413 : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3414 : errmsg("could not serialize access due to concurrent update")));
3415 0 : elog(ERROR, "unexpected table_tuple_lock status: %u", test);
3416 : break;
3417 :
3418 16 : case TM_Deleted:
3419 16 : if (IsolationUsesXactSnapshot())
3420 2 : ereport(ERROR,
3421 : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3422 : errmsg("could not serialize access due to concurrent delete")));
3423 : /* tuple was deleted */
3424 14 : return false;
3425 :
3426 0 : case TM_Invisible:
3427 0 : elog(ERROR, "attempted to lock invisible tuple");
3428 : break;
3429 :
3430 0 : default:
3431 0 : elog(ERROR, "unrecognized table_tuple_lock status: %u", test);
3432 : return false; /* keep compiler quiet */
3433 : }
3434 : }
3435 : else
3436 : {
3437 : /*
3438 : * We expect the tuple to be present, thus very simple error handling
3439 : * suffices.
3440 : */
3441 9818 : if (!table_tuple_fetch_row_version(relation, tid, SnapshotAny,
3442 : oldslot))
3443 0 : elog(ERROR, "failed to fetch tuple for trigger");
3444 : }
3445 :
3446 12630 : return true;
3447 : }
3448 :
3449 : /*
3450 : * Is trigger enabled to fire?
3451 : */
3452 : static bool
3453 24460 : TriggerEnabled(EState *estate, ResultRelInfo *relinfo,
3454 : Trigger *trigger, TriggerEvent event,
3455 : Bitmapset *modifiedCols,
3456 : TupleTableSlot *oldslot, TupleTableSlot *newslot)
3457 : {
3458 : /* Check replication-role-dependent enable state */
3459 24460 : if (SessionReplicationRole == SESSION_REPLICATION_ROLE_REPLICA)
3460 : {
3461 128 : if (trigger->tgenabled == TRIGGER_FIRES_ON_ORIGIN ||
3462 80 : trigger->tgenabled == TRIGGER_DISABLED)
3463 84 : return false;
3464 : }
3465 : else /* ORIGIN or LOCAL role */
3466 : {
3467 24332 : if (trigger->tgenabled == TRIGGER_FIRES_ON_REPLICA ||
3468 24330 : trigger->tgenabled == TRIGGER_DISABLED)
3469 158 : return false;
3470 : }
3471 :
3472 : /*
3473 : * Check for column-specific trigger (only possible for UPDATE, and in
3474 : * fact we *must* ignore tgattr for other event types)
3475 : */
3476 24218 : if (trigger->tgnattr > 0 && TRIGGER_FIRED_BY_UPDATE(event))
3477 : {
3478 : int i;
3479 : bool modified;
3480 :
3481 430 : modified = false;
3482 562 : for (i = 0; i < trigger->tgnattr; i++)
3483 : {
3484 478 : if (bms_is_member(trigger->tgattr[i] - FirstLowInvalidHeapAttributeNumber,
3485 : modifiedCols))
3486 : {
3487 346 : modified = true;
3488 346 : break;
3489 : }
3490 : }
3491 430 : if (!modified)
3492 84 : return false;
3493 : }
3494 :
3495 : /* Check for WHEN clause */
3496 24134 : if (trigger->tgqual)
3497 : {
3498 : ExprState **predicate;
3499 : ExprContext *econtext;
3500 : MemoryContext oldContext;
3501 : int i;
3502 :
3503 : Assert(estate != NULL);
3504 :
3505 : /*
3506 : * trigger is an element of relinfo->ri_TrigDesc->triggers[]; find the
3507 : * matching element of relinfo->ri_TrigWhenExprs[]
3508 : */
3509 570 : i = trigger - relinfo->ri_TrigDesc->triggers;
3510 570 : predicate = &relinfo->ri_TrigWhenExprs[i];
3511 :
3512 : /*
3513 : * If first time through for this WHEN expression, build expression
3514 : * nodetrees for it. Keep them in the per-query memory context so
3515 : * they'll survive throughout the query.
3516 : */
3517 570 : if (*predicate == NULL)
3518 : {
3519 : Node *tgqual;
3520 :
3521 302 : oldContext = MemoryContextSwitchTo(estate->es_query_cxt);
3522 302 : tgqual = stringToNode(trigger->tgqual);
3523 302 : tgqual = expand_generated_columns_in_expr(tgqual, relinfo->ri_RelationDesc, PRS2_OLD_VARNO);
3524 302 : tgqual = expand_generated_columns_in_expr(tgqual, relinfo->ri_RelationDesc, PRS2_NEW_VARNO);
3525 : /* Change references to OLD and NEW to INNER_VAR and OUTER_VAR */
3526 302 : ChangeVarNodes(tgqual, PRS2_OLD_VARNO, INNER_VAR, 0);
3527 302 : ChangeVarNodes(tgqual, PRS2_NEW_VARNO, OUTER_VAR, 0);
3528 : /* ExecPrepareQual wants implicit-AND form */
3529 302 : tgqual = (Node *) make_ands_implicit((Expr *) tgqual);
3530 302 : *predicate = ExecPrepareQual((List *) tgqual, estate);
3531 302 : MemoryContextSwitchTo(oldContext);
3532 : }
3533 :
3534 : /*
3535 : * We will use the EState's per-tuple context for evaluating WHEN
3536 : * expressions (creating it if it's not already there).
3537 : */
3538 570 : econtext = GetPerTupleExprContext(estate);
3539 :
3540 : /*
3541 : * Finally evaluate the expression, making the old and/or new tuples
3542 : * available as INNER_VAR/OUTER_VAR respectively.
3543 : */
3544 570 : econtext->ecxt_innertuple = oldslot;
3545 570 : econtext->ecxt_outertuple = newslot;
3546 570 : if (!ExecQual(*predicate, econtext))
3547 318 : return false;
3548 : }
3549 :
3550 23816 : return true;
3551 : }
3552 :
3553 :
3554 : /* ----------
3555 : * After-trigger stuff
3556 : *
3557 : * The AfterTriggersData struct holds data about pending AFTER trigger events
3558 : * during the current transaction tree. (BEFORE triggers are fired
3559 : * immediately so we don't need any persistent state about them.) The struct
3560 : * and most of its subsidiary data are kept in TopTransactionContext; however
3561 : * some data that can be discarded sooner appears in the CurTransactionContext
3562 : * of the relevant subtransaction. Also, the individual event records are
3563 : * kept in a separate sub-context of TopTransactionContext. This is done
3564 : * mainly so that it's easy to tell from a memory context dump how much space
3565 : * is being eaten by trigger events.
3566 : *
3567 : * Because the list of pending events can grow large, we go to some
3568 : * considerable effort to minimize per-event memory consumption. The event
3569 : * records are grouped into chunks and common data for similar events in the
3570 : * same chunk is only stored once.
3571 : *
3572 : * XXX We need to be able to save the per-event data in a file if it grows too
3573 : * large.
3574 : * ----------
3575 : */
3576 :
3577 : /* Per-trigger SET CONSTRAINT status */
3578 : typedef struct SetConstraintTriggerData
3579 : {
3580 : Oid sct_tgoid;
3581 : bool sct_tgisdeferred;
3582 : } SetConstraintTriggerData;
3583 :
3584 : typedef struct SetConstraintTriggerData *SetConstraintTrigger;
3585 :
3586 : /*
3587 : * SET CONSTRAINT intra-transaction status.
3588 : *
3589 : * We make this a single palloc'd object so it can be copied and freed easily.
3590 : *
3591 : * all_isset and all_isdeferred are used to keep track
3592 : * of SET CONSTRAINTS ALL {DEFERRED, IMMEDIATE}.
3593 : *
3594 : * trigstates[] stores per-trigger tgisdeferred settings.
3595 : */
3596 : typedef struct SetConstraintStateData
3597 : {
3598 : bool all_isset;
3599 : bool all_isdeferred;
3600 : int numstates; /* number of trigstates[] entries in use */
3601 : int numalloc; /* allocated size of trigstates[] */
3602 : SetConstraintTriggerData trigstates[FLEXIBLE_ARRAY_MEMBER];
3603 : } SetConstraintStateData;
3604 :
3605 : typedef SetConstraintStateData *SetConstraintState;
3606 :
3607 :
3608 : /*
3609 : * Per-trigger-event data
3610 : *
3611 : * The actual per-event data, AfterTriggerEventData, includes DONE/IN_PROGRESS
3612 : * status bits, up to two tuple CTIDs, and optionally two OIDs of partitions.
3613 : * Each event record also has an associated AfterTriggerSharedData that is
3614 : * shared across all instances of similar events within a "chunk".
3615 : *
3616 : * For row-level triggers, we arrange not to waste storage on unneeded ctid
3617 : * fields. Updates of regular tables use two; inserts and deletes of regular
3618 : * tables use one; foreign tables always use zero and save the tuple(s) to a
3619 : * tuplestore. AFTER_TRIGGER_FDW_FETCH directs AfterTriggerExecute() to
3620 : * retrieve a fresh tuple or pair of tuples from that tuplestore, while
3621 : * AFTER_TRIGGER_FDW_REUSE directs it to use the most-recently-retrieved
3622 : * tuple(s). This permits storing tuples once regardless of the number of
3623 : * row-level triggers on a foreign table.
3624 : *
3625 : * When updates on partitioned tables cause rows to move between partitions,
3626 : * the OIDs of both partitions are stored too, so that the tuples can be
3627 : * fetched; such entries are marked AFTER_TRIGGER_CP_UPDATE (for "cross-
3628 : * partition update").
3629 : *
3630 : * Note that we need triggers on foreign tables to be fired in exactly the
3631 : * order they were queued, so that the tuples come out of the tuplestore in
3632 : * the right order. To ensure that, we forbid deferrable (constraint)
3633 : * triggers on foreign tables. This also ensures that such triggers do not
3634 : * get deferred into outer trigger query levels, meaning that it's okay to
3635 : * destroy the tuplestore at the end of the query level.
3636 : *
3637 : * Statement-level triggers always bear AFTER_TRIGGER_1CTID, though they
3638 : * require no ctid field. We lack the flag bit space to neatly represent that
3639 : * distinct case, and it seems unlikely to be worth much trouble.
3640 : *
3641 : * Note: ats_firing_id is initially zero and is set to something else when
3642 : * AFTER_TRIGGER_IN_PROGRESS is set. It indicates which trigger firing
3643 : * cycle the trigger will be fired in (or was fired in, if DONE is set).
3644 : * Although this is mutable state, we can keep it in AfterTriggerSharedData
3645 : * because all instances of the same type of event in a given event list will
3646 : * be fired at the same time, if they were queued between the same firing
3647 : * cycles. So we need only ensure that ats_firing_id is zero when attaching
3648 : * a new event to an existing AfterTriggerSharedData record.
3649 : */
3650 : typedef uint32 TriggerFlags;
3651 :
3652 : #define AFTER_TRIGGER_OFFSET 0x07FFFFFF /* must be low-order bits */
3653 : #define AFTER_TRIGGER_DONE 0x80000000
3654 : #define AFTER_TRIGGER_IN_PROGRESS 0x40000000
3655 : /* bits describing the size and tuple sources of this event */
3656 : #define AFTER_TRIGGER_FDW_REUSE 0x00000000
3657 : #define AFTER_TRIGGER_FDW_FETCH 0x20000000
3658 : #define AFTER_TRIGGER_1CTID 0x10000000
3659 : #define AFTER_TRIGGER_2CTID 0x30000000
3660 : #define AFTER_TRIGGER_CP_UPDATE 0x08000000
3661 : #define AFTER_TRIGGER_TUP_BITS 0x38000000
3662 : typedef struct AfterTriggerSharedData *AfterTriggerShared;
3663 :
3664 : typedef struct AfterTriggerSharedData
3665 : {
3666 : TriggerEvent ats_event; /* event type indicator, see trigger.h */
3667 : Oid ats_tgoid; /* the trigger's ID */
3668 : Oid ats_relid; /* the relation it's on */
3669 : Oid ats_rolid; /* role to execute the trigger */
3670 : CommandId ats_firing_id; /* ID for firing cycle */
3671 : struct AfterTriggersTableData *ats_table; /* transition table access */
3672 : Bitmapset *ats_modifiedcols; /* modified columns */
3673 : } AfterTriggerSharedData;
3674 :
3675 : typedef struct AfterTriggerEventData *AfterTriggerEvent;
3676 :
3677 : typedef struct AfterTriggerEventData
3678 : {
3679 : TriggerFlags ate_flags; /* status bits and offset to shared data */
3680 : ItemPointerData ate_ctid1; /* inserted, deleted, or old updated tuple */
3681 : ItemPointerData ate_ctid2; /* new updated tuple */
3682 :
3683 : /*
3684 : * During a cross-partition update of a partitioned table, we also store
3685 : * the OIDs of source and destination partitions that are needed to fetch
3686 : * the old (ctid1) and the new tuple (ctid2) from, respectively.
3687 : */
3688 : Oid ate_src_part;
3689 : Oid ate_dst_part;
3690 : } AfterTriggerEventData;
3691 :
3692 : /* AfterTriggerEventData, minus ate_src_part, ate_dst_part */
3693 : typedef struct AfterTriggerEventDataNoOids
3694 : {
3695 : TriggerFlags ate_flags;
3696 : ItemPointerData ate_ctid1;
3697 : ItemPointerData ate_ctid2;
3698 : } AfterTriggerEventDataNoOids;
3699 :
3700 : /* AfterTriggerEventData, minus ate_*_part and ate_ctid2 */
3701 : typedef struct AfterTriggerEventDataOneCtid
3702 : {
3703 : TriggerFlags ate_flags; /* status bits and offset to shared data */
3704 : ItemPointerData ate_ctid1; /* inserted, deleted, or old updated tuple */
3705 : } AfterTriggerEventDataOneCtid;
3706 :
3707 : /* AfterTriggerEventData, minus ate_*_part, ate_ctid1 and ate_ctid2 */
3708 : typedef struct AfterTriggerEventDataZeroCtids
3709 : {
3710 : TriggerFlags ate_flags; /* status bits and offset to shared data */
3711 : } AfterTriggerEventDataZeroCtids;
3712 :
3713 : #define SizeofTriggerEvent(evt) \
3714 : (((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_CP_UPDATE ? \
3715 : sizeof(AfterTriggerEventData) : \
3716 : (((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_2CTID ? \
3717 : sizeof(AfterTriggerEventDataNoOids) : \
3718 : (((evt)->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_1CTID ? \
3719 : sizeof(AfterTriggerEventDataOneCtid) : \
3720 : sizeof(AfterTriggerEventDataZeroCtids))))
3721 :
3722 : #define GetTriggerSharedData(evt) \
3723 : ((AfterTriggerShared) ((char *) (evt) + ((evt)->ate_flags & AFTER_TRIGGER_OFFSET)))
3724 :
3725 : /*
3726 : * To avoid palloc overhead, we keep trigger events in arrays in successively-
3727 : * larger chunks (a slightly more sophisticated version of an expansible
3728 : * array). The space between CHUNK_DATA_START and freeptr is occupied by
3729 : * AfterTriggerEventData records; the space between endfree and endptr is
3730 : * occupied by AfterTriggerSharedData records.
3731 : */
3732 : typedef struct AfterTriggerEventChunk
3733 : {
3734 : struct AfterTriggerEventChunk *next; /* list link */
3735 : char *freeptr; /* start of free space in chunk */
3736 : char *endfree; /* end of free space in chunk */
3737 : char *endptr; /* end of chunk */
3738 : /* event data follows here */
3739 : } AfterTriggerEventChunk;
3740 :
3741 : #define CHUNK_DATA_START(cptr) ((char *) (cptr) + MAXALIGN(sizeof(AfterTriggerEventChunk)))
3742 :
3743 : /* A list of events */
3744 : typedef struct AfterTriggerEventList
3745 : {
3746 : AfterTriggerEventChunk *head;
3747 : AfterTriggerEventChunk *tail;
3748 : char *tailfree; /* freeptr of tail chunk */
3749 : } AfterTriggerEventList;
3750 :
3751 : /* Macros to help in iterating over a list of events */
3752 : #define for_each_chunk(cptr, evtlist) \
3753 : for (cptr = (evtlist).head; cptr != NULL; cptr = cptr->next)
3754 : #define for_each_event(eptr, cptr) \
3755 : for (eptr = (AfterTriggerEvent) CHUNK_DATA_START(cptr); \
3756 : (char *) eptr < (cptr)->freeptr; \
3757 : eptr = (AfterTriggerEvent) (((char *) eptr) + SizeofTriggerEvent(eptr)))
3758 : /* Use this if no special per-chunk processing is needed */
3759 : #define for_each_event_chunk(eptr, cptr, evtlist) \
3760 : for_each_chunk(cptr, evtlist) for_each_event(eptr, cptr)
3761 :
3762 : /* Macros for iterating from a start point that might not be list start */
3763 : #define for_each_chunk_from(cptr) \
3764 : for (; cptr != NULL; cptr = cptr->next)
3765 : #define for_each_event_from(eptr, cptr) \
3766 : for (; \
3767 : (char *) eptr < (cptr)->freeptr; \
3768 : eptr = (AfterTriggerEvent) (((char *) eptr) + SizeofTriggerEvent(eptr)))
3769 :
3770 :
3771 : /*
3772 : * All per-transaction data for the AFTER TRIGGERS module.
3773 : *
3774 : * AfterTriggersData has the following fields:
3775 : *
3776 : * firing_counter is incremented for each call of afterTriggerInvokeEvents.
3777 : * We mark firable events with the current firing cycle's ID so that we can
3778 : * tell which ones to work on. This ensures sane behavior if a trigger
3779 : * function chooses to do SET CONSTRAINTS: the inner SET CONSTRAINTS will
3780 : * only fire those events that weren't already scheduled for firing.
3781 : *
3782 : * state keeps track of the transaction-local effects of SET CONSTRAINTS.
3783 : * This is saved and restored across failed subtransactions.
3784 : *
3785 : * events is the current list of deferred events. This is global across
3786 : * all subtransactions of the current transaction. In a subtransaction
3787 : * abort, we know that the events added by the subtransaction are at the
3788 : * end of the list, so it is relatively easy to discard them. The event
3789 : * list chunks themselves are stored in event_cxt.
3790 : *
3791 : * query_depth is the current depth of nested AfterTriggerBeginQuery calls
3792 : * (-1 when the stack is empty).
3793 : *
3794 : * query_stack[query_depth] is the per-query-level data, including these fields:
3795 : *
3796 : * events is a list of AFTER trigger events queued by the current query.
3797 : * None of these are valid until the matching AfterTriggerEndQuery call
3798 : * occurs. At that point we fire immediate-mode triggers, and append any
3799 : * deferred events to the main events list.
3800 : *
3801 : * fdw_tuplestore is a tuplestore containing the foreign-table tuples
3802 : * needed by events queued by the current query. (Note: we use just one
3803 : * tuplestore even though more than one foreign table might be involved.
3804 : * This is okay because tuplestores don't really care what's in the tuples
3805 : * they store; but it's possible that someday it'd break.)
3806 : *
3807 : * tables is a List of AfterTriggersTableData structs for target tables
3808 : * of the current query (see below).
3809 : *
3810 : * maxquerydepth is just the allocated length of query_stack.
3811 : *
3812 : * trans_stack holds per-subtransaction data, including these fields:
3813 : *
3814 : * state is NULL or a pointer to a saved copy of the SET CONSTRAINTS
3815 : * state data. Each subtransaction level that modifies that state first
3816 : * saves a copy, which we use to restore the state if we abort.
3817 : *
3818 : * events is a copy of the events head/tail pointers,
3819 : * which we use to restore those values during subtransaction abort.
3820 : *
3821 : * query_depth is the subtransaction-start-time value of query_depth,
3822 : * which we similarly use to clean up at subtransaction abort.
3823 : *
3824 : * firing_counter is the subtransaction-start-time value of firing_counter.
3825 : * We use this to recognize which deferred triggers were fired (or marked
3826 : * for firing) within an aborted subtransaction.
3827 : *
3828 : * We use GetCurrentTransactionNestLevel() to determine the correct array
3829 : * index in trans_stack. maxtransdepth is the number of allocated entries in
3830 : * trans_stack. (By not keeping our own stack pointer, we can avoid trouble
3831 : * in cases where errors during subxact abort cause multiple invocations
3832 : * of AfterTriggerEndSubXact() at the same nesting depth.)
3833 : *
3834 : * We create an AfterTriggersTableData struct for each target table of the
3835 : * current query, and each operation mode (INSERT/UPDATE/DELETE), that has
3836 : * either transition tables or statement-level triggers. This is used to
3837 : * hold the relevant transition tables, as well as info tracking whether
3838 : * we already queued the statement triggers. (We use that info to prevent
3839 : * firing the same statement triggers more than once per statement, or really
3840 : * once per transition table set.) These structs, along with the transition
3841 : * table tuplestores, live in the (sub)transaction's CurTransactionContext.
3842 : * That's sufficient lifespan because we don't allow transition tables to be
3843 : * used by deferrable triggers, so they only need to survive until
3844 : * AfterTriggerEndQuery.
3845 : */
3846 : typedef struct AfterTriggersQueryData AfterTriggersQueryData;
3847 : typedef struct AfterTriggersTransData AfterTriggersTransData;
3848 : typedef struct AfterTriggersTableData AfterTriggersTableData;
3849 :
3850 : typedef struct AfterTriggersData
3851 : {
3852 : CommandId firing_counter; /* next firing ID to assign */
3853 : SetConstraintState state; /* the active S C state */
3854 : AfterTriggerEventList events; /* deferred-event list */
3855 : MemoryContext event_cxt; /* memory context for events, if any */
3856 :
3857 : /* per-query-level data: */
3858 : AfterTriggersQueryData *query_stack; /* array of structs shown below */
3859 : int query_depth; /* current index in above array */
3860 : int maxquerydepth; /* allocated len of above array */
3861 :
3862 : /* per-subtransaction-level data: */
3863 : AfterTriggersTransData *trans_stack; /* array of structs shown below */
3864 : int maxtransdepth; /* allocated len of above array */
3865 : } AfterTriggersData;
3866 :
3867 : struct AfterTriggersQueryData
3868 : {
3869 : AfterTriggerEventList events; /* events pending from this query */
3870 : Tuplestorestate *fdw_tuplestore; /* foreign tuples for said events */
3871 : List *tables; /* list of AfterTriggersTableData, see below */
3872 : };
3873 :
3874 : struct AfterTriggersTransData
3875 : {
3876 : /* these fields are just for resetting at subtrans abort: */
3877 : SetConstraintState state; /* saved S C state, or NULL if not yet saved */
3878 : AfterTriggerEventList events; /* saved list pointer */
3879 : int query_depth; /* saved query_depth */
3880 : CommandId firing_counter; /* saved firing_counter */
3881 : };
3882 :
3883 : struct AfterTriggersTableData
3884 : {
3885 : /* relid + cmdType form the lookup key for these structs: */
3886 : Oid relid; /* target table's OID */
3887 : CmdType cmdType; /* event type, CMD_INSERT/UPDATE/DELETE */
3888 : bool closed; /* true when no longer OK to add tuples */
3889 : bool before_trig_done; /* did we already queue BS triggers? */
3890 : bool after_trig_done; /* did we already queue AS triggers? */
3891 : AfterTriggerEventList after_trig_events; /* if so, saved list pointer */
3892 :
3893 : /*
3894 : * We maintain separate transition tables for UPDATE/INSERT/DELETE since
3895 : * MERGE can run all three actions in a single statement. Note that UPDATE
3896 : * needs both old and new transition tables whereas INSERT needs only new,
3897 : * and DELETE needs only old.
3898 : */
3899 :
3900 : /* "old" transition table for UPDATE, if any */
3901 : Tuplestorestate *old_upd_tuplestore;
3902 : /* "new" transition table for UPDATE, if any */
3903 : Tuplestorestate *new_upd_tuplestore;
3904 : /* "old" transition table for DELETE, if any */
3905 : Tuplestorestate *old_del_tuplestore;
3906 : /* "new" transition table for INSERT, if any */
3907 : Tuplestorestate *new_ins_tuplestore;
3908 :
3909 : TupleTableSlot *storeslot; /* for converting to tuplestore's format */
3910 : };
3911 :
3912 : static AfterTriggersData afterTriggers;
3913 :
3914 : static void AfterTriggerExecute(EState *estate,
3915 : AfterTriggerEvent event,
3916 : ResultRelInfo *relInfo,
3917 : ResultRelInfo *src_relInfo,
3918 : ResultRelInfo *dst_relInfo,
3919 : TriggerDesc *trigdesc,
3920 : FmgrInfo *finfo,
3921 : Instrumentation *instr,
3922 : MemoryContext per_tuple_context,
3923 : TupleTableSlot *trig_tuple_slot1,
3924 : TupleTableSlot *trig_tuple_slot2);
3925 : static AfterTriggersTableData *GetAfterTriggersTableData(Oid relid,
3926 : CmdType cmdType);
3927 : static TupleTableSlot *GetAfterTriggersStoreSlot(AfterTriggersTableData *table,
3928 : TupleDesc tupdesc);
3929 : static Tuplestorestate *GetAfterTriggersTransitionTable(int event,
3930 : TupleTableSlot *oldslot,
3931 : TupleTableSlot *newslot,
3932 : TransitionCaptureState *transition_capture);
3933 : static void TransitionTableAddTuple(EState *estate,
3934 : TransitionCaptureState *transition_capture,
3935 : ResultRelInfo *relinfo,
3936 : TupleTableSlot *slot,
3937 : TupleTableSlot *original_insert_tuple,
3938 : Tuplestorestate *tuplestore);
3939 : static void AfterTriggerFreeQuery(AfterTriggersQueryData *qs);
3940 : static SetConstraintState SetConstraintStateCreate(int numalloc);
3941 : static SetConstraintState SetConstraintStateCopy(SetConstraintState origstate);
3942 : static SetConstraintState SetConstraintStateAddItem(SetConstraintState state,
3943 : Oid tgoid, bool tgisdeferred);
3944 : static void cancel_prior_stmt_triggers(Oid relid, CmdType cmdType, int tgevent);
3945 :
3946 :
3947 : /*
3948 : * Get the FDW tuplestore for the current trigger query level, creating it
3949 : * if necessary.
3950 : */
3951 : static Tuplestorestate *
3952 100 : GetCurrentFDWTuplestore(void)
3953 : {
3954 : Tuplestorestate *ret;
3955 :
3956 100 : ret = afterTriggers.query_stack[afterTriggers.query_depth].fdw_tuplestore;
3957 100 : if (ret == NULL)
3958 : {
3959 : MemoryContext oldcxt;
3960 : ResourceOwner saveResourceOwner;
3961 :
3962 : /*
3963 : * Make the tuplestore valid until end of subtransaction. We really
3964 : * only need it until AfterTriggerEndQuery().
3965 : */
3966 36 : oldcxt = MemoryContextSwitchTo(CurTransactionContext);
3967 36 : saveResourceOwner = CurrentResourceOwner;
3968 36 : CurrentResourceOwner = CurTransactionResourceOwner;
3969 :
3970 36 : ret = tuplestore_begin_heap(false, false, work_mem);
3971 :
3972 36 : CurrentResourceOwner = saveResourceOwner;
3973 36 : MemoryContextSwitchTo(oldcxt);
3974 :
3975 36 : afterTriggers.query_stack[afterTriggers.query_depth].fdw_tuplestore = ret;
3976 : }
3977 :
3978 100 : return ret;
3979 : }
3980 :
3981 : /* ----------
3982 : * afterTriggerCheckState()
3983 : *
3984 : * Returns true if the trigger event is actually in state DEFERRED.
3985 : * ----------
3986 : */
3987 : static bool
3988 11858 : afterTriggerCheckState(AfterTriggerShared evtshared)
3989 : {
3990 11858 : Oid tgoid = evtshared->ats_tgoid;
3991 11858 : SetConstraintState state = afterTriggers.state;
3992 : int i;
3993 :
3994 : /*
3995 : * For not-deferrable triggers (i.e. normal AFTER ROW triggers and
3996 : * constraints declared NOT DEFERRABLE), the state is always false.
3997 : */
3998 11858 : if ((evtshared->ats_event & AFTER_TRIGGER_DEFERRABLE) == 0)
3999 11120 : return false;
4000 :
4001 : /*
4002 : * If constraint state exists, SET CONSTRAINTS might have been executed
4003 : * either for this trigger or for all triggers.
4004 : */
4005 738 : if (state != NULL)
4006 : {
4007 : /* Check for SET CONSTRAINTS for this specific trigger. */
4008 316 : for (i = 0; i < state->numstates; i++)
4009 : {
4010 250 : if (state->trigstates[i].sct_tgoid == tgoid)
4011 60 : return state->trigstates[i].sct_tgisdeferred;
4012 : }
4013 :
4014 : /* Check for SET CONSTRAINTS ALL. */
4015 66 : if (state->all_isset)
4016 54 : return state->all_isdeferred;
4017 : }
4018 :
4019 : /*
4020 : * Otherwise return the default state for the trigger.
4021 : */
4022 624 : return ((evtshared->ats_event & AFTER_TRIGGER_INITDEFERRED) != 0);
4023 : }
4024 :
4025 : /* ----------
4026 : * afterTriggerCopyBitmap()
4027 : *
4028 : * Copy bitmap into AfterTriggerEvents memory context, which is where the after
4029 : * trigger events are kept.
4030 : * ----------
4031 : */
4032 : static Bitmapset *
4033 10992 : afterTriggerCopyBitmap(Bitmapset *src)
4034 : {
4035 : Bitmapset *dst;
4036 : MemoryContext oldcxt;
4037 :
4038 10992 : if (src == NULL)
4039 7720 : return NULL;
4040 :
4041 3272 : oldcxt = MemoryContextSwitchTo(afterTriggers.event_cxt);
4042 :
4043 3272 : dst = bms_copy(src);
4044 :
4045 3272 : MemoryContextSwitchTo(oldcxt);
4046 :
4047 3272 : return dst;
4048 : }
4049 :
4050 : /* ----------
4051 : * afterTriggerAddEvent()
4052 : *
4053 : * Add a new trigger event to the specified queue.
4054 : * The passed-in event data is copied.
4055 : * ----------
4056 : */
4057 : static void
4058 12532 : afterTriggerAddEvent(AfterTriggerEventList *events,
4059 : AfterTriggerEvent event, AfterTriggerShared evtshared)
4060 : {
4061 12532 : Size eventsize = SizeofTriggerEvent(event);
4062 12532 : Size needed = eventsize + sizeof(AfterTriggerSharedData);
4063 : AfterTriggerEventChunk *chunk;
4064 : AfterTriggerShared newshared;
4065 : AfterTriggerEvent newevent;
4066 :
4067 : /*
4068 : * If empty list or not enough room in the tail chunk, make a new chunk.
4069 : * We assume here that a new shared record will always be needed.
4070 : */
4071 12532 : chunk = events->tail;
4072 12532 : if (chunk == NULL ||
4073 4718 : chunk->endfree - chunk->freeptr < needed)
4074 : {
4075 : Size chunksize;
4076 :
4077 : /* Create event context if we didn't already */
4078 7814 : if (afterTriggers.event_cxt == NULL)
4079 6580 : afterTriggers.event_cxt =
4080 6580 : AllocSetContextCreate(TopTransactionContext,
4081 : "AfterTriggerEvents",
4082 : ALLOCSET_DEFAULT_SIZES);
4083 :
4084 : /*
4085 : * Chunk size starts at 1KB and is allowed to increase up to 1MB.
4086 : * These numbers are fairly arbitrary, though there is a hard limit at
4087 : * AFTER_TRIGGER_OFFSET; else we couldn't link event records to their
4088 : * shared records using the available space in ate_flags. Another
4089 : * constraint is that if the chunk size gets too huge, the search loop
4090 : * below would get slow given a (not too common) usage pattern with
4091 : * many distinct event types in a chunk. Therefore, we double the
4092 : * preceding chunk size only if there weren't too many shared records
4093 : * in the preceding chunk; otherwise we halve it. This gives us some
4094 : * ability to adapt to the actual usage pattern of the current query
4095 : * while still having large chunk sizes in typical usage. All chunk
4096 : * sizes used should be MAXALIGN multiples, to ensure that the shared
4097 : * records will be aligned safely.
4098 : */
4099 : #define MIN_CHUNK_SIZE 1024
4100 : #define MAX_CHUNK_SIZE (1024*1024)
4101 :
4102 : #if MAX_CHUNK_SIZE > (AFTER_TRIGGER_OFFSET+1)
4103 : #error MAX_CHUNK_SIZE must not exceed AFTER_TRIGGER_OFFSET
4104 : #endif
4105 :
4106 7814 : if (chunk == NULL)
4107 7814 : chunksize = MIN_CHUNK_SIZE;
4108 : else
4109 : {
4110 : /* preceding chunk size... */
4111 0 : chunksize = chunk->endptr - (char *) chunk;
4112 : /* check number of shared records in preceding chunk */
4113 0 : if ((chunk->endptr - chunk->endfree) <=
4114 : (100 * sizeof(AfterTriggerSharedData)))
4115 0 : chunksize *= 2; /* okay, double it */
4116 : else
4117 0 : chunksize /= 2; /* too many shared records */
4118 0 : chunksize = Min(chunksize, MAX_CHUNK_SIZE);
4119 : }
4120 7814 : chunk = MemoryContextAlloc(afterTriggers.event_cxt, chunksize);
4121 7814 : chunk->next = NULL;
4122 7814 : chunk->freeptr = CHUNK_DATA_START(chunk);
4123 7814 : chunk->endptr = chunk->endfree = (char *) chunk + chunksize;
4124 : Assert(chunk->endfree - chunk->freeptr >= needed);
4125 :
4126 7814 : if (events->tail == NULL)
4127 : {
4128 : Assert(events->head == NULL);
4129 7814 : events->head = chunk;
4130 : }
4131 : else
4132 0 : events->tail->next = chunk;
4133 7814 : events->tail = chunk;
4134 : /* events->tailfree is now out of sync, but we'll fix it below */
4135 : }
4136 :
4137 : /*
4138 : * Try to locate a matching shared-data record already in the chunk. If
4139 : * none, make a new one. The search begins with the most recently added
4140 : * record, since newer ones are most likely to match.
4141 : */
4142 12532 : for (newshared = (AfterTriggerShared) chunk->endfree;
4143 17756 : (char *) newshared < chunk->endptr;
4144 5224 : newshared++)
4145 : {
4146 : /* compare fields roughly by probability of them being different */
4147 6764 : if (newshared->ats_tgoid == evtshared->ats_tgoid &&
4148 1758 : newshared->ats_event == evtshared->ats_event &&
4149 1752 : newshared->ats_firing_id == 0 &&
4150 1578 : newshared->ats_table == evtshared->ats_table &&
4151 1578 : newshared->ats_relid == evtshared->ats_relid &&
4152 3150 : newshared->ats_rolid == evtshared->ats_rolid &&
4153 1572 : bms_equal(newshared->ats_modifiedcols,
4154 1572 : evtshared->ats_modifiedcols))
4155 1540 : break;
4156 : }
4157 12532 : if ((char *) newshared >= chunk->endptr)
4158 : {
4159 10992 : newshared = ((AfterTriggerShared) chunk->endfree) - 1;
4160 10992 : *newshared = *evtshared;
4161 : /* now we must make a suitably-long-lived copy of the bitmap */
4162 10992 : newshared->ats_modifiedcols = afterTriggerCopyBitmap(evtshared->ats_modifiedcols);
4163 10992 : newshared->ats_firing_id = 0; /* just to be sure */
4164 10992 : chunk->endfree = (char *) newshared;
4165 : }
4166 :
4167 : /* Insert the data */
4168 12532 : newevent = (AfterTriggerEvent) chunk->freeptr;
4169 12532 : memcpy(newevent, event, eventsize);
4170 : /* ... and link the new event to its shared record */
4171 12532 : newevent->ate_flags &= ~AFTER_TRIGGER_OFFSET;
4172 12532 : newevent->ate_flags |= (char *) newshared - (char *) newevent;
4173 :
4174 12532 : chunk->freeptr += eventsize;
4175 12532 : events->tailfree = chunk->freeptr;
4176 12532 : }
4177 :
4178 : /* ----------
4179 : * afterTriggerFreeEventList()
4180 : *
4181 : * Free all the event storage in the given list.
4182 : * ----------
4183 : */
4184 : static void
4185 17060 : afterTriggerFreeEventList(AfterTriggerEventList *events)
4186 : {
4187 : AfterTriggerEventChunk *chunk;
4188 :
4189 23368 : while ((chunk = events->head) != NULL)
4190 : {
4191 6308 : events->head = chunk->next;
4192 6308 : pfree(chunk);
4193 : }
4194 17060 : events->tail = NULL;
4195 17060 : events->tailfree = NULL;
4196 17060 : }
4197 :
4198 : /* ----------
4199 : * afterTriggerRestoreEventList()
4200 : *
4201 : * Restore an event list to its prior length, removing all the events
4202 : * added since it had the value old_events.
4203 : * ----------
4204 : */
4205 : static void
4206 9346 : afterTriggerRestoreEventList(AfterTriggerEventList *events,
4207 : const AfterTriggerEventList *old_events)
4208 : {
4209 : AfterTriggerEventChunk *chunk;
4210 : AfterTriggerEventChunk *next_chunk;
4211 :
4212 9346 : if (old_events->tail == NULL)
4213 : {
4214 : /* restoring to a completely empty state, so free everything */
4215 9324 : afterTriggerFreeEventList(events);
4216 : }
4217 : else
4218 : {
4219 22 : *events = *old_events;
4220 : /* free any chunks after the last one we want to keep */
4221 22 : for (chunk = events->tail->next; chunk != NULL; chunk = next_chunk)
4222 : {
4223 0 : next_chunk = chunk->next;
4224 0 : pfree(chunk);
4225 : }
4226 : /* and clean up the tail chunk to be the right length */
4227 22 : events->tail->next = NULL;
4228 22 : events->tail->freeptr = events->tailfree;
4229 :
4230 : /*
4231 : * We don't make any effort to remove now-unused shared data records.
4232 : * They might still be useful, anyway.
4233 : */
4234 : }
4235 9346 : }
4236 :
4237 : /* ----------
4238 : * afterTriggerDeleteHeadEventChunk()
4239 : *
4240 : * Remove the first chunk of events from the query level's event list.
4241 : * Keep any event list pointers elsewhere in the query level's data
4242 : * structures in sync.
4243 : * ----------
4244 : */
4245 : static void
4246 0 : afterTriggerDeleteHeadEventChunk(AfterTriggersQueryData *qs)
4247 : {
4248 0 : AfterTriggerEventChunk *target = qs->events.head;
4249 : ListCell *lc;
4250 :
4251 : Assert(target && target->next);
4252 :
4253 : /*
4254 : * First, update any pointers in the per-table data, so that they won't be
4255 : * dangling. Resetting obsoleted pointers to NULL will make
4256 : * cancel_prior_stmt_triggers start from the list head, which is fine.
4257 : */
4258 0 : foreach(lc, qs->tables)
4259 : {
4260 0 : AfterTriggersTableData *table = (AfterTriggersTableData *) lfirst(lc);
4261 :
4262 0 : if (table->after_trig_done &&
4263 0 : table->after_trig_events.tail == target)
4264 : {
4265 0 : table->after_trig_events.head = NULL;
4266 0 : table->after_trig_events.tail = NULL;
4267 0 : table->after_trig_events.tailfree = NULL;
4268 : }
4269 : }
4270 :
4271 : /* Now we can flush the head chunk */
4272 0 : qs->events.head = target->next;
4273 0 : pfree(target);
4274 0 : }
4275 :
4276 :
4277 : /* ----------
4278 : * AfterTriggerExecute()
4279 : *
4280 : * Fetch the required tuples back from the heap and fire one
4281 : * single trigger function.
4282 : *
4283 : * Frequently, this will be fired many times in a row for triggers of
4284 : * a single relation. Therefore, we cache the open relation and provide
4285 : * fmgr lookup cache space at the caller level. (For triggers fired at
4286 : * the end of a query, we can even piggyback on the executor's state.)
4287 : *
4288 : * When fired for a cross-partition update of a partitioned table, the old
4289 : * tuple is fetched using 'src_relInfo' (the source leaf partition) and
4290 : * the new tuple using 'dst_relInfo' (the destination leaf partition), though
4291 : * both are converted into the root partitioned table's format before passing
4292 : * to the trigger function.
4293 : *
4294 : * event: event currently being fired.
4295 : * relInfo: result relation for event.
4296 : * src_relInfo: source partition of a cross-partition update
4297 : * dst_relInfo: its destination partition
4298 : * trigdesc: working copy of rel's trigger info.
4299 : * finfo: array of fmgr lookup cache entries (one per trigger in trigdesc).
4300 : * instr: array of EXPLAIN ANALYZE instrumentation nodes (one per trigger),
4301 : * or NULL if no instrumentation is wanted.
4302 : * per_tuple_context: memory context to call trigger function in.
4303 : * trig_tuple_slot1: scratch slot for tg_trigtuple (foreign tables only)
4304 : * trig_tuple_slot2: scratch slot for tg_newtuple (foreign tables only)
4305 : * ----------
4306 : */
4307 : static void
4308 11572 : AfterTriggerExecute(EState *estate,
4309 : AfterTriggerEvent event,
4310 : ResultRelInfo *relInfo,
4311 : ResultRelInfo *src_relInfo,
4312 : ResultRelInfo *dst_relInfo,
4313 : TriggerDesc *trigdesc,
4314 : FmgrInfo *finfo, Instrumentation *instr,
4315 : MemoryContext per_tuple_context,
4316 : TupleTableSlot *trig_tuple_slot1,
4317 : TupleTableSlot *trig_tuple_slot2)
4318 : {
4319 11572 : Relation rel = relInfo->ri_RelationDesc;
4320 11572 : Relation src_rel = src_relInfo->ri_RelationDesc;
4321 11572 : Relation dst_rel = dst_relInfo->ri_RelationDesc;
4322 11572 : AfterTriggerShared evtshared = GetTriggerSharedData(event);
4323 11572 : Oid tgoid = evtshared->ats_tgoid;
4324 11572 : TriggerData LocTriggerData = {0};
4325 : Oid save_rolid;
4326 : int save_sec_context;
4327 : HeapTuple rettuple;
4328 : int tgindx;
4329 11572 : bool should_free_trig = false;
4330 11572 : bool should_free_new = false;
4331 :
4332 : /*
4333 : * Locate trigger in trigdesc. It might not be present, and in fact the
4334 : * trigdesc could be NULL, if the trigger was dropped since the event was
4335 : * queued. In that case, silently do nothing.
4336 : */
4337 11572 : if (trigdesc == NULL)
4338 6 : return;
4339 25894 : for (tgindx = 0; tgindx < trigdesc->numtriggers; tgindx++)
4340 : {
4341 25894 : if (trigdesc->triggers[tgindx].tgoid == tgoid)
4342 : {
4343 11566 : LocTriggerData.tg_trigger = &(trigdesc->triggers[tgindx]);
4344 11566 : break;
4345 : }
4346 : }
4347 11566 : if (LocTriggerData.tg_trigger == NULL)
4348 0 : return;
4349 :
4350 : /*
4351 : * If doing EXPLAIN ANALYZE, start charging time to this trigger. We want
4352 : * to include time spent re-fetching tuples in the trigger cost.
4353 : */
4354 11566 : if (instr)
4355 0 : InstrStartNode(instr + tgindx);
4356 :
4357 : /*
4358 : * Fetch the required tuple(s).
4359 : */
4360 11566 : switch (event->ate_flags & AFTER_TRIGGER_TUP_BITS)
4361 : {
4362 50 : case AFTER_TRIGGER_FDW_FETCH:
4363 : {
4364 50 : Tuplestorestate *fdw_tuplestore = GetCurrentFDWTuplestore();
4365 :
4366 50 : if (!tuplestore_gettupleslot(fdw_tuplestore, true, false,
4367 : trig_tuple_slot1))
4368 0 : elog(ERROR, "failed to fetch tuple1 for AFTER trigger");
4369 :
4370 50 : if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) ==
4371 18 : TRIGGER_EVENT_UPDATE &&
4372 18 : !tuplestore_gettupleslot(fdw_tuplestore, true, false,
4373 : trig_tuple_slot2))
4374 0 : elog(ERROR, "failed to fetch tuple2 for AFTER trigger");
4375 : }
4376 : /* fall through */
4377 : case AFTER_TRIGGER_FDW_REUSE:
4378 :
4379 : /*
4380 : * Store tuple in the slot so that tg_trigtuple does not reference
4381 : * tuplestore memory. (It is formally possible for the trigger
4382 : * function to queue trigger events that add to the same
4383 : * tuplestore, which can push other tuples out of memory.) The
4384 : * distinction is academic, because we start with a minimal tuple
4385 : * that is stored as a heap tuple, constructed in different memory
4386 : * context, in the slot anyway.
4387 : */
4388 58 : LocTriggerData.tg_trigslot = trig_tuple_slot1;
4389 58 : LocTriggerData.tg_trigtuple =
4390 58 : ExecFetchSlotHeapTuple(trig_tuple_slot1, true, &should_free_trig);
4391 :
4392 58 : if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) ==
4393 : TRIGGER_EVENT_UPDATE)
4394 : {
4395 22 : LocTriggerData.tg_newslot = trig_tuple_slot2;
4396 22 : LocTriggerData.tg_newtuple =
4397 22 : ExecFetchSlotHeapTuple(trig_tuple_slot2, true, &should_free_new);
4398 : }
4399 : else
4400 : {
4401 36 : LocTriggerData.tg_newtuple = NULL;
4402 : }
4403 58 : break;
4404 :
4405 11508 : default:
4406 11508 : if (ItemPointerIsValid(&(event->ate_ctid1)))
4407 : {
4408 10468 : TupleTableSlot *src_slot = ExecGetTriggerOldSlot(estate,
4409 : src_relInfo);
4410 :
4411 10468 : if (!table_tuple_fetch_row_version(src_rel,
4412 : &(event->ate_ctid1),
4413 : SnapshotAny,
4414 : src_slot))
4415 0 : elog(ERROR, "failed to fetch tuple1 for AFTER trigger");
4416 :
4417 : /*
4418 : * Store the tuple fetched from the source partition into the
4419 : * target (root partitioned) table slot, converting if needed.
4420 : */
4421 10468 : if (src_relInfo != relInfo)
4422 : {
4423 144 : TupleConversionMap *map = ExecGetChildToRootMap(src_relInfo);
4424 :
4425 144 : LocTriggerData.tg_trigslot = ExecGetTriggerOldSlot(estate, relInfo);
4426 144 : if (map)
4427 : {
4428 36 : execute_attr_map_slot(map->attrMap,
4429 : src_slot,
4430 : LocTriggerData.tg_trigslot);
4431 : }
4432 : else
4433 108 : ExecCopySlot(LocTriggerData.tg_trigslot, src_slot);
4434 : }
4435 : else
4436 10324 : LocTriggerData.tg_trigslot = src_slot;
4437 10468 : LocTriggerData.tg_trigtuple =
4438 10468 : ExecFetchSlotHeapTuple(LocTriggerData.tg_trigslot, false, &should_free_trig);
4439 : }
4440 : else
4441 : {
4442 1040 : LocTriggerData.tg_trigtuple = NULL;
4443 : }
4444 :
4445 : /* don't touch ctid2 if not there */
4446 11508 : if (((event->ate_flags & AFTER_TRIGGER_TUP_BITS) == AFTER_TRIGGER_2CTID ||
4447 11652 : (event->ate_flags & AFTER_TRIGGER_CP_UPDATE)) &&
4448 3086 : ItemPointerIsValid(&(event->ate_ctid2)))
4449 3086 : {
4450 3086 : TupleTableSlot *dst_slot = ExecGetTriggerNewSlot(estate,
4451 : dst_relInfo);
4452 :
4453 3086 : if (!table_tuple_fetch_row_version(dst_rel,
4454 : &(event->ate_ctid2),
4455 : SnapshotAny,
4456 : dst_slot))
4457 0 : elog(ERROR, "failed to fetch tuple2 for AFTER trigger");
4458 :
4459 : /*
4460 : * Store the tuple fetched from the destination partition into
4461 : * the target (root partitioned) table slot, converting if
4462 : * needed.
4463 : */
4464 3086 : if (dst_relInfo != relInfo)
4465 : {
4466 144 : TupleConversionMap *map = ExecGetChildToRootMap(dst_relInfo);
4467 :
4468 144 : LocTriggerData.tg_newslot = ExecGetTriggerNewSlot(estate, relInfo);
4469 144 : if (map)
4470 : {
4471 36 : execute_attr_map_slot(map->attrMap,
4472 : dst_slot,
4473 : LocTriggerData.tg_newslot);
4474 : }
4475 : else
4476 108 : ExecCopySlot(LocTriggerData.tg_newslot, dst_slot);
4477 : }
4478 : else
4479 2942 : LocTriggerData.tg_newslot = dst_slot;
4480 3086 : LocTriggerData.tg_newtuple =
4481 3086 : ExecFetchSlotHeapTuple(LocTriggerData.tg_newslot, false, &should_free_new);
4482 : }
4483 : else
4484 : {
4485 8422 : LocTriggerData.tg_newtuple = NULL;
4486 : }
4487 : }
4488 :
4489 : /*
4490 : * Set up the tuplestore information to let the trigger have access to
4491 : * transition tables. When we first make a transition table available to
4492 : * a trigger, mark it "closed" so that it cannot change anymore. If any
4493 : * additional events of the same type get queued in the current trigger
4494 : * query level, they'll go into new transition tables.
4495 : */
4496 11566 : LocTriggerData.tg_oldtable = LocTriggerData.tg_newtable = NULL;
4497 11566 : if (evtshared->ats_table)
4498 : {
4499 564 : if (LocTriggerData.tg_trigger->tgoldtable)
4500 : {
4501 312 : if (TRIGGER_FIRED_BY_UPDATE(evtshared->ats_event))
4502 162 : LocTriggerData.tg_oldtable = evtshared->ats_table->old_upd_tuplestore;
4503 : else
4504 150 : LocTriggerData.tg_oldtable = evtshared->ats_table->old_del_tuplestore;
4505 312 : evtshared->ats_table->closed = true;
4506 : }
4507 :
4508 564 : if (LocTriggerData.tg_trigger->tgnewtable)
4509 : {
4510 402 : if (TRIGGER_FIRED_BY_INSERT(evtshared->ats_event))
4511 222 : LocTriggerData.tg_newtable = evtshared->ats_table->new_ins_tuplestore;
4512 : else
4513 180 : LocTriggerData.tg_newtable = evtshared->ats_table->new_upd_tuplestore;
4514 402 : evtshared->ats_table->closed = true;
4515 : }
4516 : }
4517 :
4518 : /*
4519 : * Setup the remaining trigger information
4520 : */
4521 11566 : LocTriggerData.type = T_TriggerData;
4522 11566 : LocTriggerData.tg_event =
4523 11566 : evtshared->ats_event & (TRIGGER_EVENT_OPMASK | TRIGGER_EVENT_ROW);
4524 11566 : LocTriggerData.tg_relation = rel;
4525 11566 : if (TRIGGER_FOR_UPDATE(LocTriggerData.tg_trigger->tgtype))
4526 5436 : LocTriggerData.tg_updatedcols = evtshared->ats_modifiedcols;
4527 :
4528 11566 : MemoryContextReset(per_tuple_context);
4529 :
4530 : /*
4531 : * If necessary, become the role that was active when the trigger got
4532 : * queued. Note that the role might have been dropped since the trigger
4533 : * was queued, but if that is a problem, we will get an error later.
4534 : * Checking here would still leave a race condition.
4535 : */
4536 11566 : GetUserIdAndSecContext(&save_rolid, &save_sec_context);
4537 11566 : if (save_rolid != evtshared->ats_rolid)
4538 24 : SetUserIdAndSecContext(evtshared->ats_rolid,
4539 : save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
4540 :
4541 : /*
4542 : * Call the trigger and throw away any possibly returned updated tuple.
4543 : * (Don't let ExecCallTriggerFunc measure EXPLAIN time.)
4544 : */
4545 11566 : rettuple = ExecCallTriggerFunc(&LocTriggerData,
4546 : tgindx,
4547 : finfo,
4548 : NULL,
4549 : per_tuple_context);
4550 10308 : if (rettuple != NULL &&
4551 3416 : rettuple != LocTriggerData.tg_trigtuple &&
4552 1440 : rettuple != LocTriggerData.tg_newtuple)
4553 0 : heap_freetuple(rettuple);
4554 :
4555 : /* Restore the current role if necessary */
4556 10308 : if (save_rolid != evtshared->ats_rolid)
4557 18 : SetUserIdAndSecContext(save_rolid, save_sec_context);
4558 :
4559 : /*
4560 : * Release resources
4561 : */
4562 10308 : if (should_free_trig)
4563 172 : heap_freetuple(LocTriggerData.tg_trigtuple);
4564 10308 : if (should_free_new)
4565 136 : heap_freetuple(LocTriggerData.tg_newtuple);
4566 :
4567 : /* don't clear slots' contents if foreign table */
4568 10308 : if (trig_tuple_slot1 == NULL)
4569 : {
4570 10238 : if (LocTriggerData.tg_trigslot)
4571 9258 : ExecClearTuple(LocTriggerData.tg_trigslot);
4572 10238 : if (LocTriggerData.tg_newslot)
4573 2764 : ExecClearTuple(LocTriggerData.tg_newslot);
4574 : }
4575 :
4576 : /*
4577 : * If doing EXPLAIN ANALYZE, stop charging time to this trigger, and count
4578 : * one "tuple returned" (really the number of firings).
4579 : */
4580 10308 : if (instr)
4581 0 : InstrStopNode(instr + tgindx, 1);
4582 : }
4583 :
4584 :
4585 : /*
4586 : * afterTriggerMarkEvents()
4587 : *
4588 : * Scan the given event list for not yet invoked events. Mark the ones
4589 : * that can be invoked now with the current firing ID.
4590 : *
4591 : * If move_list isn't NULL, events that are not to be invoked now are
4592 : * transferred to move_list.
4593 : *
4594 : * When immediate_only is true, do not invoke currently-deferred triggers.
4595 : * (This will be false only at main transaction exit.)
4596 : *
4597 : * Returns true if any invokable events were found.
4598 : */
4599 : static bool
4600 1072028 : afterTriggerMarkEvents(AfterTriggerEventList *events,
4601 : AfterTriggerEventList *move_list,
4602 : bool immediate_only)
4603 : {
4604 1072028 : bool found = false;
4605 1072028 : bool deferred_found = false;
4606 : AfterTriggerEvent event;
4607 : AfterTriggerEventChunk *chunk;
4608 :
4609 1093282 : for_each_event_chunk(event, chunk, *events)
4610 : {
4611 13214 : AfterTriggerShared evtshared = GetTriggerSharedData(event);
4612 13214 : bool defer_it = false;
4613 :
4614 13214 : if (!(event->ate_flags &
4615 : (AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS)))
4616 : {
4617 : /*
4618 : * This trigger hasn't been called or scheduled yet. Check if we
4619 : * should call it now.
4620 : */
4621 12380 : if (immediate_only && afterTriggerCheckState(evtshared))
4622 : {
4623 618 : defer_it = true;
4624 : }
4625 : else
4626 : {
4627 : /*
4628 : * Mark it as to be fired in this firing cycle.
4629 : */
4630 11762 : evtshared->ats_firing_id = afterTriggers.firing_counter;
4631 11762 : event->ate_flags |= AFTER_TRIGGER_IN_PROGRESS;
4632 11762 : found = true;
4633 : }
4634 : }
4635 :
4636 : /*
4637 : * If it's deferred, move it to move_list, if requested.
4638 : */
4639 13214 : if (defer_it && move_list != NULL)
4640 : {
4641 618 : deferred_found = true;
4642 : /* add it to move_list */
4643 618 : afterTriggerAddEvent(move_list, event, evtshared);
4644 : /* mark original copy "done" so we don't do it again */
4645 618 : event->ate_flags |= AFTER_TRIGGER_DONE;
4646 : }
4647 : }
4648 :
4649 : /*
4650 : * We could allow deferred triggers if, before the end of the
4651 : * security-restricted operation, we were to verify that a SET CONSTRAINTS
4652 : * ... IMMEDIATE has fired all such triggers. For now, don't bother.
4653 : */
4654 1072028 : if (deferred_found && InSecurityRestrictedOperation())
4655 12 : ereport(ERROR,
4656 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
4657 : errmsg("cannot fire deferred trigger within security-restricted operation")));
4658 :
4659 1072016 : return found;
4660 : }
4661 :
4662 : /*
4663 : * afterTriggerInvokeEvents()
4664 : *
4665 : * Scan the given event list for events that are marked as to be fired
4666 : * in the current firing cycle, and fire them.
4667 : *
4668 : * If estate isn't NULL, we use its result relation info to avoid repeated
4669 : * openings and closing of trigger target relations. If it is NULL, we
4670 : * make one locally to cache the info in case there are multiple trigger
4671 : * events per rel.
4672 : *
4673 : * When delete_ok is true, it's safe to delete fully-processed events.
4674 : * (We are not very tense about that: we simply reset a chunk to be empty
4675 : * if all its events got fired. The objective here is just to avoid useless
4676 : * rescanning of events when a trigger queues new events during transaction
4677 : * end, so it's not necessary to worry much about the case where only
4678 : * some events are fired.)
4679 : *
4680 : * Returns true if no unfired events remain in the list (this allows us
4681 : * to avoid repeating afterTriggerMarkEvents).
4682 : */
4683 : static bool
4684 7572 : afterTriggerInvokeEvents(AfterTriggerEventList *events,
4685 : CommandId firing_id,
4686 : EState *estate,
4687 : bool delete_ok)
4688 : {
4689 7572 : bool all_fired = true;
4690 : AfterTriggerEventChunk *chunk;
4691 : MemoryContext per_tuple_context;
4692 7572 : bool local_estate = false;
4693 7572 : ResultRelInfo *rInfo = NULL;
4694 7572 : Relation rel = NULL;
4695 7572 : TriggerDesc *trigdesc = NULL;
4696 7572 : FmgrInfo *finfo = NULL;
4697 7572 : Instrumentation *instr = NULL;
4698 7572 : TupleTableSlot *slot1 = NULL,
4699 7572 : *slot2 = NULL;
4700 :
4701 : /* Make a local EState if need be */
4702 7572 : if (estate == NULL)
4703 : {
4704 362 : estate = CreateExecutorState();
4705 362 : local_estate = true;
4706 : }
4707 :
4708 : /* Make a per-tuple memory context for trigger function calls */
4709 : per_tuple_context =
4710 7572 : AllocSetContextCreate(CurrentMemoryContext,
4711 : "AfterTriggerTupleContext",
4712 : ALLOCSET_DEFAULT_SIZES);
4713 :
4714 13886 : for_each_chunk(chunk, *events)
4715 : {
4716 : AfterTriggerEvent event;
4717 7572 : bool all_fired_in_chunk = true;
4718 :
4719 19356 : for_each_event(event, chunk)
4720 : {
4721 13042 : AfterTriggerShared evtshared = GetTriggerSharedData(event);
4722 :
4723 : /*
4724 : * Is it one for me to fire?
4725 : */
4726 13042 : if ((event->ate_flags & AFTER_TRIGGER_IN_PROGRESS) &&
4727 11572 : evtshared->ats_firing_id == firing_id)
4728 10314 : {
4729 : ResultRelInfo *src_rInfo,
4730 : *dst_rInfo;
4731 :
4732 : /*
4733 : * So let's fire it... but first, find the correct relation if
4734 : * this is not the same relation as before.
4735 : */
4736 11572 : if (rel == NULL || RelationGetRelid(rel) != evtshared->ats_relid)
4737 : {
4738 7874 : rInfo = ExecGetTriggerResultRel(estate, evtshared->ats_relid,
4739 : NULL);
4740 7874 : rel = rInfo->ri_RelationDesc;
4741 : /* Catch calls with insufficient relcache refcounting */
4742 : Assert(!RelationHasReferenceCountZero(rel));
4743 7874 : trigdesc = rInfo->ri_TrigDesc;
4744 : /* caution: trigdesc could be NULL here */
4745 7874 : finfo = rInfo->ri_TrigFunctions;
4746 7874 : instr = rInfo->ri_TrigInstrument;
4747 7874 : if (slot1 != NULL)
4748 : {
4749 0 : ExecDropSingleTupleTableSlot(slot1);
4750 0 : ExecDropSingleTupleTableSlot(slot2);
4751 0 : slot1 = slot2 = NULL;
4752 : }
4753 7874 : if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
4754 : {
4755 38 : slot1 = MakeSingleTupleTableSlot(rel->rd_att,
4756 : &TTSOpsMinimalTuple);
4757 38 : slot2 = MakeSingleTupleTableSlot(rel->rd_att,
4758 : &TTSOpsMinimalTuple);
4759 : }
4760 : }
4761 :
4762 : /*
4763 : * Look up source and destination partition result rels of a
4764 : * cross-partition update event.
4765 : */
4766 11572 : if ((event->ate_flags & AFTER_TRIGGER_TUP_BITS) ==
4767 : AFTER_TRIGGER_CP_UPDATE)
4768 : {
4769 : Assert(OidIsValid(event->ate_src_part) &&
4770 : OidIsValid(event->ate_dst_part));
4771 144 : src_rInfo = ExecGetTriggerResultRel(estate,
4772 : event->ate_src_part,
4773 : rInfo);
4774 144 : dst_rInfo = ExecGetTriggerResultRel(estate,
4775 : event->ate_dst_part,
4776 : rInfo);
4777 : }
4778 : else
4779 11428 : src_rInfo = dst_rInfo = rInfo;
4780 :
4781 : /*
4782 : * Fire it. Note that the AFTER_TRIGGER_IN_PROGRESS flag is
4783 : * still set, so recursive examinations of the event list
4784 : * won't try to re-fire it.
4785 : */
4786 11572 : AfterTriggerExecute(estate, event, rInfo,
4787 : src_rInfo, dst_rInfo,
4788 : trigdesc, finfo, instr,
4789 : per_tuple_context, slot1, slot2);
4790 :
4791 : /*
4792 : * Mark the event as done.
4793 : */
4794 10314 : event->ate_flags &= ~AFTER_TRIGGER_IN_PROGRESS;
4795 10314 : event->ate_flags |= AFTER_TRIGGER_DONE;
4796 : }
4797 1470 : else if (!(event->ate_flags & AFTER_TRIGGER_DONE))
4798 : {
4799 : /* something remains to be done */
4800 510 : all_fired = all_fired_in_chunk = false;
4801 : }
4802 : }
4803 :
4804 : /* Clear the chunk if delete_ok and nothing left of interest */
4805 6314 : if (delete_ok && all_fired_in_chunk)
4806 : {
4807 192 : chunk->freeptr = CHUNK_DATA_START(chunk);
4808 192 : chunk->endfree = chunk->endptr;
4809 :
4810 : /*
4811 : * If it's last chunk, must sync event list's tailfree too. Note
4812 : * that delete_ok must NOT be passed as true if there could be
4813 : * additional AfterTriggerEventList values pointing at this event
4814 : * list, since we'd fail to fix their copies of tailfree.
4815 : */
4816 192 : if (chunk == events->tail)
4817 192 : events->tailfree = chunk->freeptr;
4818 : }
4819 : }
4820 6314 : if (slot1 != NULL)
4821 : {
4822 38 : ExecDropSingleTupleTableSlot(slot1);
4823 38 : ExecDropSingleTupleTableSlot(slot2);
4824 : }
4825 :
4826 : /* Release working resources */
4827 6314 : MemoryContextDelete(per_tuple_context);
4828 :
4829 6314 : if (local_estate)
4830 : {
4831 192 : ExecCloseResultRelations(estate);
4832 192 : ExecResetTupleTable(estate->es_tupleTable, false);
4833 192 : FreeExecutorState(estate);
4834 : }
4835 :
4836 6314 : return all_fired;
4837 : }
4838 :
4839 :
4840 : /*
4841 : * GetAfterTriggersTableData
4842 : *
4843 : * Find or create an AfterTriggersTableData struct for the specified
4844 : * trigger event (relation + operation type). Ignore existing structs
4845 : * marked "closed"; we don't want to put any additional tuples into them,
4846 : * nor change their stmt-triggers-fired state.
4847 : *
4848 : * Note: the AfterTriggersTableData list is allocated in the current
4849 : * (sub)transaction's CurTransactionContext. This is OK because
4850 : * we don't need it to live past AfterTriggerEndQuery.
4851 : */
4852 : static AfterTriggersTableData *
4853 2178 : GetAfterTriggersTableData(Oid relid, CmdType cmdType)
4854 : {
4855 : AfterTriggersTableData *table;
4856 : AfterTriggersQueryData *qs;
4857 : MemoryContext oldcxt;
4858 : ListCell *lc;
4859 :
4860 : /* Caller should have ensured query_depth is OK. */
4861 : Assert(afterTriggers.query_depth >= 0 &&
4862 : afterTriggers.query_depth < afterTriggers.maxquerydepth);
4863 2178 : qs = &afterTriggers.query_stack[afterTriggers.query_depth];
4864 :
4865 2526 : foreach(lc, qs->tables)
4866 : {
4867 1438 : table = (AfterTriggersTableData *) lfirst(lc);
4868 1438 : if (table->relid == relid && table->cmdType == cmdType &&
4869 1126 : !table->closed)
4870 1090 : return table;
4871 : }
4872 :
4873 1088 : oldcxt = MemoryContextSwitchTo(CurTransactionContext);
4874 :
4875 1088 : table = (AfterTriggersTableData *) palloc0(sizeof(AfterTriggersTableData));
4876 1088 : table->relid = relid;
4877 1088 : table->cmdType = cmdType;
4878 1088 : qs->tables = lappend(qs->tables, table);
4879 :
4880 1088 : MemoryContextSwitchTo(oldcxt);
4881 :
4882 1088 : return table;
4883 : }
4884 :
4885 : /*
4886 : * Returns a TupleTableSlot suitable for holding the tuples to be put
4887 : * into AfterTriggersTableData's transition table tuplestores.
4888 : */
4889 : static TupleTableSlot *
4890 294 : GetAfterTriggersStoreSlot(AfterTriggersTableData *table,
4891 : TupleDesc tupdesc)
4892 : {
4893 : /* Create it if not already done. */
4894 294 : if (!table->storeslot)
4895 : {
4896 : MemoryContext oldcxt;
4897 :
4898 : /*
4899 : * We need this slot only until AfterTriggerEndQuery, but making it
4900 : * last till end-of-subxact is good enough. It'll be freed by
4901 : * AfterTriggerFreeQuery(). However, the passed-in tupdesc might have
4902 : * a different lifespan, so we'd better make a copy of that.
4903 : */
4904 84 : oldcxt = MemoryContextSwitchTo(CurTransactionContext);
4905 84 : tupdesc = CreateTupleDescCopy(tupdesc);
4906 84 : table->storeslot = MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual);
4907 84 : MemoryContextSwitchTo(oldcxt);
4908 : }
4909 :
4910 294 : return table->storeslot;
4911 : }
4912 :
4913 : /*
4914 : * MakeTransitionCaptureState
4915 : *
4916 : * Make a TransitionCaptureState object for the given TriggerDesc, target
4917 : * relation, and operation type. The TCS object holds all the state needed
4918 : * to decide whether to capture tuples in transition tables.
4919 : *
4920 : * If there are no triggers in 'trigdesc' that request relevant transition
4921 : * tables, then return NULL.
4922 : *
4923 : * The resulting object can be passed to the ExecAR* functions. When
4924 : * dealing with child tables, the caller can set tcs_original_insert_tuple
4925 : * to avoid having to reconstruct the original tuple in the root table's
4926 : * format.
4927 : *
4928 : * Note that we copy the flags from a parent table into this struct (rather
4929 : * than subsequently using the relation's TriggerDesc directly) so that we can
4930 : * use it to control collection of transition tuples from child tables.
4931 : *
4932 : * Per SQL spec, all operations of the same kind (INSERT/UPDATE/DELETE)
4933 : * on the same table during one query should share one transition table.
4934 : * Therefore, the Tuplestores are owned by an AfterTriggersTableData struct
4935 : * looked up using the table OID + CmdType, and are merely referenced by
4936 : * the TransitionCaptureState objects we hand out to callers.
4937 : */
4938 : TransitionCaptureState *
4939 118674 : MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
4940 : {
4941 : TransitionCaptureState *state;
4942 : bool need_old_upd,
4943 : need_new_upd,
4944 : need_old_del,
4945 : need_new_ins;
4946 : AfterTriggersTableData *table;
4947 : MemoryContext oldcxt;
4948 : ResourceOwner saveResourceOwner;
4949 :
4950 118674 : if (trigdesc == NULL)
4951 106118 : return NULL;
4952 :
4953 : /* Detect which table(s) we need. */
4954 12556 : switch (cmdType)
4955 : {
4956 6928 : case CMD_INSERT:
4957 6928 : need_old_upd = need_old_del = need_new_upd = false;
4958 6928 : need_new_ins = trigdesc->trig_insert_new_table;
4959 6928 : break;
4960 3882 : case CMD_UPDATE:
4961 3882 : need_old_upd = trigdesc->trig_update_old_table;
4962 3882 : need_new_upd = trigdesc->trig_update_new_table;
4963 3882 : need_old_del = need_new_ins = false;
4964 3882 : break;
4965 1422 : case CMD_DELETE:
4966 1422 : need_old_del = trigdesc->trig_delete_old_table;
4967 1422 : need_old_upd = need_new_upd = need_new_ins = false;
4968 1422 : break;
4969 324 : case CMD_MERGE:
4970 324 : need_old_upd = trigdesc->trig_update_old_table;
4971 324 : need_new_upd = trigdesc->trig_update_new_table;
4972 324 : need_old_del = trigdesc->trig_delete_old_table;
4973 324 : need_new_ins = trigdesc->trig_insert_new_table;
4974 324 : break;
4975 0 : default:
4976 0 : elog(ERROR, "unexpected CmdType: %d", (int) cmdType);
4977 : /* keep compiler quiet */
4978 : need_old_upd = need_new_upd = need_old_del = need_new_ins = false;
4979 : break;
4980 : }
4981 12556 : if (!need_old_upd && !need_new_upd && !need_new_ins && !need_old_del)
4982 11974 : return NULL;
4983 :
4984 : /* Check state, like AfterTriggerSaveEvent. */
4985 582 : if (afterTriggers.query_depth < 0)
4986 0 : elog(ERROR, "MakeTransitionCaptureState() called outside of query");
4987 :
4988 : /* Be sure we have enough space to record events at this query depth. */
4989 582 : if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
4990 438 : AfterTriggerEnlargeQueryState();
4991 :
4992 : /*
4993 : * Find or create an AfterTriggersTableData struct to hold the
4994 : * tuplestore(s). If there's a matching struct but it's marked closed,
4995 : * ignore it; we need a newer one.
4996 : *
4997 : * Note: the AfterTriggersTableData list, as well as the tuplestores, are
4998 : * allocated in the current (sub)transaction's CurTransactionContext, and
4999 : * the tuplestores are managed by the (sub)transaction's resource owner.
5000 : * This is sufficient lifespan because we do not allow triggers using
5001 : * transition tables to be deferrable; they will be fired during
5002 : * AfterTriggerEndQuery, after which it's okay to delete the data.
5003 : */
5004 582 : table = GetAfterTriggersTableData(relid, cmdType);
5005 :
5006 : /* Now create required tuplestore(s), if we don't have them already. */
5007 582 : oldcxt = MemoryContextSwitchTo(CurTransactionContext);
5008 582 : saveResourceOwner = CurrentResourceOwner;
5009 582 : CurrentResourceOwner = CurTransactionResourceOwner;
5010 :
5011 582 : if (need_old_upd && table->old_upd_tuplestore == NULL)
5012 168 : table->old_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
5013 582 : if (need_new_upd && table->new_upd_tuplestore == NULL)
5014 180 : table->new_upd_tuplestore = tuplestore_begin_heap(false, false, work_mem);
5015 582 : if (need_old_del && table->old_del_tuplestore == NULL)
5016 138 : table->old_del_tuplestore = tuplestore_begin_heap(false, false, work_mem);
5017 582 : if (need_new_ins && table->new_ins_tuplestore == NULL)
5018 222 : table->new_ins_tuplestore = tuplestore_begin_heap(false, false, work_mem);
5019 :
5020 582 : CurrentResourceOwner = saveResourceOwner;
5021 582 : MemoryContextSwitchTo(oldcxt);
5022 :
5023 : /* Now build the TransitionCaptureState struct, in caller's context */
5024 582 : state = (TransitionCaptureState *) palloc0(sizeof(TransitionCaptureState));
5025 582 : state->tcs_delete_old_table = need_old_del;
5026 582 : state->tcs_update_old_table = need_old_upd;
5027 582 : state->tcs_update_new_table = need_new_upd;
5028 582 : state->tcs_insert_new_table = need_new_ins;
5029 582 : state->tcs_private = table;
5030 :
5031 582 : return state;
5032 : }
5033 :
5034 :
5035 : /* ----------
5036 : * AfterTriggerBeginXact()
5037 : *
5038 : * Called at transaction start (either BEGIN or implicit for single
5039 : * statement outside of transaction block).
5040 : * ----------
5041 : */
5042 : void
5043 1100364 : AfterTriggerBeginXact(void)
5044 : {
5045 : /*
5046 : * Initialize after-trigger state structure to empty
5047 : */
5048 1100364 : afterTriggers.firing_counter = (CommandId) 1; /* mustn't be 0 */
5049 1100364 : afterTriggers.query_depth = -1;
5050 :
5051 : /*
5052 : * Verify that there is no leftover state remaining. If these assertions
5053 : * trip, it means that AfterTriggerEndXact wasn't called or didn't clean
5054 : * up properly.
5055 : */
5056 : Assert(afterTriggers.state == NULL);
5057 : Assert(afterTriggers.query_stack == NULL);
5058 : Assert(afterTriggers.maxquerydepth == 0);
5059 : Assert(afterTriggers.event_cxt == NULL);
5060 : Assert(afterTriggers.events.head == NULL);
5061 : Assert(afterTriggers.trans_stack == NULL);
5062 : Assert(afterTriggers.maxtransdepth == 0);
5063 1100364 : }
5064 :
5065 :
5066 : /* ----------
5067 : * AfterTriggerBeginQuery()
5068 : *
5069 : * Called just before we start processing a single query within a
5070 : * transaction (or subtransaction). Most of the real work gets deferred
5071 : * until somebody actually tries to queue a trigger event.
5072 : * ----------
5073 : */
5074 : void
5075 416956 : AfterTriggerBeginQuery(void)
5076 : {
5077 : /* Increase the query stack depth */
5078 416956 : afterTriggers.query_depth++;
5079 416956 : }
5080 :
5081 :
5082 : /* ----------
5083 : * AfterTriggerEndQuery()
5084 : *
5085 : * Called after one query has been completely processed. At this time
5086 : * we invoke all AFTER IMMEDIATE trigger events queued by the query, and
5087 : * transfer deferred trigger events to the global deferred-trigger list.
5088 : *
5089 : * Note that this must be called BEFORE closing down the executor
5090 : * with ExecutorEnd, because we make use of the EState's info about
5091 : * target relations. Normally it is called from ExecutorFinish.
5092 : * ----------
5093 : */
5094 : void
5095 412180 : AfterTriggerEndQuery(EState *estate)
5096 : {
5097 : AfterTriggersQueryData *qs;
5098 :
5099 : /* Must be inside a query, too */
5100 : Assert(afterTriggers.query_depth >= 0);
5101 :
5102 : /*
5103 : * If we never even got as far as initializing the event stack, there
5104 : * certainly won't be any events, so exit quickly.
5105 : */
5106 412180 : if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
5107 : {
5108 403374 : afterTriggers.query_depth--;
5109 403374 : return;
5110 : }
5111 :
5112 : /*
5113 : * Process all immediate-mode triggers queued by the query, and move the
5114 : * deferred ones to the main list of deferred events.
5115 : *
5116 : * Notice that we decide which ones will be fired, and put the deferred
5117 : * ones on the main list, before anything is actually fired. This ensures
5118 : * reasonably sane behavior if a trigger function does SET CONSTRAINTS ...
5119 : * IMMEDIATE: all events we have decided to defer will be available for it
5120 : * to fire.
5121 : *
5122 : * We loop in case a trigger queues more events at the same query level.
5123 : * Ordinary trigger functions, including all PL/pgSQL trigger functions,
5124 : * will instead fire any triggers in a dedicated query level. Foreign key
5125 : * enforcement triggers do add to the current query level, thanks to their
5126 : * passing fire_triggers = false to SPI_execute_snapshot(). Other
5127 : * C-language triggers might do likewise.
5128 : *
5129 : * If we find no firable events, we don't have to increment
5130 : * firing_counter.
5131 : */
5132 8806 : qs = &afterTriggers.query_stack[afterTriggers.query_depth];
5133 :
5134 : for (;;)
5135 : {
5136 9106 : if (afterTriggerMarkEvents(&qs->events, &afterTriggers.events, true))
5137 : {
5138 7210 : CommandId firing_id = afterTriggers.firing_counter++;
5139 7210 : AfterTriggerEventChunk *oldtail = qs->events.tail;
5140 :
5141 7210 : if (afterTriggerInvokeEvents(&qs->events, firing_id, estate, false))
5142 5822 : break; /* all fired */
5143 :
5144 : /*
5145 : * Firing a trigger could result in query_stack being repalloc'd,
5146 : * so we must recalculate qs after each afterTriggerInvokeEvents
5147 : * call. Furthermore, it's unsafe to pass delete_ok = true here,
5148 : * because that could cause afterTriggerInvokeEvents to try to
5149 : * access qs->events after the stack has been repalloc'd.
5150 : */
5151 300 : qs = &afterTriggers.query_stack[afterTriggers.query_depth];
5152 :
5153 : /*
5154 : * We'll need to scan the events list again. To reduce the cost
5155 : * of doing so, get rid of completely-fired chunks. We know that
5156 : * all events were marked IN_PROGRESS or DONE at the conclusion of
5157 : * afterTriggerMarkEvents, so any still-interesting events must
5158 : * have been added after that, and so must be in the chunk that
5159 : * was then the tail chunk, or in later chunks. So, zap all
5160 : * chunks before oldtail. This is approximately the same set of
5161 : * events we would have gotten rid of by passing delete_ok = true.
5162 : */
5163 : Assert(oldtail != NULL);
5164 300 : while (qs->events.head != oldtail)
5165 0 : afterTriggerDeleteHeadEventChunk(qs);
5166 : }
5167 : else
5168 1884 : break;
5169 : }
5170 :
5171 : /* Release query-level-local storage, including tuplestores if any */
5172 7706 : AfterTriggerFreeQuery(&afterTriggers.query_stack[afterTriggers.query_depth]);
5173 :
5174 7706 : afterTriggers.query_depth--;
5175 : }
5176 :
5177 :
5178 : /*
5179 : * AfterTriggerFreeQuery
5180 : * Release subsidiary storage for a trigger query level.
5181 : * This includes closing down tuplestores.
5182 : * Note: it's important for this to be safe if interrupted by an error
5183 : * and then called again for the same query level.
5184 : */
5185 : static void
5186 7736 : AfterTriggerFreeQuery(AfterTriggersQueryData *qs)
5187 : {
5188 : Tuplestorestate *ts;
5189 : List *tables;
5190 : ListCell *lc;
5191 :
5192 : /* Drop the trigger events */
5193 7736 : afterTriggerFreeEventList(&qs->events);
5194 :
5195 : /* Drop FDW tuplestore if any */
5196 7736 : ts = qs->fdw_tuplestore;
5197 7736 : qs->fdw_tuplestore = NULL;
5198 7736 : if (ts)
5199 36 : tuplestore_end(ts);
5200 :
5201 : /* Release per-table subsidiary storage */
5202 7736 : tables = qs->tables;
5203 8766 : foreach(lc, tables)
5204 : {
5205 1030 : AfterTriggersTableData *table = (AfterTriggersTableData *) lfirst(lc);
5206 :
5207 1030 : ts = table->old_upd_tuplestore;
5208 1030 : table->old_upd_tuplestore = NULL;
5209 1030 : if (ts)
5210 156 : tuplestore_end(ts);
5211 1030 : ts = table->new_upd_tuplestore;
5212 1030 : table->new_upd_tuplestore = NULL;
5213 1030 : if (ts)
5214 162 : tuplestore_end(ts);
5215 1030 : ts = table->old_del_tuplestore;
5216 1030 : table->old_del_tuplestore = NULL;
5217 1030 : if (ts)
5218 126 : tuplestore_end(ts);
5219 1030 : ts = table->new_ins_tuplestore;
5220 1030 : table->new_ins_tuplestore = NULL;
5221 1030 : if (ts)
5222 210 : tuplestore_end(ts);
5223 1030 : if (table->storeslot)
5224 : {
5225 84 : TupleTableSlot *slot = table->storeslot;
5226 :
5227 84 : table->storeslot = NULL;
5228 84 : ExecDropSingleTupleTableSlot(slot);
5229 : }
5230 : }
5231 :
5232 : /*
5233 : * Now free the AfterTriggersTableData structs and list cells. Reset list
5234 : * pointer first; if list_free_deep somehow gets an error, better to leak
5235 : * that storage than have an infinite loop.
5236 : */
5237 7736 : qs->tables = NIL;
5238 7736 : list_free_deep(tables);
5239 7736 : }
5240 :
5241 :
5242 : /* ----------
5243 : * AfterTriggerFireDeferred()
5244 : *
5245 : * Called just before the current transaction is committed. At this
5246 : * time we invoke all pending DEFERRED triggers.
5247 : *
5248 : * It is possible for other modules to queue additional deferred triggers
5249 : * during pre-commit processing; therefore xact.c may have to call this
5250 : * multiple times.
5251 : * ----------
5252 : */
5253 : void
5254 1062888 : AfterTriggerFireDeferred(void)
5255 : {
5256 : AfterTriggerEventList *events;
5257 1062888 : bool snap_pushed = false;
5258 :
5259 : /* Must not be inside a query */
5260 : Assert(afterTriggers.query_depth == -1);
5261 :
5262 : /*
5263 : * If there are any triggers to fire, make sure we have set a snapshot for
5264 : * them to use. (Since PortalRunUtility doesn't set a snap for COMMIT, we
5265 : * can't assume ActiveSnapshot is valid on entry.)
5266 : */
5267 1062888 : events = &afterTriggers.events;
5268 1062888 : if (events->head != NULL)
5269 : {
5270 346 : PushActiveSnapshot(GetTransactionSnapshot());
5271 346 : snap_pushed = true;
5272 : }
5273 :
5274 : /*
5275 : * Run all the remaining triggers. Loop until they are all gone, in case
5276 : * some trigger queues more for us to do.
5277 : */
5278 1062888 : while (afterTriggerMarkEvents(events, NULL, false))
5279 : {
5280 346 : CommandId firing_id = afterTriggers.firing_counter++;
5281 :
5282 346 : if (afterTriggerInvokeEvents(events, firing_id, NULL, true))
5283 192 : break; /* all fired */
5284 : }
5285 :
5286 : /*
5287 : * We don't bother freeing the event list, since it will go away anyway
5288 : * (and more efficiently than via pfree) in AfterTriggerEndXact.
5289 : */
5290 :
5291 1062734 : if (snap_pushed)
5292 192 : PopActiveSnapshot();
5293 1062734 : }
5294 :
5295 :
5296 : /* ----------
5297 : * AfterTriggerEndXact()
5298 : *
5299 : * The current transaction is finishing.
5300 : *
5301 : * Any unfired triggers are canceled so we simply throw
5302 : * away anything we know.
5303 : *
5304 : * Note: it is possible for this to be called repeatedly in case of
5305 : * error during transaction abort; therefore, do not complain if
5306 : * already closed down.
5307 : * ----------
5308 : */
5309 : void
5310 1100776 : AfterTriggerEndXact(bool isCommit)
5311 : {
5312 : /*
5313 : * Forget the pending-events list.
5314 : *
5315 : * Since all the info is in TopTransactionContext or children thereof, we
5316 : * don't really need to do anything to reclaim memory. However, the
5317 : * pending-events list could be large, and so it's useful to discard it as
5318 : * soon as possible --- especially if we are aborting because we ran out
5319 : * of memory for the list!
5320 : */
5321 1100776 : if (afterTriggers.event_cxt)
5322 : {
5323 6580 : MemoryContextDelete(afterTriggers.event_cxt);
5324 6580 : afterTriggers.event_cxt = NULL;
5325 6580 : afterTriggers.events.head = NULL;
5326 6580 : afterTriggers.events.tail = NULL;
5327 6580 : afterTriggers.events.tailfree = NULL;
5328 : }
5329 :
5330 : /*
5331 : * Forget any subtransaction state as well. Since this can't be very
5332 : * large, we let the eventual reset of TopTransactionContext free the
5333 : * memory instead of doing it here.
5334 : */
5335 1100776 : afterTriggers.trans_stack = NULL;
5336 1100776 : afterTriggers.maxtransdepth = 0;
5337 :
5338 :
5339 : /*
5340 : * Forget the query stack and constraint-related state information. As
5341 : * with the subtransaction state information, we don't bother freeing the
5342 : * memory here.
5343 : */
5344 1100776 : afterTriggers.query_stack = NULL;
5345 1100776 : afterTriggers.maxquerydepth = 0;
5346 1100776 : afterTriggers.state = NULL;
5347 :
5348 : /* No more afterTriggers manipulation until next transaction starts. */
5349 1100776 : afterTriggers.query_depth = -1;
5350 1100776 : }
5351 :
5352 : /*
5353 : * AfterTriggerBeginSubXact()
5354 : *
5355 : * Start a subtransaction.
5356 : */
5357 : void
5358 20042 : AfterTriggerBeginSubXact(void)
5359 : {
5360 20042 : int my_level = GetCurrentTransactionNestLevel();
5361 :
5362 : /*
5363 : * Allocate more space in the trans_stack if needed. (Note: because the
5364 : * minimum nest level of a subtransaction is 2, we waste the first couple
5365 : * entries of the array; not worth the notational effort to avoid it.)
5366 : */
5367 22798 : while (my_level >= afterTriggers.maxtransdepth)
5368 : {
5369 2756 : if (afterTriggers.maxtransdepth == 0)
5370 : {
5371 : /* Arbitrarily initialize for max of 8 subtransaction levels */
5372 2672 : afterTriggers.trans_stack = (AfterTriggersTransData *)
5373 2672 : MemoryContextAlloc(TopTransactionContext,
5374 : 8 * sizeof(AfterTriggersTransData));
5375 2672 : afterTriggers.maxtransdepth = 8;
5376 : }
5377 : else
5378 : {
5379 : /* repalloc will keep the stack in the same context */
5380 84 : int new_alloc = afterTriggers.maxtransdepth * 2;
5381 :
5382 84 : afterTriggers.trans_stack = (AfterTriggersTransData *)
5383 84 : repalloc(afterTriggers.trans_stack,
5384 : new_alloc * sizeof(AfterTriggersTransData));
5385 84 : afterTriggers.maxtransdepth = new_alloc;
5386 : }
5387 : }
5388 :
5389 : /*
5390 : * Push the current information into the stack. The SET CONSTRAINTS state
5391 : * is not saved until/unless changed. Likewise, we don't make a
5392 : * per-subtransaction event context until needed.
5393 : */
5394 20042 : afterTriggers.trans_stack[my_level].state = NULL;
5395 20042 : afterTriggers.trans_stack[my_level].events = afterTriggers.events;
5396 20042 : afterTriggers.trans_stack[my_level].query_depth = afterTriggers.query_depth;
5397 20042 : afterTriggers.trans_stack[my_level].firing_counter = afterTriggers.firing_counter;
5398 20042 : }
5399 :
5400 : /*
5401 : * AfterTriggerEndSubXact()
5402 : *
5403 : * The current subtransaction is ending.
5404 : */
5405 : void
5406 20042 : AfterTriggerEndSubXact(bool isCommit)
5407 : {
5408 20042 : int my_level = GetCurrentTransactionNestLevel();
5409 : SetConstraintState state;
5410 : AfterTriggerEvent event;
5411 : AfterTriggerEventChunk *chunk;
5412 : CommandId subxact_firing_id;
5413 :
5414 : /*
5415 : * Pop the prior state if needed.
5416 : */
5417 20042 : if (isCommit)
5418 : {
5419 : Assert(my_level < afterTriggers.maxtransdepth);
5420 : /* If we saved a prior state, we don't need it anymore */
5421 10696 : state = afterTriggers.trans_stack[my_level].state;
5422 10696 : if (state != NULL)
5423 6 : pfree(state);
5424 : /* this avoids double pfree if error later: */
5425 10696 : afterTriggers.trans_stack[my_level].state = NULL;
5426 : Assert(afterTriggers.query_depth ==
5427 : afterTriggers.trans_stack[my_level].query_depth);
5428 : }
5429 : else
5430 : {
5431 : /*
5432 : * Aborting. It is possible subxact start failed before calling
5433 : * AfterTriggerBeginSubXact, in which case we mustn't risk touching
5434 : * trans_stack levels that aren't there.
5435 : */
5436 9346 : if (my_level >= afterTriggers.maxtransdepth)
5437 0 : return;
5438 :
5439 : /*
5440 : * Release query-level storage for queries being aborted, and restore
5441 : * query_depth to its pre-subxact value. This assumes that a
5442 : * subtransaction will not add events to query levels started in a
5443 : * earlier transaction state.
5444 : */
5445 9440 : while (afterTriggers.query_depth > afterTriggers.trans_stack[my_level].query_depth)
5446 : {
5447 94 : if (afterTriggers.query_depth < afterTriggers.maxquerydepth)
5448 30 : AfterTriggerFreeQuery(&afterTriggers.query_stack[afterTriggers.query_depth]);
5449 94 : afterTriggers.query_depth--;
5450 : }
5451 : Assert(afterTriggers.query_depth ==
5452 : afterTriggers.trans_stack[my_level].query_depth);
5453 :
5454 : /*
5455 : * Restore the global deferred-event list to its former length,
5456 : * discarding any events queued by the subxact.
5457 : */
5458 9346 : afterTriggerRestoreEventList(&afterTriggers.events,
5459 9346 : &afterTriggers.trans_stack[my_level].events);
5460 :
5461 : /*
5462 : * Restore the trigger state. If the saved state is NULL, then this
5463 : * subxact didn't save it, so it doesn't need restoring.
5464 : */
5465 9346 : state = afterTriggers.trans_stack[my_level].state;
5466 9346 : if (state != NULL)
5467 : {
5468 4 : pfree(afterTriggers.state);
5469 4 : afterTriggers.state = state;
5470 : }
5471 : /* this avoids double pfree if error later: */
5472 9346 : afterTriggers.trans_stack[my_level].state = NULL;
5473 :
5474 : /*
5475 : * Scan for any remaining deferred events that were marked DONE or IN
5476 : * PROGRESS by this subxact or a child, and un-mark them. We can
5477 : * recognize such events because they have a firing ID greater than or
5478 : * equal to the firing_counter value we saved at subtransaction start.
5479 : * (This essentially assumes that the current subxact includes all
5480 : * subxacts started after it.)
5481 : */
5482 9346 : subxact_firing_id = afterTriggers.trans_stack[my_level].firing_counter;
5483 9390 : for_each_event_chunk(event, chunk, afterTriggers.events)
5484 : {
5485 22 : AfterTriggerShared evtshared = GetTriggerSharedData(event);
5486 :
5487 22 : if (event->ate_flags &
5488 : (AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS))
5489 : {
5490 4 : if (evtshared->ats_firing_id >= subxact_firing_id)
5491 4 : event->ate_flags &=
5492 : ~(AFTER_TRIGGER_DONE | AFTER_TRIGGER_IN_PROGRESS);
5493 : }
5494 : }
5495 : }
5496 : }
5497 :
5498 : /*
5499 : * Get the transition table for the given event and depending on whether we are
5500 : * processing the old or the new tuple.
5501 : */
5502 : static Tuplestorestate *
5503 66126 : GetAfterTriggersTransitionTable(int event,
5504 : TupleTableSlot *oldslot,
5505 : TupleTableSlot *newslot,
5506 : TransitionCaptureState *transition_capture)
5507 : {
5508 66126 : Tuplestorestate *tuplestore = NULL;
5509 66126 : bool delete_old_table = transition_capture->tcs_delete_old_table;
5510 66126 : bool update_old_table = transition_capture->tcs_update_old_table;
5511 66126 : bool update_new_table = transition_capture->tcs_update_new_table;
5512 66126 : bool insert_new_table = transition_capture->tcs_insert_new_table;
5513 :
5514 : /*
5515 : * For INSERT events NEW should be non-NULL, for DELETE events OLD should
5516 : * be non-NULL, whereas for UPDATE events normally both OLD and NEW are
5517 : * non-NULL. But for UPDATE events fired for capturing transition tuples
5518 : * during UPDATE partition-key row movement, OLD is NULL when the event is
5519 : * for a row being inserted, whereas NEW is NULL when the event is for a
5520 : * row being deleted.
5521 : */
5522 : Assert(!(event == TRIGGER_EVENT_DELETE && delete_old_table &&
5523 : TupIsNull(oldslot)));
5524 : Assert(!(event == TRIGGER_EVENT_INSERT && insert_new_table &&
5525 : TupIsNull(newslot)));
5526 :
5527 66126 : if (!TupIsNull(oldslot))
5528 : {
5529 : Assert(TupIsNull(newslot));
5530 5412 : if (event == TRIGGER_EVENT_DELETE && delete_old_table)
5531 5052 : tuplestore = transition_capture->tcs_private->old_del_tuplestore;
5532 360 : else if (event == TRIGGER_EVENT_UPDATE && update_old_table)
5533 336 : tuplestore = transition_capture->tcs_private->old_upd_tuplestore;
5534 : }
5535 60714 : else if (!TupIsNull(newslot))
5536 : {
5537 : Assert(TupIsNull(oldslot));
5538 60714 : if (event == TRIGGER_EVENT_INSERT && insert_new_table)
5539 60354 : tuplestore = transition_capture->tcs_private->new_ins_tuplestore;
5540 360 : else if (event == TRIGGER_EVENT_UPDATE && update_new_table)
5541 354 : tuplestore = transition_capture->tcs_private->new_upd_tuplestore;
5542 : }
5543 :
5544 66126 : return tuplestore;
5545 : }
5546 :
5547 : /*
5548 : * Add the given heap tuple to the given tuplestore, applying the conversion
5549 : * map if necessary.
5550 : *
5551 : * If original_insert_tuple is given, we can add that tuple without conversion.
5552 : */
5553 : static void
5554 66126 : TransitionTableAddTuple(EState *estate,
5555 : TransitionCaptureState *transition_capture,
5556 : ResultRelInfo *relinfo,
5557 : TupleTableSlot *slot,
5558 : TupleTableSlot *original_insert_tuple,
5559 : Tuplestorestate *tuplestore)
5560 : {
5561 : TupleConversionMap *map;
5562 :
5563 : /*
5564 : * Nothing needs to be done if we don't have a tuplestore.
5565 : */
5566 66126 : if (tuplestore == NULL)
5567 30 : return;
5568 :
5569 66096 : if (original_insert_tuple)
5570 144 : tuplestore_puttupleslot(tuplestore, original_insert_tuple);
5571 65952 : else if ((map = ExecGetChildToRootMap(relinfo)) != NULL)
5572 : {
5573 294 : AfterTriggersTableData *table = transition_capture->tcs_private;
5574 : TupleTableSlot *storeslot;
5575 :
5576 294 : storeslot = GetAfterTriggersStoreSlot(table, map->outdesc);
5577 294 : execute_attr_map_slot(map->attrMap, slot, storeslot);
5578 294 : tuplestore_puttupleslot(tuplestore, storeslot);
5579 : }
5580 : else
5581 65658 : tuplestore_puttupleslot(tuplestore, slot);
5582 : }
5583 :
5584 : /* ----------
5585 : * AfterTriggerEnlargeQueryState()
5586 : *
5587 : * Prepare the necessary state so that we can record AFTER trigger events
5588 : * queued by a query. It is allowed to have nested queries within a
5589 : * (sub)transaction, so we need to have separate state for each query
5590 : * nesting level.
5591 : * ----------
5592 : */
5593 : static void
5594 6934 : AfterTriggerEnlargeQueryState(void)
5595 : {
5596 6934 : int init_depth = afterTriggers.maxquerydepth;
5597 :
5598 : Assert(afterTriggers.query_depth >= afterTriggers.maxquerydepth);
5599 :
5600 6934 : if (afterTriggers.maxquerydepth == 0)
5601 : {
5602 6934 : int new_alloc = Max(afterTriggers.query_depth + 1, 8);
5603 :
5604 6934 : afterTriggers.query_stack = (AfterTriggersQueryData *)
5605 6934 : MemoryContextAlloc(TopTransactionContext,
5606 : new_alloc * sizeof(AfterTriggersQueryData));
5607 6934 : afterTriggers.maxquerydepth = new_alloc;
5608 : }
5609 : else
5610 : {
5611 : /* repalloc will keep the stack in the same context */
5612 0 : int old_alloc = afterTriggers.maxquerydepth;
5613 0 : int new_alloc = Max(afterTriggers.query_depth + 1,
5614 : old_alloc * 2);
5615 :
5616 0 : afterTriggers.query_stack = (AfterTriggersQueryData *)
5617 0 : repalloc(afterTriggers.query_stack,
5618 : new_alloc * sizeof(AfterTriggersQueryData));
5619 0 : afterTriggers.maxquerydepth = new_alloc;
5620 : }
5621 :
5622 : /* Initialize new array entries to empty */
5623 62406 : while (init_depth < afterTriggers.maxquerydepth)
5624 : {
5625 55472 : AfterTriggersQueryData *qs = &afterTriggers.query_stack[init_depth];
5626 :
5627 55472 : qs->events.head = NULL;
5628 55472 : qs->events.tail = NULL;
5629 55472 : qs->events.tailfree = NULL;
5630 55472 : qs->fdw_tuplestore = NULL;
5631 55472 : qs->tables = NIL;
5632 :
5633 55472 : ++init_depth;
5634 : }
5635 6934 : }
5636 :
5637 : /*
5638 : * Create an empty SetConstraintState with room for numalloc trigstates
5639 : */
5640 : static SetConstraintState
5641 96 : SetConstraintStateCreate(int numalloc)
5642 : {
5643 : SetConstraintState state;
5644 :
5645 : /* Behave sanely with numalloc == 0 */
5646 96 : if (numalloc <= 0)
5647 10 : numalloc = 1;
5648 :
5649 : /*
5650 : * We assume that zeroing will correctly initialize the state values.
5651 : */
5652 : state = (SetConstraintState)
5653 96 : MemoryContextAllocZero(TopTransactionContext,
5654 : offsetof(SetConstraintStateData, trigstates) +
5655 96 : numalloc * sizeof(SetConstraintTriggerData));
5656 :
5657 96 : state->numalloc = numalloc;
5658 :
5659 96 : return state;
5660 : }
5661 :
5662 : /*
5663 : * Copy a SetConstraintState
5664 : */
5665 : static SetConstraintState
5666 10 : SetConstraintStateCopy(SetConstraintState origstate)
5667 : {
5668 : SetConstraintState state;
5669 :
5670 10 : state = SetConstraintStateCreate(origstate->numstates);
5671 :
5672 10 : state->all_isset = origstate->all_isset;
5673 10 : state->all_isdeferred = origstate->all_isdeferred;
5674 10 : state->numstates = origstate->numstates;
5675 10 : memcpy(state->trigstates, origstate->trigstates,
5676 10 : origstate->numstates * sizeof(SetConstraintTriggerData));
5677 :
5678 10 : return state;
5679 : }
5680 :
5681 : /*
5682 : * Add a per-trigger item to a SetConstraintState. Returns possibly-changed
5683 : * pointer to the state object (it will change if we have to repalloc).
5684 : */
5685 : static SetConstraintState
5686 342 : SetConstraintStateAddItem(SetConstraintState state,
5687 : Oid tgoid, bool tgisdeferred)
5688 : {
5689 342 : if (state->numstates >= state->numalloc)
5690 : {
5691 30 : int newalloc = state->numalloc * 2;
5692 :
5693 30 : newalloc = Max(newalloc, 8); /* in case original has size 0 */
5694 : state = (SetConstraintState)
5695 30 : repalloc(state,
5696 : offsetof(SetConstraintStateData, trigstates) +
5697 30 : newalloc * sizeof(SetConstraintTriggerData));
5698 30 : state->numalloc = newalloc;
5699 : Assert(state->numstates < state->numalloc);
5700 : }
5701 :
5702 342 : state->trigstates[state->numstates].sct_tgoid = tgoid;
5703 342 : state->trigstates[state->numstates].sct_tgisdeferred = tgisdeferred;
5704 342 : state->numstates++;
5705 :
5706 342 : return state;
5707 : }
5708 :
5709 : /* ----------
5710 : * AfterTriggerSetState()
5711 : *
5712 : * Execute the SET CONSTRAINTS ... utility command.
5713 : * ----------
5714 : */
5715 : void
5716 102 : AfterTriggerSetState(ConstraintsSetStmt *stmt)
5717 : {
5718 102 : int my_level = GetCurrentTransactionNestLevel();
5719 :
5720 : /* If we haven't already done so, initialize our state. */
5721 102 : if (afterTriggers.state == NULL)
5722 86 : afterTriggers.state = SetConstraintStateCreate(8);
5723 :
5724 : /*
5725 : * If in a subtransaction, and we didn't save the current state already,
5726 : * save it so it can be restored if the subtransaction aborts.
5727 : */
5728 102 : if (my_level > 1 &&
5729 10 : afterTriggers.trans_stack[my_level].state == NULL)
5730 : {
5731 10 : afterTriggers.trans_stack[my_level].state =
5732 10 : SetConstraintStateCopy(afterTriggers.state);
5733 : }
5734 :
5735 : /*
5736 : * Handle SET CONSTRAINTS ALL ...
5737 : */
5738 102 : if (stmt->constraints == NIL)
5739 : {
5740 : /*
5741 : * Forget any previous SET CONSTRAINTS commands in this transaction.
5742 : */
5743 54 : afterTriggers.state->numstates = 0;
5744 :
5745 : /*
5746 : * Set the per-transaction ALL state to known.
5747 : */
5748 54 : afterTriggers.state->all_isset = true;
5749 54 : afterTriggers.state->all_isdeferred = stmt->deferred;
5750 : }
5751 : else
5752 : {
5753 : Relation conrel;
5754 : Relation tgrel;
5755 48 : List *conoidlist = NIL;
5756 48 : List *tgoidlist = NIL;
5757 : ListCell *lc;
5758 :
5759 : /*
5760 : * Handle SET CONSTRAINTS constraint-name [, ...]
5761 : *
5762 : * First, identify all the named constraints and make a list of their
5763 : * OIDs. Since, unlike the SQL spec, we allow multiple constraints of
5764 : * the same name within a schema, the specifications are not
5765 : * necessarily unique. Our strategy is to target all matching
5766 : * constraints within the first search-path schema that has any
5767 : * matches, but disregard matches in schemas beyond the first match.
5768 : * (This is a bit odd but it's the historical behavior.)
5769 : *
5770 : * A constraint in a partitioned table may have corresponding
5771 : * constraints in the partitions. Grab those too.
5772 : */
5773 48 : conrel = table_open(ConstraintRelationId, AccessShareLock);
5774 :
5775 96 : foreach(lc, stmt->constraints)
5776 : {
5777 48 : RangeVar *constraint = lfirst(lc);
5778 : bool found;
5779 : List *namespacelist;
5780 : ListCell *nslc;
5781 :
5782 48 : if (constraint->catalogname)
5783 : {
5784 0 : if (strcmp(constraint->catalogname, get_database_name(MyDatabaseId)) != 0)
5785 0 : ereport(ERROR,
5786 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5787 : errmsg("cross-database references are not implemented: \"%s.%s.%s\"",
5788 : constraint->catalogname, constraint->schemaname,
5789 : constraint->relname)));
5790 : }
5791 :
5792 : /*
5793 : * If we're given the schema name with the constraint, look only
5794 : * in that schema. If given a bare constraint name, use the
5795 : * search path to find the first matching constraint.
5796 : */
5797 48 : if (constraint->schemaname)
5798 : {
5799 12 : Oid namespaceId = LookupExplicitNamespace(constraint->schemaname,
5800 : false);
5801 :
5802 12 : namespacelist = list_make1_oid(namespaceId);
5803 : }
5804 : else
5805 : {
5806 36 : namespacelist = fetch_search_path(true);
5807 : }
5808 :
5809 48 : found = false;
5810 120 : foreach(nslc, namespacelist)
5811 : {
5812 120 : Oid namespaceId = lfirst_oid(nslc);
5813 : SysScanDesc conscan;
5814 : ScanKeyData skey[2];
5815 : HeapTuple tup;
5816 :
5817 120 : ScanKeyInit(&skey[0],
5818 : Anum_pg_constraint_conname,
5819 : BTEqualStrategyNumber, F_NAMEEQ,
5820 120 : CStringGetDatum(constraint->relname));
5821 120 : ScanKeyInit(&skey[1],
5822 : Anum_pg_constraint_connamespace,
5823 : BTEqualStrategyNumber, F_OIDEQ,
5824 : ObjectIdGetDatum(namespaceId));
5825 :
5826 120 : conscan = systable_beginscan(conrel, ConstraintNameNspIndexId,
5827 : true, NULL, 2, skey);
5828 :
5829 216 : while (HeapTupleIsValid(tup = systable_getnext(conscan)))
5830 : {
5831 96 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tup);
5832 :
5833 96 : if (con->condeferrable)
5834 96 : conoidlist = lappend_oid(conoidlist, con->oid);
5835 0 : else if (stmt->deferred)
5836 0 : ereport(ERROR,
5837 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5838 : errmsg("constraint \"%s\" is not deferrable",
5839 : constraint->relname)));
5840 96 : found = true;
5841 : }
5842 :
5843 120 : systable_endscan(conscan);
5844 :
5845 : /*
5846 : * Once we've found a matching constraint we do not search
5847 : * later parts of the search path.
5848 : */
5849 120 : if (found)
5850 48 : break;
5851 : }
5852 :
5853 48 : list_free(namespacelist);
5854 :
5855 : /*
5856 : * Not found ?
5857 : */
5858 48 : if (!found)
5859 0 : ereport(ERROR,
5860 : (errcode(ERRCODE_UNDEFINED_OBJECT),
5861 : errmsg("constraint \"%s\" does not exist",
5862 : constraint->relname)));
5863 : }
5864 :
5865 : /*
5866 : * Scan for any possible descendants of the constraints. We append
5867 : * whatever we find to the same list that we're scanning; this has the
5868 : * effect that we create new scans for those, too, so if there are
5869 : * further descendents, we'll also catch them.
5870 : */
5871 258 : foreach(lc, conoidlist)
5872 : {
5873 210 : Oid parent = lfirst_oid(lc);
5874 : ScanKeyData key;
5875 : SysScanDesc scan;
5876 : HeapTuple tuple;
5877 :
5878 210 : ScanKeyInit(&key,
5879 : Anum_pg_constraint_conparentid,
5880 : BTEqualStrategyNumber, F_OIDEQ,
5881 : ObjectIdGetDatum(parent));
5882 :
5883 210 : scan = systable_beginscan(conrel, ConstraintParentIndexId, true, NULL, 1, &key);
5884 :
5885 324 : while (HeapTupleIsValid(tuple = systable_getnext(scan)))
5886 : {
5887 114 : Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
5888 :
5889 114 : conoidlist = lappend_oid(conoidlist, con->oid);
5890 : }
5891 :
5892 210 : systable_endscan(scan);
5893 : }
5894 :
5895 48 : table_close(conrel, AccessShareLock);
5896 :
5897 : /*
5898 : * Now, locate the trigger(s) implementing each of these constraints,
5899 : * and make a list of their OIDs.
5900 : */
5901 48 : tgrel = table_open(TriggerRelationId, AccessShareLock);
5902 :
5903 258 : foreach(lc, conoidlist)
5904 : {
5905 210 : Oid conoid = lfirst_oid(lc);
5906 : ScanKeyData skey;
5907 : SysScanDesc tgscan;
5908 : HeapTuple htup;
5909 :
5910 210 : ScanKeyInit(&skey,
5911 : Anum_pg_trigger_tgconstraint,
5912 : BTEqualStrategyNumber, F_OIDEQ,
5913 : ObjectIdGetDatum(conoid));
5914 :
5915 210 : tgscan = systable_beginscan(tgrel, TriggerConstraintIndexId, true,
5916 : NULL, 1, &skey);
5917 :
5918 858 : while (HeapTupleIsValid(htup = systable_getnext(tgscan)))
5919 : {
5920 438 : Form_pg_trigger pg_trigger = (Form_pg_trigger) GETSTRUCT(htup);
5921 :
5922 : /*
5923 : * Silently skip triggers that are marked as non-deferrable in
5924 : * pg_trigger. This is not an error condition, since a
5925 : * deferrable RI constraint may have some non-deferrable
5926 : * actions.
5927 : */
5928 438 : if (pg_trigger->tgdeferrable)
5929 438 : tgoidlist = lappend_oid(tgoidlist, pg_trigger->oid);
5930 : }
5931 :
5932 210 : systable_endscan(tgscan);
5933 : }
5934 :
5935 48 : table_close(tgrel, AccessShareLock);
5936 :
5937 : /*
5938 : * Now we can set the trigger states of individual triggers for this
5939 : * xact.
5940 : */
5941 486 : foreach(lc, tgoidlist)
5942 : {
5943 438 : Oid tgoid = lfirst_oid(lc);
5944 438 : SetConstraintState state = afterTriggers.state;
5945 438 : bool found = false;
5946 : int i;
5947 :
5948 2448 : for (i = 0; i < state->numstates; i++)
5949 : {
5950 2106 : if (state->trigstates[i].sct_tgoid == tgoid)
5951 : {
5952 96 : state->trigstates[i].sct_tgisdeferred = stmt->deferred;
5953 96 : found = true;
5954 96 : break;
5955 : }
5956 : }
5957 438 : if (!found)
5958 : {
5959 342 : afterTriggers.state =
5960 342 : SetConstraintStateAddItem(state, tgoid, stmt->deferred);
5961 : }
5962 : }
5963 : }
5964 :
5965 : /*
5966 : * SQL99 requires that when a constraint is set to IMMEDIATE, any deferred
5967 : * checks against that constraint must be made when the SET CONSTRAINTS
5968 : * command is executed -- i.e. the effects of the SET CONSTRAINTS command
5969 : * apply retroactively. We've updated the constraints state, so scan the
5970 : * list of previously deferred events to fire any that have now become
5971 : * immediate.
5972 : *
5973 : * Obviously, if this was SET ... DEFERRED then it can't have converted
5974 : * any unfired events to immediate, so we need do nothing in that case.
5975 : */
5976 102 : if (!stmt->deferred)
5977 : {
5978 34 : AfterTriggerEventList *events = &afterTriggers.events;
5979 34 : bool snapshot_set = false;
5980 :
5981 34 : while (afterTriggerMarkEvents(events, NULL, true))
5982 : {
5983 16 : CommandId firing_id = afterTriggers.firing_counter++;
5984 :
5985 : /*
5986 : * Make sure a snapshot has been established in case trigger
5987 : * functions need one. Note that we avoid setting a snapshot if
5988 : * we don't find at least one trigger that has to be fired now.
5989 : * This is so that BEGIN; SET CONSTRAINTS ...; SET TRANSACTION
5990 : * ISOLATION LEVEL SERIALIZABLE; ... works properly. (If we are
5991 : * at the start of a transaction it's not possible for any trigger
5992 : * events to be queued yet.)
5993 : */
5994 16 : if (!snapshot_set)
5995 : {
5996 16 : PushActiveSnapshot(GetTransactionSnapshot());
5997 16 : snapshot_set = true;
5998 : }
5999 :
6000 : /*
6001 : * We can delete fired events if we are at top transaction level,
6002 : * but we'd better not if inside a subtransaction, since the
6003 : * subtransaction could later get rolled back.
6004 : */
6005 0 : if (afterTriggerInvokeEvents(events, firing_id, NULL,
6006 16 : !IsSubTransaction()))
6007 0 : break; /* all fired */
6008 : }
6009 :
6010 18 : if (snapshot_set)
6011 0 : PopActiveSnapshot();
6012 : }
6013 86 : }
6014 :
6015 : /* ----------
6016 : * AfterTriggerPendingOnRel()
6017 : * Test to see if there are any pending after-trigger events for rel.
6018 : *
6019 : * This is used by TRUNCATE, CLUSTER, ALTER TABLE, etc to detect whether
6020 : * it is unsafe to perform major surgery on a relation. Note that only
6021 : * local pending events are examined. We assume that having exclusive lock
6022 : * on a rel guarantees there are no unserviced events in other backends ---
6023 : * but having a lock does not prevent there being such events in our own.
6024 : *
6025 : * In some scenarios it'd be reasonable to remove pending events (more
6026 : * specifically, mark them DONE by the current subxact) but without a lot
6027 : * of knowledge of the trigger semantics we can't do this in general.
6028 : * ----------
6029 : */
6030 : bool
6031 140572 : AfterTriggerPendingOnRel(Oid relid)
6032 : {
6033 : AfterTriggerEvent event;
6034 : AfterTriggerEventChunk *chunk;
6035 : int depth;
6036 :
6037 : /* Scan queued events */
6038 140608 : for_each_event_chunk(event, chunk, afterTriggers.events)
6039 : {
6040 36 : AfterTriggerShared evtshared = GetTriggerSharedData(event);
6041 :
6042 : /*
6043 : * We can ignore completed events. (Even if a DONE flag is rolled
6044 : * back by subxact abort, it's OK because the effects of the TRUNCATE
6045 : * or whatever must get rolled back too.)
6046 : */
6047 36 : if (event->ate_flags & AFTER_TRIGGER_DONE)
6048 0 : continue;
6049 :
6050 36 : if (evtshared->ats_relid == relid)
6051 18 : return true;
6052 : }
6053 :
6054 : /*
6055 : * Also scan events queued by incomplete queries. This could only matter
6056 : * if TRUNCATE/etc is executed by a function or trigger within an updating
6057 : * query on the same relation, which is pretty perverse, but let's check.
6058 : */
6059 140554 : for (depth = 0; depth <= afterTriggers.query_depth && depth < afterTriggers.maxquerydepth; depth++)
6060 : {
6061 0 : for_each_event_chunk(event, chunk, afterTriggers.query_stack[depth].events)
6062 : {
6063 0 : AfterTriggerShared evtshared = GetTriggerSharedData(event);
6064 :
6065 0 : if (event->ate_flags & AFTER_TRIGGER_DONE)
6066 0 : continue;
6067 :
6068 0 : if (evtshared->ats_relid == relid)
6069 0 : return true;
6070 : }
6071 : }
6072 :
6073 140554 : return false;
6074 : }
6075 :
6076 : /* ----------
6077 : * AfterTriggerSaveEvent()
6078 : *
6079 : * Called by ExecA[RS]...Triggers() to queue up the triggers that should
6080 : * be fired for an event.
6081 : *
6082 : * NOTE: this is called whenever there are any triggers associated with
6083 : * the event (even if they are disabled). This function decides which
6084 : * triggers actually need to be queued. It is also called after each row,
6085 : * even if there are no triggers for that event, if there are any AFTER
6086 : * STATEMENT triggers for the statement which use transition tables, so that
6087 : * the transition tuplestores can be built. Furthermore, if the transition
6088 : * capture is happening for UPDATEd rows being moved to another partition due
6089 : * to the partition-key being changed, then this function is called once when
6090 : * the row is deleted (to capture OLD row), and once when the row is inserted
6091 : * into another partition (to capture NEW row). This is done separately because
6092 : * DELETE and INSERT happen on different tables.
6093 : *
6094 : * Transition tuplestores are built now, rather than when events are pulled
6095 : * off of the queue because AFTER ROW triggers are allowed to select from the
6096 : * transition tables for the statement.
6097 : *
6098 : * This contains special support to queue the update events for the case where
6099 : * a partitioned table undergoing a cross-partition update may have foreign
6100 : * keys pointing into it. Normally, a partitioned table's row triggers are
6101 : * not fired because the leaf partition(s) which are modified as a result of
6102 : * the operation on the partitioned table contain the same triggers which are
6103 : * fired instead. But that general scheme can cause problematic behavior with
6104 : * foreign key triggers during cross-partition updates, which are implemented
6105 : * as DELETE on the source partition followed by INSERT into the destination
6106 : * partition. Specifically, firing DELETE triggers would lead to the wrong
6107 : * foreign key action to be enforced considering that the original command is
6108 : * UPDATE; in this case, this function is called with relinfo as the
6109 : * partitioned table, and src_partinfo and dst_partinfo referring to the
6110 : * source and target leaf partitions, respectively.
6111 : *
6112 : * is_crosspart_update is true either when a DELETE event is fired on the
6113 : * source partition (which is to be ignored) or an UPDATE event is fired on
6114 : * the root partitioned table.
6115 : * ----------
6116 : */
6117 : static void
6118 76654 : AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
6119 : ResultRelInfo *src_partinfo,
6120 : ResultRelInfo *dst_partinfo,
6121 : int event, bool row_trigger,
6122 : TupleTableSlot *oldslot, TupleTableSlot *newslot,
6123 : List *recheckIndexes, Bitmapset *modifiedCols,
6124 : TransitionCaptureState *transition_capture,
6125 : bool is_crosspart_update)
6126 : {
6127 76654 : Relation rel = relinfo->ri_RelationDesc;
6128 76654 : TriggerDesc *trigdesc = relinfo->ri_TrigDesc;
6129 : AfterTriggerEventData new_event;
6130 : AfterTriggerSharedData new_shared;
6131 76654 : char relkind = rel->rd_rel->relkind;
6132 : int tgtype_event;
6133 : int tgtype_level;
6134 : int i;
6135 76654 : Tuplestorestate *fdw_tuplestore = NULL;
6136 :
6137 : /*
6138 : * Check state. We use a normal test not Assert because it is possible to
6139 : * reach here in the wrong state given misconfigured RI triggers, in
6140 : * particular deferring a cascade action trigger.
6141 : */
6142 76654 : if (afterTriggers.query_depth < 0)
6143 0 : elog(ERROR, "AfterTriggerSaveEvent() called outside of query");
6144 :
6145 : /* Be sure we have enough space to record events at this query depth. */
6146 76654 : if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
6147 6160 : AfterTriggerEnlargeQueryState();
6148 :
6149 : /*
6150 : * If the directly named relation has any triggers with transition tables,
6151 : * then we need to capture transition tuples.
6152 : */
6153 76654 : if (row_trigger && transition_capture != NULL)
6154 : {
6155 65814 : TupleTableSlot *original_insert_tuple = transition_capture->tcs_original_insert_tuple;
6156 :
6157 : /*
6158 : * Capture the old tuple in the appropriate transition table based on
6159 : * the event.
6160 : */
6161 65814 : if (!TupIsNull(oldslot))
6162 : {
6163 : Tuplestorestate *old_tuplestore;
6164 :
6165 5412 : old_tuplestore = GetAfterTriggersTransitionTable(event,
6166 : oldslot,
6167 : NULL,
6168 : transition_capture);
6169 5412 : TransitionTableAddTuple(estate, transition_capture, relinfo,
6170 : oldslot, NULL, old_tuplestore);
6171 : }
6172 :
6173 : /*
6174 : * Capture the new tuple in the appropriate transition table based on
6175 : * the event.
6176 : */
6177 65814 : if (!TupIsNull(newslot))
6178 : {
6179 : Tuplestorestate *new_tuplestore;
6180 :
6181 60714 : new_tuplestore = GetAfterTriggersTransitionTable(event,
6182 : NULL,
6183 : newslot,
6184 : transition_capture);
6185 60714 : TransitionTableAddTuple(estate, transition_capture, relinfo,
6186 : newslot, original_insert_tuple, new_tuplestore);
6187 : }
6188 :
6189 : /*
6190 : * If transition tables are the only reason we're here, return. As
6191 : * mentioned above, we can also be here during update tuple routing in
6192 : * presence of transition tables, in which case this function is
6193 : * called separately for OLD and NEW, so we expect exactly one of them
6194 : * to be NULL.
6195 : */
6196 65814 : if (trigdesc == NULL ||
6197 65574 : (event == TRIGGER_EVENT_DELETE && !trigdesc->trig_delete_after_row) ||
6198 60594 : (event == TRIGGER_EVENT_INSERT && !trigdesc->trig_insert_after_row) ||
6199 354 : (event == TRIGGER_EVENT_UPDATE && !trigdesc->trig_update_after_row) ||
6200 36 : (event == TRIGGER_EVENT_UPDATE && (TupIsNull(oldslot) ^ TupIsNull(newslot))))
6201 65700 : return;
6202 : }
6203 :
6204 : /*
6205 : * We normally don't see partitioned tables here for row level triggers
6206 : * except in the special case of a cross-partition update. In that case,
6207 : * nodeModifyTable.c:ExecCrossPartitionUpdateForeignKey() calls here to
6208 : * queue an update event on the root target partitioned table, also
6209 : * passing the source and destination partitions and their tuples.
6210 : */
6211 : Assert(!row_trigger ||
6212 : rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE ||
6213 : (is_crosspart_update &&
6214 : TRIGGER_FIRED_BY_UPDATE(event) &&
6215 : src_partinfo != NULL && dst_partinfo != NULL));
6216 :
6217 : /*
6218 : * Validate the event code and collect the associated tuple CTIDs.
6219 : *
6220 : * The event code will be used both as a bitmask and an array offset, so
6221 : * validation is important to make sure we don't walk off the edge of our
6222 : * arrays.
6223 : *
6224 : * Also, if we're considering statement-level triggers, check whether we
6225 : * already queued a set of them for this event, and cancel the prior set
6226 : * if so. This preserves the behavior that statement-level triggers fire
6227 : * just once per statement and fire after row-level triggers.
6228 : */
6229 10954 : switch (event)
6230 : {
6231 5782 : case TRIGGER_EVENT_INSERT:
6232 5782 : tgtype_event = TRIGGER_TYPE_INSERT;
6233 5782 : if (row_trigger)
6234 : {
6235 : Assert(oldslot == NULL);
6236 : Assert(newslot != NULL);
6237 5340 : ItemPointerCopy(&(newslot->tts_tid), &(new_event.ate_ctid1));
6238 5340 : ItemPointerSetInvalid(&(new_event.ate_ctid2));
6239 : }
6240 : else
6241 : {
6242 : Assert(oldslot == NULL);
6243 : Assert(newslot == NULL);
6244 442 : ItemPointerSetInvalid(&(new_event.ate_ctid1));
6245 442 : ItemPointerSetInvalid(&(new_event.ate_ctid2));
6246 442 : cancel_prior_stmt_triggers(RelationGetRelid(rel),
6247 : CMD_INSERT, event);
6248 : }
6249 5782 : break;
6250 1406 : case TRIGGER_EVENT_DELETE:
6251 1406 : tgtype_event = TRIGGER_TYPE_DELETE;
6252 1406 : if (row_trigger)
6253 : {
6254 : Assert(oldslot != NULL);
6255 : Assert(newslot == NULL);
6256 1170 : ItemPointerCopy(&(oldslot->tts_tid), &(new_event.ate_ctid1));
6257 1170 : ItemPointerSetInvalid(&(new_event.ate_ctid2));
6258 : }
6259 : else
6260 : {
6261 : Assert(oldslot == NULL);
6262 : Assert(newslot == NULL);
6263 236 : ItemPointerSetInvalid(&(new_event.ate_ctid1));
6264 236 : ItemPointerSetInvalid(&(new_event.ate_ctid2));
6265 236 : cancel_prior_stmt_triggers(RelationGetRelid(rel),
6266 : CMD_DELETE, event);
6267 : }
6268 1406 : break;
6269 3758 : case TRIGGER_EVENT_UPDATE:
6270 3758 : tgtype_event = TRIGGER_TYPE_UPDATE;
6271 3758 : if (row_trigger)
6272 : {
6273 : Assert(oldslot != NULL);
6274 : Assert(newslot != NULL);
6275 3350 : ItemPointerCopy(&(oldslot->tts_tid), &(new_event.ate_ctid1));
6276 3350 : ItemPointerCopy(&(newslot->tts_tid), &(new_event.ate_ctid2));
6277 :
6278 : /*
6279 : * Also remember the OIDs of partitions to fetch these tuples
6280 : * out of later in AfterTriggerExecute().
6281 : */
6282 3350 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6283 : {
6284 : Assert(src_partinfo != NULL && dst_partinfo != NULL);
6285 282 : new_event.ate_src_part =
6286 282 : RelationGetRelid(src_partinfo->ri_RelationDesc);
6287 282 : new_event.ate_dst_part =
6288 282 : RelationGetRelid(dst_partinfo->ri_RelationDesc);
6289 : }
6290 : }
6291 : else
6292 : {
6293 : Assert(oldslot == NULL);
6294 : Assert(newslot == NULL);
6295 408 : ItemPointerSetInvalid(&(new_event.ate_ctid1));
6296 408 : ItemPointerSetInvalid(&(new_event.ate_ctid2));
6297 408 : cancel_prior_stmt_triggers(RelationGetRelid(rel),
6298 : CMD_UPDATE, event);
6299 : }
6300 3758 : break;
6301 8 : case TRIGGER_EVENT_TRUNCATE:
6302 8 : tgtype_event = TRIGGER_TYPE_TRUNCATE;
6303 : Assert(oldslot == NULL);
6304 : Assert(newslot == NULL);
6305 8 : ItemPointerSetInvalid(&(new_event.ate_ctid1));
6306 8 : ItemPointerSetInvalid(&(new_event.ate_ctid2));
6307 8 : break;
6308 0 : default:
6309 0 : elog(ERROR, "invalid after-trigger event code: %d", event);
6310 : tgtype_event = 0; /* keep compiler quiet */
6311 : break;
6312 : }
6313 :
6314 : /* Determine flags */
6315 10954 : if (!(relkind == RELKIND_FOREIGN_TABLE && row_trigger))
6316 : {
6317 10898 : if (row_trigger && event == TRIGGER_EVENT_UPDATE)
6318 : {
6319 3330 : if (relkind == RELKIND_PARTITIONED_TABLE)
6320 282 : new_event.ate_flags = AFTER_TRIGGER_CP_UPDATE;
6321 : else
6322 3048 : new_event.ate_flags = AFTER_TRIGGER_2CTID;
6323 : }
6324 : else
6325 7568 : new_event.ate_flags = AFTER_TRIGGER_1CTID;
6326 : }
6327 :
6328 : /* else, we'll initialize ate_flags for each trigger */
6329 :
6330 10954 : tgtype_level = (row_trigger ? TRIGGER_TYPE_ROW : TRIGGER_TYPE_STATEMENT);
6331 :
6332 : /*
6333 : * Must convert/copy the source and destination partition tuples into the
6334 : * root partitioned table's format/slot, because the processing in the
6335 : * loop below expects both oldslot and newslot tuples to be in that form.
6336 : */
6337 10954 : if (row_trigger && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6338 : {
6339 : TupleTableSlot *rootslot;
6340 : TupleConversionMap *map;
6341 :
6342 282 : rootslot = ExecGetTriggerOldSlot(estate, relinfo);
6343 282 : map = ExecGetChildToRootMap(src_partinfo);
6344 282 : if (map)
6345 36 : oldslot = execute_attr_map_slot(map->attrMap,
6346 : oldslot,
6347 : rootslot);
6348 : else
6349 246 : oldslot = ExecCopySlot(rootslot, oldslot);
6350 :
6351 282 : rootslot = ExecGetTriggerNewSlot(estate, relinfo);
6352 282 : map = ExecGetChildToRootMap(dst_partinfo);
6353 282 : if (map)
6354 36 : newslot = execute_attr_map_slot(map->attrMap,
6355 : newslot,
6356 : rootslot);
6357 : else
6358 246 : newslot = ExecCopySlot(rootslot, newslot);
6359 : }
6360 :
6361 50208 : for (i = 0; i < trigdesc->numtriggers; i++)
6362 : {
6363 39254 : Trigger *trigger = &trigdesc->triggers[i];
6364 :
6365 39254 : if (!TRIGGER_TYPE_MATCHES(trigger->tgtype,
6366 : tgtype_level,
6367 : TRIGGER_TYPE_AFTER,
6368 : tgtype_event))
6369 25284 : continue;
6370 13970 : if (!TriggerEnabled(estate, relinfo, trigger, event,
6371 : modifiedCols, oldslot, newslot))
6372 422 : continue;
6373 :
6374 13548 : if (relkind == RELKIND_FOREIGN_TABLE && row_trigger)
6375 : {
6376 58 : if (fdw_tuplestore == NULL)
6377 : {
6378 50 : fdw_tuplestore = GetCurrentFDWTuplestore();
6379 50 : new_event.ate_flags = AFTER_TRIGGER_FDW_FETCH;
6380 : }
6381 : else
6382 : /* subsequent event for the same tuple */
6383 8 : new_event.ate_flags = AFTER_TRIGGER_FDW_REUSE;
6384 : }
6385 :
6386 : /*
6387 : * If the trigger is a foreign key enforcement trigger, there are
6388 : * certain cases where we can skip queueing the event because we can
6389 : * tell by inspection that the FK constraint will still pass. There
6390 : * are also some cases during cross-partition updates of a partitioned
6391 : * table where queuing the event can be skipped.
6392 : */
6393 13548 : if (TRIGGER_FIRED_BY_UPDATE(event) || TRIGGER_FIRED_BY_DELETE(event))
6394 : {
6395 6586 : switch (RI_FKey_trigger_type(trigger->tgfoid))
6396 : {
6397 2578 : case RI_TRIGGER_PK:
6398 :
6399 : /*
6400 : * For cross-partitioned updates of partitioned PK table,
6401 : * skip the event fired by the component delete on the
6402 : * source leaf partition unless the constraint originates
6403 : * in the partition itself (!tgisclone), because the
6404 : * update event that will be fired on the root
6405 : * (partitioned) target table will be used to perform the
6406 : * necessary foreign key enforcement action.
6407 : */
6408 2578 : if (is_crosspart_update &&
6409 498 : TRIGGER_FIRED_BY_DELETE(event) &&
6410 264 : trigger->tgisclone)
6411 246 : continue;
6412 :
6413 : /* Update or delete on trigger's PK table */
6414 2332 : if (!RI_FKey_pk_upd_check_required(trigger, rel,
6415 : oldslot, newslot))
6416 : {
6417 : /* skip queuing this event */
6418 542 : continue;
6419 : }
6420 1790 : break;
6421 :
6422 1194 : case RI_TRIGGER_FK:
6423 :
6424 : /*
6425 : * Update on trigger's FK table. We can skip the update
6426 : * event fired on a partitioned table during a
6427 : * cross-partition of that table, because the insert event
6428 : * that is fired on the destination leaf partition would
6429 : * suffice to perform the necessary foreign key check.
6430 : * Moreover, RI_FKey_fk_upd_check_required() expects to be
6431 : * passed a tuple that contains system attributes, most of
6432 : * which are not present in the virtual slot belonging to
6433 : * a partitioned table.
6434 : */
6435 1194 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ||
6436 1080 : !RI_FKey_fk_upd_check_required(trigger, rel,
6437 : oldslot, newslot))
6438 : {
6439 : /* skip queuing this event */
6440 728 : continue;
6441 : }
6442 466 : break;
6443 :
6444 2814 : case RI_TRIGGER_NONE:
6445 :
6446 : /*
6447 : * Not an FK trigger. No need to queue the update event
6448 : * fired during a cross-partitioned update of a
6449 : * partitioned table, because the same row trigger must be
6450 : * present in the leaf partition(s) that are affected as
6451 : * part of this update and the events fired on them are
6452 : * queued instead.
6453 : */
6454 2814 : if (row_trigger &&
6455 2134 : rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
6456 30 : continue;
6457 2784 : break;
6458 : }
6459 : }
6460 :
6461 : /*
6462 : * If the trigger is a deferred unique constraint check trigger, only
6463 : * queue it if the unique constraint was potentially violated, which
6464 : * we know from index insertion time.
6465 : */
6466 12002 : if (trigger->tgfoid == F_UNIQUE_KEY_RECHECK)
6467 : {
6468 210 : if (!list_member_oid(recheckIndexes, trigger->tgconstrindid))
6469 88 : continue; /* Uniqueness definitely not violated */
6470 : }
6471 :
6472 : /*
6473 : * Fill in event structure and add it to the current query's queue.
6474 : * Note we set ats_table to NULL whenever this trigger doesn't use
6475 : * transition tables, to improve sharability of the shared event data.
6476 : */
6477 11914 : new_shared.ats_event =
6478 23828 : (event & TRIGGER_EVENT_OPMASK) |
6479 11914 : (row_trigger ? TRIGGER_EVENT_ROW : 0) |
6480 11914 : (trigger->tgdeferrable ? AFTER_TRIGGER_DEFERRABLE : 0) |
6481 11914 : (trigger->tginitdeferred ? AFTER_TRIGGER_INITDEFERRED : 0);
6482 11914 : new_shared.ats_tgoid = trigger->tgoid;
6483 11914 : new_shared.ats_relid = RelationGetRelid(rel);
6484 11914 : new_shared.ats_rolid = GetUserId();
6485 11914 : new_shared.ats_firing_id = 0;
6486 11914 : if ((trigger->tgoldtable || trigger->tgnewtable) &&
6487 : transition_capture != NULL)
6488 636 : new_shared.ats_table = transition_capture->tcs_private;
6489 : else
6490 11278 : new_shared.ats_table = NULL;
6491 11914 : new_shared.ats_modifiedcols = modifiedCols;
6492 :
6493 11914 : afterTriggerAddEvent(&afterTriggers.query_stack[afterTriggers.query_depth].events,
6494 : &new_event, &new_shared);
6495 : }
6496 :
6497 : /*
6498 : * Finally, spool any foreign tuple(s). The tuplestore squashes them to
6499 : * minimal tuples, so this loses any system columns. The executor lost
6500 : * those columns before us, for an unrelated reason, so this is fine.
6501 : */
6502 10954 : if (fdw_tuplestore)
6503 : {
6504 50 : if (oldslot != NULL)
6505 32 : tuplestore_puttupleslot(fdw_tuplestore, oldslot);
6506 50 : if (newslot != NULL)
6507 36 : tuplestore_puttupleslot(fdw_tuplestore, newslot);
6508 : }
6509 : }
6510 :
6511 : /*
6512 : * Detect whether we already queued BEFORE STATEMENT triggers for the given
6513 : * relation + operation, and set the flag so the next call will report "true".
6514 : */
6515 : static bool
6516 510 : before_stmt_triggers_fired(Oid relid, CmdType cmdType)
6517 : {
6518 : bool result;
6519 : AfterTriggersTableData *table;
6520 :
6521 : /* Check state, like AfterTriggerSaveEvent. */
6522 510 : if (afterTriggers.query_depth < 0)
6523 0 : elog(ERROR, "before_stmt_triggers_fired() called outside of query");
6524 :
6525 : /* Be sure we have enough space to record events at this query depth. */
6526 510 : if (afterTriggers.query_depth >= afterTriggers.maxquerydepth)
6527 336 : AfterTriggerEnlargeQueryState();
6528 :
6529 : /*
6530 : * We keep this state in the AfterTriggersTableData that also holds
6531 : * transition tables for the relation + operation. In this way, if we are
6532 : * forced to make a new set of transition tables because more tuples get
6533 : * entered after we've already fired triggers, we will allow a new set of
6534 : * statement triggers to get queued.
6535 : */
6536 510 : table = GetAfterTriggersTableData(relid, cmdType);
6537 510 : result = table->before_trig_done;
6538 510 : table->before_trig_done = true;
6539 510 : return result;
6540 : }
6541 :
6542 : /*
6543 : * If we previously queued a set of AFTER STATEMENT triggers for the given
6544 : * relation + operation, and they've not been fired yet, cancel them. The
6545 : * caller will queue a fresh set that's after any row-level triggers that may
6546 : * have been queued by the current sub-statement, preserving (as much as
6547 : * possible) the property that AFTER ROW triggers fire before AFTER STATEMENT
6548 : * triggers, and that the latter only fire once. This deals with the
6549 : * situation where several FK enforcement triggers sequentially queue triggers
6550 : * for the same table into the same trigger query level. We can't fully
6551 : * prevent odd behavior though: if there are AFTER ROW triggers taking
6552 : * transition tables, we don't want to change the transition tables once the
6553 : * first such trigger has seen them. In such a case, any additional events
6554 : * will result in creating new transition tables and allowing new firings of
6555 : * statement triggers.
6556 : *
6557 : * This also saves the current event list location so that a later invocation
6558 : * of this function can cheaply find the triggers we're about to queue and
6559 : * cancel them.
6560 : */
6561 : static void
6562 1086 : cancel_prior_stmt_triggers(Oid relid, CmdType cmdType, int tgevent)
6563 : {
6564 : AfterTriggersTableData *table;
6565 1086 : AfterTriggersQueryData *qs = &afterTriggers.query_stack[afterTriggers.query_depth];
6566 :
6567 : /*
6568 : * We keep this state in the AfterTriggersTableData that also holds
6569 : * transition tables for the relation + operation. In this way, if we are
6570 : * forced to make a new set of transition tables because more tuples get
6571 : * entered after we've already fired triggers, we will allow a new set of
6572 : * statement triggers to get queued without canceling the old ones.
6573 : */
6574 1086 : table = GetAfterTriggersTableData(relid, cmdType);
6575 :
6576 1086 : if (table->after_trig_done)
6577 : {
6578 : /*
6579 : * We want to start scanning from the tail location that existed just
6580 : * before we inserted any statement triggers. But the events list
6581 : * might've been entirely empty then, in which case scan from the
6582 : * current head.
6583 : */
6584 : AfterTriggerEvent event;
6585 : AfterTriggerEventChunk *chunk;
6586 :
6587 66 : if (table->after_trig_events.tail)
6588 : {
6589 60 : chunk = table->after_trig_events.tail;
6590 60 : event = (AfterTriggerEvent) table->after_trig_events.tailfree;
6591 : }
6592 : else
6593 : {
6594 6 : chunk = qs->events.head;
6595 6 : event = NULL;
6596 : }
6597 :
6598 96 : for_each_chunk_from(chunk)
6599 : {
6600 66 : if (event == NULL)
6601 6 : event = (AfterTriggerEvent) CHUNK_DATA_START(chunk);
6602 138 : for_each_event_from(event, chunk)
6603 : {
6604 108 : AfterTriggerShared evtshared = GetTriggerSharedData(event);
6605 :
6606 : /*
6607 : * Exit loop when we reach events that aren't AS triggers for
6608 : * the target relation.
6609 : */
6610 108 : if (evtshared->ats_relid != relid)
6611 0 : goto done;
6612 108 : if ((evtshared->ats_event & TRIGGER_EVENT_OPMASK) != tgevent)
6613 0 : goto done;
6614 108 : if (!TRIGGER_FIRED_FOR_STATEMENT(evtshared->ats_event))
6615 36 : goto done;
6616 72 : if (!TRIGGER_FIRED_AFTER(evtshared->ats_event))
6617 0 : goto done;
6618 : /* OK, mark it DONE */
6619 72 : event->ate_flags &= ~AFTER_TRIGGER_IN_PROGRESS;
6620 72 : event->ate_flags |= AFTER_TRIGGER_DONE;
6621 : }
6622 : /* signal we must reinitialize event ptr for next chunk */
6623 30 : event = NULL;
6624 : }
6625 : }
6626 1050 : done:
6627 :
6628 : /* In any case, save current insertion point for next time */
6629 1086 : table->after_trig_done = true;
6630 1086 : table->after_trig_events = qs->events;
6631 1086 : }
6632 :
6633 : /*
6634 : * GUC assign_hook for session_replication_role
6635 : */
6636 : void
6637 3154 : assign_session_replication_role(int newval, void *extra)
6638 : {
6639 : /*
6640 : * Must flush the plan cache when changing replication role; but don't
6641 : * flush unnecessarily.
6642 : */
6643 3154 : if (SessionReplicationRole != newval)
6644 926 : ResetPlanCache();
6645 3154 : }
6646 :
6647 : /*
6648 : * SQL function pg_trigger_depth()
6649 : */
6650 : Datum
6651 90 : pg_trigger_depth(PG_FUNCTION_ARGS)
6652 : {
6653 90 : PG_RETURN_INT32(MyTriggerDepth);
6654 : }
6655 :
6656 : /*
6657 : * Check whether a trigger modified a virtual generated column and replace the
6658 : * value with null if so.
6659 : *
6660 : * We need to check this so that we don't end up storing a non-null value in a
6661 : * virtual generated column.
6662 : *
6663 : * We don't need to check for stored generated columns, since those will be
6664 : * overwritten later anyway.
6665 : */
6666 : static HeapTuple
6667 2048 : check_modified_virtual_generated(TupleDesc tupdesc, HeapTuple tuple)
6668 : {
6669 2048 : if (!(tupdesc->constr && tupdesc->constr->has_generated_virtual))
6670 2030 : return tuple;
6671 :
6672 66 : for (int i = 0; i < tupdesc->natts; i++)
6673 : {
6674 48 : if (TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
6675 : {
6676 18 : if (!heap_attisnull(tuple, i + 1, tupdesc))
6677 : {
6678 12 : int replCol = i + 1;
6679 12 : Datum replValue = 0;
6680 12 : bool replIsnull = true;
6681 :
6682 12 : tuple = heap_modify_tuple_by_cols(tuple, tupdesc, 1, &replCol, &replValue, &replIsnull);
6683 : }
6684 : }
6685 : }
6686 :
6687 18 : return tuple;
6688 : }
|