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