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