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