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