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