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