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