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