PostgreSQL Source Code  git master
event_trigger.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * event_trigger.c
4  * PostgreSQL EVENT TRIGGER support code.
5  *
6  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/backend/commands/event_trigger.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15 
16 #include "access/htup_details.h"
17 #include "access/table.h"
18 #include "access/xact.h"
19 #include "catalog/catalog.h"
20 #include "catalog/dependency.h"
21 #include "catalog/indexing.h"
22 #include "catalog/objectaccess.h"
24 #include "catalog/pg_namespace.h"
25 #include "catalog/pg_opclass.h"
26 #include "catalog/pg_opfamily.h"
27 #include "catalog/pg_proc.h"
28 #include "catalog/pg_trigger.h"
29 #include "catalog/pg_ts_config.h"
30 #include "catalog/pg_type.h"
31 #include "commands/dbcommands.h"
32 #include "commands/event_trigger.h"
33 #include "commands/extension.h"
34 #include "commands/trigger.h"
35 #include "funcapi.h"
36 #include "lib/ilist.h"
37 #include "miscadmin.h"
38 #include "parser/parse_func.h"
39 #include "pgstat.h"
40 #include "tcop/deparse_utility.h"
41 #include "tcop/utility.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/evtcache.h"
45 #include "utils/fmgroids.h"
46 #include "utils/lsyscache.h"
47 #include "utils/memutils.h"
48 #include "utils/rel.h"
49 #include "utils/syscache.h"
50 
51 typedef struct EventTriggerQueryState
52 {
53  /* memory context for this state's objects */
55 
56  /* sql_drop */
59 
60  /* table_rewrite */
61  Oid table_rewrite_oid; /* InvalidOid, or set for table_rewrite
62  * event */
63  int table_rewrite_reason; /* AT_REWRITE reason */
64 
65  /* Support for command collection */
68  List *commandList; /* list of CollectedCommand; see
69  * deparse_utility.h */
72 
74 
75 typedef struct
76 {
77  const char *obtypename;
78  bool supported;
80 
81 typedef enum
82 {
87 
88 /* XXX merge this with ObjectTypeMap? */
90  {"ACCESS METHOD", true},
91  {"AGGREGATE", true},
92  {"CAST", true},
93  {"CONSTRAINT", true},
94  {"COLLATION", true},
95  {"CONVERSION", true},
96  {"DATABASE", false},
97  {"DOMAIN", true},
98  {"EXTENSION", true},
99  {"EVENT TRIGGER", false},
100  {"FOREIGN DATA WRAPPER", true},
101  {"FOREIGN TABLE", true},
102  {"FUNCTION", true},
103  {"INDEX", true},
104  {"LANGUAGE", true},
105  {"MATERIALIZED VIEW", true},
106  {"OPERATOR", true},
107  {"OPERATOR CLASS", true},
108  {"OPERATOR FAMILY", true},
109  {"POLICY", true},
110  {"PROCEDURE", true},
111  {"PUBLICATION", true},
112  {"ROLE", false},
113  {"ROUTINE", true},
114  {"RULE", true},
115  {"SCHEMA", true},
116  {"SEQUENCE", true},
117  {"SERVER", true},
118  {"STATISTICS", true},
119  {"SUBSCRIPTION", true},
120  {"TABLE", true},
121  {"TABLESPACE", false},
122  {"TRANSFORM", true},
123  {"TRIGGER", true},
124  {"TEXT SEARCH CONFIGURATION", true},
125  {"TEXT SEARCH DICTIONARY", true},
126  {"TEXT SEARCH PARSER", true},
127  {"TEXT SEARCH TEMPLATE", true},
128  {"TYPE", true},
129  {"USER MAPPING", true},
130  {"VIEW", true},
131  {NULL, false}
132 };
133 
134 /* Support for dropped objects */
135 typedef struct SQLDropObject
136 {
138  const char *schemaname;
139  const char *objname;
140  const char *objidentity;
141  const char *objecttype;
144  bool original;
145  bool normal;
146  bool istemp;
148 } SQLDropObject;
149 
151  HeapTuple tup,
152  Oid newOwnerId);
155 static void error_duplicate_filter_variable(const char *defname);
156 static Datum filter_list_to_array(List *filterlist);
157 static Oid insert_event_trigger_tuple(const char *trigname, const char *eventname,
158  Oid evtOwner, Oid funcoid, List *tags);
159 static void validate_ddl_tags(const char *filtervar, List *taglist);
160 static void validate_table_rewrite_tags(const char *filtervar, List *taglist);
161 static void EventTriggerInvoke(List *fn_oid_list, EventTriggerData *trigdata);
162 static const char *stringify_grant_objtype(ObjectType objtype);
163 static const char *stringify_adefprivs_objtype(ObjectType objtype);
164 
165 /*
166  * Create an event trigger.
167  */
168 Oid
170 {
171  HeapTuple tuple;
172  Oid funcoid;
173  Oid funcrettype;
174  Oid evtowner = GetUserId();
175  ListCell *lc;
176  List *tags = NULL;
177 
178  /*
179  * It would be nice to allow database owners or even regular users to do
180  * this, but there are obvious privilege escalation risks which would have
181  * to somehow be plugged first.
182  */
183  if (!superuser())
184  ereport(ERROR,
185  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
186  errmsg("permission denied to create event trigger \"%s\"",
187  stmt->trigname),
188  errhint("Must be superuser to create an event trigger.")));
189 
190  /* Validate event name. */
191  if (strcmp(stmt->eventname, "ddl_command_start") != 0 &&
192  strcmp(stmt->eventname, "ddl_command_end") != 0 &&
193  strcmp(stmt->eventname, "sql_drop") != 0 &&
194  strcmp(stmt->eventname, "table_rewrite") != 0)
195  ereport(ERROR,
196  (errcode(ERRCODE_SYNTAX_ERROR),
197  errmsg("unrecognized event name \"%s\"",
198  stmt->eventname)));
199 
200  /* Validate filter conditions. */
201  foreach(lc, stmt->whenclause)
202  {
203  DefElem *def = (DefElem *) lfirst(lc);
204 
205  if (strcmp(def->defname, "tag") == 0)
206  {
207  if (tags != NULL)
209  tags = (List *) def->arg;
210  }
211  else
212  ereport(ERROR,
213  (errcode(ERRCODE_SYNTAX_ERROR),
214  errmsg("unrecognized filter variable \"%s\"", def->defname)));
215  }
216 
217  /* Validate tag list, if any. */
218  if ((strcmp(stmt->eventname, "ddl_command_start") == 0 ||
219  strcmp(stmt->eventname, "ddl_command_end") == 0 ||
220  strcmp(stmt->eventname, "sql_drop") == 0)
221  && tags != NULL)
222  validate_ddl_tags("tag", tags);
223  else if (strcmp(stmt->eventname, "table_rewrite") == 0
224  && tags != NULL)
225  validate_table_rewrite_tags("tag", tags);
226 
227  /*
228  * Give user a nice error message if an event trigger of the same name
229  * already exists.
230  */
232  if (HeapTupleIsValid(tuple))
233  ereport(ERROR,
235  errmsg("event trigger \"%s\" already exists",
236  stmt->trigname)));
237 
238  /* Find and validate the trigger function. */
239  funcoid = LookupFuncName(stmt->funcname, 0, NULL, false);
240  funcrettype = get_func_rettype(funcoid);
241  if (funcrettype != EVTTRIGGEROID)
242  ereport(ERROR,
243  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
244  errmsg("function %s must return type %s",
245  NameListToString(stmt->funcname), "event_trigger")));
246 
247  /* Insert catalog entries. */
248  return insert_event_trigger_tuple(stmt->trigname, stmt->eventname,
249  evtowner, funcoid, tags);
250 }
251 
252 /*
253  * Validate DDL command tags.
254  */
255 static void
256 validate_ddl_tags(const char *filtervar, List *taglist)
257 {
258  ListCell *lc;
259 
260  foreach(lc, taglist)
261  {
262  const char *tag = strVal(lfirst(lc));
264 
265  result = check_ddl_tag(tag);
267  ereport(ERROR,
268  (errcode(ERRCODE_SYNTAX_ERROR),
269  errmsg("filter value \"%s\" not recognized for filter variable \"%s\"",
270  tag, filtervar)));
272  ereport(ERROR,
273  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
274  /* translator: %s represents an SQL statement name */
275  errmsg("event triggers are not supported for %s",
276  tag)));
277  }
278 }
279 
281 check_ddl_tag(const char *tag)
282 {
283  const char *obtypename;
284  const event_trigger_support_data *etsd;
285 
286  /*
287  * Handle some idiosyncratic special cases.
288  */
289  if (pg_strcasecmp(tag, "CREATE TABLE AS") == 0 ||
290  pg_strcasecmp(tag, "SELECT INTO") == 0 ||
291  pg_strcasecmp(tag, "REFRESH MATERIALIZED VIEW") == 0 ||
292  pg_strcasecmp(tag, "ALTER DEFAULT PRIVILEGES") == 0 ||
293  pg_strcasecmp(tag, "ALTER LARGE OBJECT") == 0 ||
294  pg_strcasecmp(tag, "COMMENT") == 0 ||
295  pg_strcasecmp(tag, "GRANT") == 0 ||
296  pg_strcasecmp(tag, "REVOKE") == 0 ||
297  pg_strcasecmp(tag, "DROP OWNED") == 0 ||
298  pg_strcasecmp(tag, "IMPORT FOREIGN SCHEMA") == 0 ||
299  pg_strcasecmp(tag, "SECURITY LABEL") == 0)
301 
302  /*
303  * Otherwise, command should be CREATE, ALTER, or DROP.
304  */
305  if (pg_strncasecmp(tag, "CREATE ", 7) == 0)
306  obtypename = tag + 7;
307  else if (pg_strncasecmp(tag, "ALTER ", 6) == 0)
308  obtypename = tag + 6;
309  else if (pg_strncasecmp(tag, "DROP ", 5) == 0)
310  obtypename = tag + 5;
311  else
313 
314  /*
315  * ...and the object type should be something recognizable.
316  */
317  for (etsd = event_trigger_support; etsd->obtypename != NULL; etsd++)
318  if (pg_strcasecmp(etsd->obtypename, obtypename) == 0)
319  break;
320  if (etsd->obtypename == NULL)
322  if (!etsd->supported)
325 }
326 
327 /*
328  * Validate DDL command tags for event table_rewrite.
329  */
330 static void
331 validate_table_rewrite_tags(const char *filtervar, List *taglist)
332 {
333  ListCell *lc;
334 
335  foreach(lc, taglist)
336  {
337  const char *tag = strVal(lfirst(lc));
339 
340  result = check_table_rewrite_ddl_tag(tag);
342  ereport(ERROR,
343  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
344  /* translator: %s represents an SQL statement name */
345  errmsg("event triggers are not supported for %s",
346  tag)));
347  }
348 }
349 
352 {
353  if (pg_strcasecmp(tag, "ALTER TABLE") == 0 ||
354  pg_strcasecmp(tag, "ALTER TYPE") == 0)
356 
358 }
359 
360 /*
361  * Complain about a duplicate filter variable.
362  */
363 static void
365 {
366  ereport(ERROR,
367  (errcode(ERRCODE_SYNTAX_ERROR),
368  errmsg("filter variable \"%s\" specified more than once",
369  defname)));
370 }
371 
372 /*
373  * Insert the new pg_event_trigger row and record dependencies.
374  */
375 static Oid
376 insert_event_trigger_tuple(const char *trigname, const char *eventname, Oid evtOwner,
377  Oid funcoid, List *taglist)
378 {
379  Relation tgrel;
380  Oid trigoid;
381  HeapTuple tuple;
382  Datum values[Natts_pg_trigger];
383  bool nulls[Natts_pg_trigger];
384  NameData evtnamedata,
385  evteventdata;
386  ObjectAddress myself,
387  referenced;
388 
389  /* Open pg_event_trigger. */
390  tgrel = table_open(EventTriggerRelationId, RowExclusiveLock);
391 
392  /* Build the new pg_trigger tuple. */
394  Anum_pg_event_trigger_oid);
395  values[Anum_pg_event_trigger_oid - 1] = ObjectIdGetDatum(trigoid);
396  memset(nulls, false, sizeof(nulls));
397  namestrcpy(&evtnamedata, trigname);
398  values[Anum_pg_event_trigger_evtname - 1] = NameGetDatum(&evtnamedata);
399  namestrcpy(&evteventdata, eventname);
400  values[Anum_pg_event_trigger_evtevent - 1] = NameGetDatum(&evteventdata);
401  values[Anum_pg_event_trigger_evtowner - 1] = ObjectIdGetDatum(evtOwner);
402  values[Anum_pg_event_trigger_evtfoid - 1] = ObjectIdGetDatum(funcoid);
403  values[Anum_pg_event_trigger_evtenabled - 1] =
405  if (taglist == NIL)
406  nulls[Anum_pg_event_trigger_evttags - 1] = true;
407  else
408  values[Anum_pg_event_trigger_evttags - 1] =
409  filter_list_to_array(taglist);
410 
411  /* Insert heap tuple. */
412  tuple = heap_form_tuple(tgrel->rd_att, values, nulls);
413  CatalogTupleInsert(tgrel, tuple);
414  heap_freetuple(tuple);
415 
416  /* Depend on owner. */
417  recordDependencyOnOwner(EventTriggerRelationId, trigoid, evtOwner);
418 
419  /* Depend on event trigger function. */
420  myself.classId = EventTriggerRelationId;
421  myself.objectId = trigoid;
422  myself.objectSubId = 0;
423  referenced.classId = ProcedureRelationId;
424  referenced.objectId = funcoid;
425  referenced.objectSubId = 0;
426  recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
427 
428  /* Depend on extension, if any. */
429  recordDependencyOnCurrentExtension(&myself, false);
430 
431  /* Post creation hook for new event trigger */
432  InvokeObjectPostCreateHook(EventTriggerRelationId, trigoid, 0);
433 
434  /* Close pg_event_trigger. */
436 
437  return trigoid;
438 }
439 
440 /*
441  * In the parser, a clause like WHEN tag IN ('cmd1', 'cmd2') is represented
442  * by a DefElem whose value is a List of String nodes; in the catalog, we
443  * store the list of strings as a text array. This function transforms the
444  * former representation into the latter one.
445  *
446  * For cleanliness, we store command tags in the catalog as text. It's
447  * possible (although not currently anticipated) that we might have
448  * a case-sensitive filter variable in the future, in which case this would
449  * need some further adjustment.
450  */
451 static Datum
453 {
454  ListCell *lc;
455  Datum *data;
456  int i = 0,
457  l = list_length(filterlist);
458 
459  data = (Datum *) palloc(l * sizeof(Datum));
460 
461  foreach(lc, filterlist)
462  {
463  const char *value = strVal(lfirst(lc));
464  char *result,
465  *p;
466 
467  result = pstrdup(value);
468  for (p = result; *p; p++)
469  *p = pg_ascii_toupper((unsigned char) *p);
470  data[i++] = PointerGetDatum(cstring_to_text(result));
471  pfree(result);
472  }
473 
474  return PointerGetDatum(construct_array(data, l, TEXTOID, -1, false, 'i'));
475 }
476 
477 /*
478  * Guts of event trigger deletion.
479  */
480 void
482 {
483  Relation tgrel;
484  HeapTuple tup;
485 
486  tgrel = table_open(EventTriggerRelationId, RowExclusiveLock);
487 
489  if (!HeapTupleIsValid(tup))
490  elog(ERROR, "cache lookup failed for event trigger %u", trigOid);
491 
492  CatalogTupleDelete(tgrel, &tup->t_self);
493 
494  ReleaseSysCache(tup);
495 
497 }
498 
499 /*
500  * ALTER EVENT TRIGGER foo ENABLE|DISABLE|ENABLE ALWAYS|REPLICA
501  */
502 Oid
504 {
505  Relation tgrel;
506  HeapTuple tup;
507  Oid trigoid;
508  Form_pg_event_trigger evtForm;
509  char tgenabled = stmt->tgenabled;
510 
511  tgrel = table_open(EventTriggerRelationId, RowExclusiveLock);
512 
514  CStringGetDatum(stmt->trigname));
515  if (!HeapTupleIsValid(tup))
516  ereport(ERROR,
517  (errcode(ERRCODE_UNDEFINED_OBJECT),
518  errmsg("event trigger \"%s\" does not exist",
519  stmt->trigname)));
520 
521  evtForm = (Form_pg_event_trigger) GETSTRUCT(tup);
522  trigoid = evtForm->oid;
523 
524  if (!pg_event_trigger_ownercheck(trigoid, GetUserId()))
526  stmt->trigname);
527 
528  /* tuple is a copy, so we can modify it below */
529  evtForm->evtenabled = tgenabled;
530 
531  CatalogTupleUpdate(tgrel, &tup->t_self, tup);
532 
533  InvokeObjectPostAlterHook(EventTriggerRelationId,
534  trigoid, 0);
535 
536  /* clean up */
537  heap_freetuple(tup);
539 
540  return trigoid;
541 }
542 
543 /*
544  * Change event trigger's owner -- by name
545  */
547 AlterEventTriggerOwner(const char *name, Oid newOwnerId)
548 {
549  Oid evtOid;
550  HeapTuple tup;
551  Form_pg_event_trigger evtForm;
552  Relation rel;
553  ObjectAddress address;
554 
555  rel = table_open(EventTriggerRelationId, RowExclusiveLock);
556 
558 
559  if (!HeapTupleIsValid(tup))
560  ereport(ERROR,
561  (errcode(ERRCODE_UNDEFINED_OBJECT),
562  errmsg("event trigger \"%s\" does not exist", name)));
563 
564  evtForm = (Form_pg_event_trigger) GETSTRUCT(tup);
565  evtOid = evtForm->oid;
566 
567  AlterEventTriggerOwner_internal(rel, tup, newOwnerId);
568 
569  ObjectAddressSet(address, EventTriggerRelationId, evtOid);
570 
571  heap_freetuple(tup);
572 
574 
575  return address;
576 }
577 
578 /*
579  * Change event trigger owner, by OID
580  */
581 void
582 AlterEventTriggerOwner_oid(Oid trigOid, Oid newOwnerId)
583 {
584  HeapTuple tup;
585  Relation rel;
586 
587  rel = table_open(EventTriggerRelationId, RowExclusiveLock);
588 
590 
591  if (!HeapTupleIsValid(tup))
592  ereport(ERROR,
593  (errcode(ERRCODE_UNDEFINED_OBJECT),
594  errmsg("event trigger with OID %u does not exist", trigOid)));
595 
596  AlterEventTriggerOwner_internal(rel, tup, newOwnerId);
597 
598  heap_freetuple(tup);
599 
601 }
602 
603 /*
604  * Internal workhorse for changing an event trigger's owner
605  */
606 static void
608 {
610 
611  form = (Form_pg_event_trigger) GETSTRUCT(tup);
612 
613  if (form->evtowner == newOwnerId)
614  return;
615 
616  if (!pg_event_trigger_ownercheck(form->oid, GetUserId()))
618  NameStr(form->evtname));
619 
620  /* New owner must be a superuser */
621  if (!superuser_arg(newOwnerId))
622  ereport(ERROR,
623  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
624  errmsg("permission denied to change owner of event trigger \"%s\"",
625  NameStr(form->evtname)),
626  errhint("The owner of an event trigger must be a superuser.")));
627 
628  form->evtowner = newOwnerId;
629  CatalogTupleUpdate(rel, &tup->t_self, tup);
630 
631  /* Update owner dependency reference */
632  changeDependencyOnOwner(EventTriggerRelationId,
633  form->oid,
634  newOwnerId);
635 
636  InvokeObjectPostAlterHook(EventTriggerRelationId,
637  form->oid, 0);
638 }
639 
640 /*
641  * get_event_trigger_oid - Look up an event trigger by name to find its OID.
642  *
643  * If missing_ok is false, throw an error if trigger not found. If
644  * true, just return InvalidOid.
645  */
646 Oid
647 get_event_trigger_oid(const char *trigname, bool missing_ok)
648 {
649  Oid oid;
650 
651  oid = GetSysCacheOid1(EVENTTRIGGERNAME, Anum_pg_event_trigger_oid,
652  CStringGetDatum(trigname));
653  if (!OidIsValid(oid) && !missing_ok)
654  ereport(ERROR,
655  (errcode(ERRCODE_UNDEFINED_OBJECT),
656  errmsg("event trigger \"%s\" does not exist", trigname)));
657  return oid;
658 }
659 
660 /*
661  * Return true when we want to fire given Event Trigger and false otherwise,
662  * filtering on the session replication role and the event trigger registered
663  * tags matching.
664  */
665 static bool
667 {
668  /*
669  * Filter by session replication role, knowing that we never see disabled
670  * items down here.
671  */
673  {
674  if (item->enabled == TRIGGER_FIRES_ON_ORIGIN)
675  return false;
676  }
677  else
678  {
679  if (item->enabled == TRIGGER_FIRES_ON_REPLICA)
680  return false;
681  }
682 
683  /* Filter by tags, if any were specified. */
684  if (item->ntags != 0 && bsearch(tag, item->tag,
685  item->ntags, sizeof(char *),
686  pg_qsort_strcmp) == NULL)
687  return false;
688 
689  /* if we reach that point, we're not filtering out this item */
690  return true;
691 }
692 
693 /*
694  * Setup for running triggers for the given event. Return value is an OID list
695  * of functions to run; if there are any, trigdata is filled with an
696  * appropriate EventTriggerData for them to receive.
697  */
698 static List *
700  EventTriggerEvent event, const char *eventstr,
701  EventTriggerData *trigdata)
702 {
703  const char *tag;
704  List *cachelist;
705  ListCell *lc;
706  List *runlist = NIL;
707 
708  /*
709  * We want the list of command tags for which this procedure is actually
710  * invoked to match up exactly with the list that CREATE EVENT TRIGGER
711  * accepts. This debugging cross-check will throw an error if this
712  * function is invoked for a command tag that CREATE EVENT TRIGGER won't
713  * accept. (Unfortunately, there doesn't seem to be any simple, automated
714  * way to verify that CREATE EVENT TRIGGER doesn't accept extra stuff that
715  * never reaches this control point.)
716  *
717  * If this cross-check fails for you, you probably need to either adjust
718  * standard_ProcessUtility() not to invoke event triggers for the command
719  * type in question, or you need to adjust check_ddl_tag to accept the
720  * relevant command tag.
721  */
722 #ifdef USE_ASSERT_CHECKING
723  {
724  const char *dbgtag;
725 
726  dbgtag = CreateCommandTag(parsetree);
727  if (event == EVT_DDLCommandStart ||
728  event == EVT_DDLCommandEnd ||
729  event == EVT_SQLDrop)
730  {
732  elog(ERROR, "unexpected command tag \"%s\"", dbgtag);
733  }
734  else if (event == EVT_TableRewrite)
735  {
737  elog(ERROR, "unexpected command tag \"%s\"", dbgtag);
738  }
739  }
740 #endif
741 
742  /* Use cache to find triggers for this event; fast exit if none. */
743  cachelist = EventCacheLookup(event);
744  if (cachelist == NIL)
745  return NIL;
746 
747  /* Get the command tag. */
748  tag = CreateCommandTag(parsetree);
749 
750  /*
751  * Filter list of event triggers by command tag, and copy them into our
752  * memory context. Once we start running the command triggers, or indeed
753  * once we do anything at all that touches the catalogs, an invalidation
754  * might leave cachelist pointing at garbage, so we must do this before we
755  * can do much else.
756  */
757  foreach(lc, cachelist)
758  {
759  EventTriggerCacheItem *item = lfirst(lc);
760 
761  if (filter_event_trigger(&tag, item))
762  {
763  /* We must plan to fire this trigger. */
764  runlist = lappend_oid(runlist, item->fnoid);
765  }
766  }
767 
768  /* don't spend any more time on this if no functions to run */
769  if (runlist == NIL)
770  return NIL;
771 
772  trigdata->type = T_EventTriggerData;
773  trigdata->event = eventstr;
774  trigdata->parsetree = parsetree;
775  trigdata->tag = tag;
776 
777  return runlist;
778 }
779 
780 /*
781  * Fire ddl_command_start triggers.
782  */
783 void
785 {
786  List *runlist;
787  EventTriggerData trigdata;
788 
789  /*
790  * Event Triggers are completely disabled in standalone mode. There are
791  * (at least) two reasons for this:
792  *
793  * 1. A sufficiently broken event trigger might not only render the
794  * database unusable, but prevent disabling itself to fix the situation.
795  * In this scenario, restarting in standalone mode provides an escape
796  * hatch.
797  *
798  * 2. BuildEventTriggerCache relies on systable_beginscan_ordered, and
799  * therefore will malfunction if pg_event_trigger's indexes are damaged.
800  * To allow recovery from a damaged index, we need some operating mode
801  * wherein event triggers are disabled. (Or we could implement
802  * heapscan-and-sort logic for that case, but having disaster recovery
803  * scenarios depend on code that's otherwise untested isn't appetizing.)
804  */
805  if (!IsUnderPostmaster)
806  return;
807 
808  runlist = EventTriggerCommonSetup(parsetree,
810  "ddl_command_start",
811  &trigdata);
812  if (runlist == NIL)
813  return;
814 
815  /* Run the triggers. */
816  EventTriggerInvoke(runlist, &trigdata);
817 
818  /* Cleanup. */
819  list_free(runlist);
820 
821  /*
822  * Make sure anything the event triggers did will be visible to the main
823  * command.
824  */
826 }
827 
828 /*
829  * Fire ddl_command_end triggers.
830  */
831 void
833 {
834  List *runlist;
835  EventTriggerData trigdata;
836 
837  /*
838  * See EventTriggerDDLCommandStart for a discussion about why event
839  * triggers are disabled in single user mode.
840  */
841  if (!IsUnderPostmaster)
842  return;
843 
844  /*
845  * Also do nothing if our state isn't set up, which it won't be if there
846  * weren't any relevant event triggers at the start of the current DDL
847  * command. This test might therefore seem optional, but it's important
848  * because EventTriggerCommonSetup might find triggers that didn't exist
849  * at the time the command started. Although this function itself
850  * wouldn't crash, the event trigger functions would presumably call
851  * pg_event_trigger_ddl_commands which would fail. Better to do nothing
852  * until the next command.
853  */
854  if (!currentEventTriggerState)
855  return;
856 
857  runlist = EventTriggerCommonSetup(parsetree,
858  EVT_DDLCommandEnd, "ddl_command_end",
859  &trigdata);
860  if (runlist == NIL)
861  return;
862 
863  /*
864  * Make sure anything the main command did will be visible to the event
865  * triggers.
866  */
868 
869  /* Run the triggers. */
870  EventTriggerInvoke(runlist, &trigdata);
871 
872  /* Cleanup. */
873  list_free(runlist);
874 }
875 
876 /*
877  * Fire sql_drop triggers.
878  */
879 void
881 {
882  List *runlist;
883  EventTriggerData trigdata;
884 
885  /*
886  * See EventTriggerDDLCommandStart for a discussion about why event
887  * triggers are disabled in single user mode.
888  */
889  if (!IsUnderPostmaster)
890  return;
891 
892  /*
893  * Use current state to determine whether this event fires at all. If
894  * there are no triggers for the sql_drop event, then we don't have
895  * anything to do here. Note that dropped object collection is disabled
896  * if this is the case, so even if we were to try to run, the list would
897  * be empty.
898  */
899  if (!currentEventTriggerState ||
900  slist_is_empty(&currentEventTriggerState->SQLDropList))
901  return;
902 
903  runlist = EventTriggerCommonSetup(parsetree,
904  EVT_SQLDrop, "sql_drop",
905  &trigdata);
906 
907  /*
908  * Nothing to do if run list is empty. Note this typically can't happen,
909  * because if there are no sql_drop events, then objects-to-drop wouldn't
910  * have been collected in the first place and we would have quit above.
911  * But it could occur if event triggers were dropped partway through.
912  */
913  if (runlist == NIL)
914  return;
915 
916  /*
917  * Make sure anything the main command did will be visible to the event
918  * triggers.
919  */
921 
922  /*
923  * Make sure pg_event_trigger_dropped_objects only works when running
924  * these triggers. Use PG_TRY to ensure in_sql_drop is reset even when
925  * one trigger fails. (This is perhaps not necessary, as the currentState
926  * variable will be removed shortly by our caller, but it seems better to
927  * play safe.)
928  */
929  currentEventTriggerState->in_sql_drop = true;
930 
931  /* Run the triggers. */
932  PG_TRY();
933  {
934  EventTriggerInvoke(runlist, &trigdata);
935  }
936  PG_FINALLY();
937  {
938  currentEventTriggerState->in_sql_drop = false;
939  }
940  PG_END_TRY();
941 
942  /* Cleanup. */
943  list_free(runlist);
944 }
945 
946 
947 /*
948  * Fire table_rewrite triggers.
949  */
950 void
951 EventTriggerTableRewrite(Node *parsetree, Oid tableOid, int reason)
952 {
953  List *runlist;
954  EventTriggerData trigdata;
955 
956  /*
957  * Event Triggers are completely disabled in standalone mode. There are
958  * (at least) two reasons for this:
959  *
960  * 1. A sufficiently broken event trigger might not only render the
961  * database unusable, but prevent disabling itself to fix the situation.
962  * In this scenario, restarting in standalone mode provides an escape
963  * hatch.
964  *
965  * 2. BuildEventTriggerCache relies on systable_beginscan_ordered, and
966  * therefore will malfunction if pg_event_trigger's indexes are damaged.
967  * To allow recovery from a damaged index, we need some operating mode
968  * wherein event triggers are disabled. (Or we could implement
969  * heapscan-and-sort logic for that case, but having disaster recovery
970  * scenarios depend on code that's otherwise untested isn't appetizing.)
971  */
972  if (!IsUnderPostmaster)
973  return;
974 
975  /*
976  * Also do nothing if our state isn't set up, which it won't be if there
977  * weren't any relevant event triggers at the start of the current DDL
978  * command. This test might therefore seem optional, but it's
979  * *necessary*, because EventTriggerCommonSetup might find triggers that
980  * didn't exist at the time the command started.
981  */
982  if (!currentEventTriggerState)
983  return;
984 
985  runlist = EventTriggerCommonSetup(parsetree,
987  "table_rewrite",
988  &trigdata);
989  if (runlist == NIL)
990  return;
991 
992  /*
993  * Make sure pg_event_trigger_table_rewrite_oid only works when running
994  * these triggers. Use PG_TRY to ensure table_rewrite_oid is reset even
995  * when one trigger fails. (This is perhaps not necessary, as the
996  * currentState variable will be removed shortly by our caller, but it
997  * seems better to play safe.)
998  */
999  currentEventTriggerState->table_rewrite_oid = tableOid;
1000  currentEventTriggerState->table_rewrite_reason = reason;
1001 
1002  /* Run the triggers. */
1003  PG_TRY();
1004  {
1005  EventTriggerInvoke(runlist, &trigdata);
1006  }
1007  PG_FINALLY();
1008  {
1009  currentEventTriggerState->table_rewrite_oid = InvalidOid;
1010  currentEventTriggerState->table_rewrite_reason = 0;
1011  }
1012  PG_END_TRY();
1013 
1014  /* Cleanup. */
1015  list_free(runlist);
1016 
1017  /*
1018  * Make sure anything the event triggers did will be visible to the main
1019  * command.
1020  */
1022 }
1023 
1024 /*
1025  * Invoke each event trigger in a list of event triggers.
1026  */
1027 static void
1028 EventTriggerInvoke(List *fn_oid_list, EventTriggerData *trigdata)
1029 {
1030  MemoryContext context;
1031  MemoryContext oldcontext;
1032  ListCell *lc;
1033  bool first = true;
1034 
1035  /* Guard against stack overflow due to recursive event trigger */
1037 
1038  /*
1039  * Let's evaluate event triggers in their own memory context, so that any
1040  * leaks get cleaned up promptly.
1041  */
1043  "event trigger context",
1045  oldcontext = MemoryContextSwitchTo(context);
1046 
1047  /* Call each event trigger. */
1048  foreach(lc, fn_oid_list)
1049  {
1050  LOCAL_FCINFO(fcinfo, 0);
1051  Oid fnoid = lfirst_oid(lc);
1052  FmgrInfo flinfo;
1053  PgStat_FunctionCallUsage fcusage;
1054 
1055  elog(DEBUG1, "EventTriggerInvoke %u", fnoid);
1056 
1057  /*
1058  * We want each event trigger to be able to see the results of the
1059  * previous event trigger's action. Caller is responsible for any
1060  * command-counter increment that is needed between the event trigger
1061  * and anything else in the transaction.
1062  */
1063  if (first)
1064  first = false;
1065  else
1067 
1068  /* Look up the function */
1069  fmgr_info(fnoid, &flinfo);
1070 
1071  /* Call the function, passing no arguments but setting a context. */
1072  InitFunctionCallInfoData(*fcinfo, &flinfo, 0,
1073  InvalidOid, (Node *) trigdata, NULL);
1074  pgstat_init_function_usage(fcinfo, &fcusage);
1075  FunctionCallInvoke(fcinfo);
1076  pgstat_end_function_usage(&fcusage, true);
1077 
1078  /* Reclaim memory. */
1079  MemoryContextReset(context);
1080  }
1081 
1082  /* Restore old memory context and delete the temporary one. */
1083  MemoryContextSwitchTo(oldcontext);
1084  MemoryContextDelete(context);
1085 }
1086 
1087 /*
1088  * Do event triggers support this object type?
1089  */
1090 bool
1092 {
1093  switch (obtype)
1094  {
1095  case OBJECT_DATABASE:
1096  case OBJECT_TABLESPACE:
1097  case OBJECT_ROLE:
1098  /* no support for global objects */
1099  return false;
1100  case OBJECT_EVENT_TRIGGER:
1101  /* no support for event triggers on event triggers */
1102  return false;
1103  case OBJECT_ACCESS_METHOD:
1104  case OBJECT_AGGREGATE:
1105  case OBJECT_AMOP:
1106  case OBJECT_AMPROC:
1107  case OBJECT_ATTRIBUTE:
1108  case OBJECT_CAST:
1109  case OBJECT_COLUMN:
1110  case OBJECT_COLLATION:
1111  case OBJECT_CONVERSION:
1112  case OBJECT_DEFACL:
1113  case OBJECT_DEFAULT:
1114  case OBJECT_DOMAIN:
1115  case OBJECT_DOMCONSTRAINT:
1116  case OBJECT_EXTENSION:
1117  case OBJECT_FDW:
1118  case OBJECT_FOREIGN_SERVER:
1119  case OBJECT_FOREIGN_TABLE:
1120  case OBJECT_FUNCTION:
1121  case OBJECT_INDEX:
1122  case OBJECT_LANGUAGE:
1123  case OBJECT_LARGEOBJECT:
1124  case OBJECT_MATVIEW:
1125  case OBJECT_OPCLASS:
1126  case OBJECT_OPERATOR:
1127  case OBJECT_OPFAMILY:
1128  case OBJECT_POLICY:
1129  case OBJECT_PROCEDURE:
1130  case OBJECT_PUBLICATION:
1132  case OBJECT_ROUTINE:
1133  case OBJECT_RULE:
1134  case OBJECT_SCHEMA:
1135  case OBJECT_SEQUENCE:
1136  case OBJECT_SUBSCRIPTION:
1137  case OBJECT_STATISTIC_EXT:
1138  case OBJECT_TABCONSTRAINT:
1139  case OBJECT_TABLE:
1140  case OBJECT_TRANSFORM:
1141  case OBJECT_TRIGGER:
1143  case OBJECT_TSDICTIONARY:
1144  case OBJECT_TSPARSER:
1145  case OBJECT_TSTEMPLATE:
1146  case OBJECT_TYPE:
1147  case OBJECT_USER_MAPPING:
1148  case OBJECT_VIEW:
1149  return true;
1150 
1151  /*
1152  * There's intentionally no default: case here; we want the
1153  * compiler to warn if a new ObjectType hasn't been handled above.
1154  */
1155  }
1156 
1157  /* Shouldn't get here, but if we do, say "no support" */
1158  return false;
1159 }
1160 
1161 /*
1162  * Do event triggers support this object class?
1163  */
1164 bool
1166 {
1167  switch (objclass)
1168  {
1169  case OCLASS_DATABASE:
1170  case OCLASS_TBLSPACE:
1171  case OCLASS_ROLE:
1172  /* no support for global objects */
1173  return false;
1174  case OCLASS_EVENT_TRIGGER:
1175  /* no support for event triggers on event triggers */
1176  return false;
1177  case OCLASS_CLASS:
1178  case OCLASS_PROC:
1179  case OCLASS_TYPE:
1180  case OCLASS_CAST:
1181  case OCLASS_COLLATION:
1182  case OCLASS_CONSTRAINT:
1183  case OCLASS_CONVERSION:
1184  case OCLASS_DEFAULT:
1185  case OCLASS_LANGUAGE:
1186  case OCLASS_LARGEOBJECT:
1187  case OCLASS_OPERATOR:
1188  case OCLASS_OPCLASS:
1189  case OCLASS_OPFAMILY:
1190  case OCLASS_AM:
1191  case OCLASS_AMOP:
1192  case OCLASS_AMPROC:
1193  case OCLASS_REWRITE:
1194  case OCLASS_TRIGGER:
1195  case OCLASS_SCHEMA:
1196  case OCLASS_STATISTIC_EXT:
1197  case OCLASS_TSPARSER:
1198  case OCLASS_TSDICT:
1199  case OCLASS_TSTEMPLATE:
1200  case OCLASS_TSCONFIG:
1201  case OCLASS_FDW:
1202  case OCLASS_FOREIGN_SERVER:
1203  case OCLASS_USER_MAPPING:
1204  case OCLASS_DEFACL:
1205  case OCLASS_EXTENSION:
1206  case OCLASS_POLICY:
1207  case OCLASS_PUBLICATION:
1209  case OCLASS_SUBSCRIPTION:
1210  case OCLASS_TRANSFORM:
1211  return true;
1212 
1213  /*
1214  * There's intentionally no default: case here; we want the
1215  * compiler to warn if a new OCLASS hasn't been handled above.
1216  */
1217  }
1218 
1219  /* Shouldn't get here, but if we do, say "no support" */
1220  return false;
1221 }
1222 
1223 /*
1224  * Prepare event trigger state for a new complete query to run, if necessary;
1225  * returns whether this was done. If it was, EventTriggerEndCompleteQuery must
1226  * be called when the query is done, regardless of whether it succeeds or fails
1227  * -- so use of a PG_TRY block is mandatory.
1228  */
1229 bool
1231 {
1234 
1235  /*
1236  * Currently, sql_drop, table_rewrite, ddl_command_end events are the only
1237  * reason to have event trigger state at all; so if there are none, don't
1238  * install one.
1239  */
1241  return false;
1242 
1244  "event trigger state",
1246  state = MemoryContextAlloc(cxt, sizeof(EventTriggerQueryState));
1247  state->cxt = cxt;
1248  slist_init(&(state->SQLDropList));
1249  state->in_sql_drop = false;
1250  state->table_rewrite_oid = InvalidOid;
1251 
1252  state->commandCollectionInhibited = currentEventTriggerState ?
1253  currentEventTriggerState->commandCollectionInhibited : false;
1254  state->currentCommand = NULL;
1255  state->commandList = NIL;
1257  currentEventTriggerState = state;
1258 
1259  return true;
1260 }
1261 
1262 /*
1263  * Query completed (or errored out) -- clean up local state, return to previous
1264  * one.
1265  *
1266  * Note: it's an error to call this routine if EventTriggerBeginCompleteQuery
1267  * returned false previously.
1268  *
1269  * Note: this might be called in the PG_CATCH block of a failing transaction,
1270  * so be wary of running anything unnecessary. (In particular, it's probably
1271  * unwise to try to allocate memory.)
1272  */
1273 void
1275 {
1276  EventTriggerQueryState *prevstate;
1277 
1278  prevstate = currentEventTriggerState->previous;
1279 
1280  /* this avoids the need for retail pfree of SQLDropList items: */
1281  MemoryContextDelete(currentEventTriggerState->cxt);
1282 
1283  currentEventTriggerState = prevstate;
1284 }
1285 
1286 /*
1287  * Do we need to keep close track of objects being dropped?
1288  *
1289  * This is useful because there is a cost to running with them enabled.
1290  */
1291 bool
1293 {
1294  /*
1295  * true if any sql_drop, table_rewrite, ddl_command_end event trigger
1296  * exists
1297  */
1298  return list_length(EventCacheLookup(EVT_SQLDrop)) > 0 ||
1301 }
1302 
1303 /*
1304  * Support for dropped objects information on event trigger functions.
1305  *
1306  * We keep the list of objects dropped by the current command in current
1307  * state's SQLDropList (comprising SQLDropObject items). Each time a new
1308  * command is to start, a clean EventTriggerQueryState is created; commands
1309  * that drop objects do the dependency.c dance to drop objects, which
1310  * populates the current state's SQLDropList; when the event triggers are
1311  * invoked they can consume the list via pg_event_trigger_dropped_objects().
1312  * When the command finishes, the EventTriggerQueryState is cleared, and
1313  * the one from the previous command is restored (when no command is in
1314  * execution, the current state is NULL).
1315  *
1316  * All this lets us support the case that an event trigger function drops
1317  * objects "reentrantly".
1318  */
1319 
1320 /*
1321  * Register one object as being dropped by the current command.
1322  */
1323 void
1324 EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
1325 {
1326  SQLDropObject *obj;
1327  MemoryContext oldcxt;
1328 
1329  if (!currentEventTriggerState)
1330  return;
1331 
1333 
1334  /* don't report temp schemas except my own */
1335  if (object->classId == NamespaceRelationId &&
1336  (isAnyTempNamespace(object->objectId) &&
1337  !isTempNamespace(object->objectId)))
1338  return;
1339 
1340  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1341 
1342  obj = palloc0(sizeof(SQLDropObject));
1343  obj->address = *object;
1344  obj->original = original;
1345  obj->normal = normal;
1346 
1347  /*
1348  * Obtain schema names from the object's catalog tuple, if one exists;
1349  * this lets us skip objects in temp schemas. We trust that
1350  * ObjectProperty contains all object classes that can be
1351  * schema-qualified.
1352  */
1353  if (is_objectclass_supported(object->classId))
1354  {
1355  Relation catalog;
1356  HeapTuple tuple;
1357 
1358  catalog = table_open(obj->address.classId, AccessShareLock);
1359  tuple = get_catalog_object_by_oid(catalog,
1360  get_object_attnum_oid(object->classId),
1361  obj->address.objectId);
1362 
1363  if (tuple)
1364  {
1366  Datum datum;
1367  bool isnull;
1368 
1370  if (attnum != InvalidAttrNumber)
1371  {
1372  datum = heap_getattr(tuple, attnum,
1373  RelationGetDescr(catalog), &isnull);
1374  if (!isnull)
1375  {
1376  Oid namespaceId;
1377 
1378  namespaceId = DatumGetObjectId(datum);
1379  /* temp objects are only reported if they are my own */
1380  if (isTempNamespace(namespaceId))
1381  {
1382  obj->schemaname = "pg_temp";
1383  obj->istemp = true;
1384  }
1385  else if (isAnyTempNamespace(namespaceId))
1386  {
1387  pfree(obj);
1388  table_close(catalog, AccessShareLock);
1389  MemoryContextSwitchTo(oldcxt);
1390  return;
1391  }
1392  else
1393  {
1394  obj->schemaname = get_namespace_name(namespaceId);
1395  obj->istemp = false;
1396  }
1397  }
1398  }
1399 
1401  obj->address.objectSubId == 0)
1402  {
1403  attnum = get_object_attnum_name(obj->address.classId);
1404  if (attnum != InvalidAttrNumber)
1405  {
1406  datum = heap_getattr(tuple, attnum,
1407  RelationGetDescr(catalog), &isnull);
1408  if (!isnull)
1409  obj->objname = pstrdup(NameStr(*DatumGetName(datum)));
1410  }
1411  }
1412  }
1413 
1414  table_close(catalog, AccessShareLock);
1415  }
1416  else
1417  {
1418  if (object->classId == NamespaceRelationId &&
1419  isTempNamespace(object->objectId))
1420  obj->istemp = true;
1421  }
1422 
1423  /* object identity, objname and objargs */
1424  obj->objidentity =
1425  getObjectIdentityParts(&obj->address, &obj->addrnames, &obj->addrargs);
1426 
1427  /* object type */
1429 
1430  slist_push_head(&(currentEventTriggerState->SQLDropList), &obj->next);
1431 
1432  MemoryContextSwitchTo(oldcxt);
1433 }
1434 
1435 /*
1436  * pg_event_trigger_dropped_objects
1437  *
1438  * Make the list of dropped objects available to the user function run by the
1439  * Event Trigger.
1440  */
1441 Datum
1443 {
1444  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1445  TupleDesc tupdesc;
1446  Tuplestorestate *tupstore;
1447  MemoryContext per_query_ctx;
1448  MemoryContext oldcontext;
1449  slist_iter iter;
1450 
1451  /*
1452  * Protect this function from being called out of context
1453  */
1454  if (!currentEventTriggerState ||
1455  !currentEventTriggerState->in_sql_drop)
1456  ereport(ERROR,
1457  (errcode(ERRCODE_E_R_I_E_EVENT_TRIGGER_PROTOCOL_VIOLATED),
1458  errmsg("%s can only be called in a sql_drop event trigger function",
1459  "pg_event_trigger_dropped_objects()")));
1460 
1461  /* check to see if caller supports us returning a tuplestore */
1462  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1463  ereport(ERROR,
1464  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1465  errmsg("set-valued function called in context that cannot accept a set")));
1466  if (!(rsinfo->allowedModes & SFRM_Materialize))
1467  ereport(ERROR,
1468  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1469  errmsg("materialize mode required, but it is not allowed in this context")));
1470 
1471  /* Build a tuple descriptor for our result type */
1472  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1473  elog(ERROR, "return type must be a row type");
1474 
1475  /* Build tuplestore to hold the result rows */
1476  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1477  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1478 
1479  tupstore = tuplestore_begin_heap(true, false, work_mem);
1480  rsinfo->returnMode = SFRM_Materialize;
1481  rsinfo->setResult = tupstore;
1482  rsinfo->setDesc = tupdesc;
1483 
1484  MemoryContextSwitchTo(oldcontext);
1485 
1486  slist_foreach(iter, &(currentEventTriggerState->SQLDropList))
1487  {
1488  SQLDropObject *obj;
1489  int i = 0;
1490  Datum values[12];
1491  bool nulls[12];
1492 
1493  obj = slist_container(SQLDropObject, next, iter.cur);
1494 
1495  MemSet(values, 0, sizeof(values));
1496  MemSet(nulls, 0, sizeof(nulls));
1497 
1498  /* classid */
1499  values[i++] = ObjectIdGetDatum(obj->address.classId);
1500 
1501  /* objid */
1502  values[i++] = ObjectIdGetDatum(obj->address.objectId);
1503 
1504  /* objsubid */
1505  values[i++] = Int32GetDatum(obj->address.objectSubId);
1506 
1507  /* original */
1508  values[i++] = BoolGetDatum(obj->original);
1509 
1510  /* normal */
1511  values[i++] = BoolGetDatum(obj->normal);
1512 
1513  /* is_temporary */
1514  values[i++] = BoolGetDatum(obj->istemp);
1515 
1516  /* object_type */
1517  values[i++] = CStringGetTextDatum(obj->objecttype);
1518 
1519  /* schema_name */
1520  if (obj->schemaname)
1521  values[i++] = CStringGetTextDatum(obj->schemaname);
1522  else
1523  nulls[i++] = true;
1524 
1525  /* object_name */
1526  if (obj->objname)
1527  values[i++] = CStringGetTextDatum(obj->objname);
1528  else
1529  nulls[i++] = true;
1530 
1531  /* object_identity */
1532  if (obj->objidentity)
1533  values[i++] = CStringGetTextDatum(obj->objidentity);
1534  else
1535  nulls[i++] = true;
1536 
1537  /* address_names and address_args */
1538  if (obj->addrnames)
1539  {
1540  values[i++] = PointerGetDatum(strlist_to_textarray(obj->addrnames));
1541 
1542  if (obj->addrargs)
1543  values[i++] = PointerGetDatum(strlist_to_textarray(obj->addrargs));
1544  else
1545  values[i++] = PointerGetDatum(construct_empty_array(TEXTOID));
1546  }
1547  else
1548  {
1549  nulls[i++] = true;
1550  nulls[i++] = true;
1551  }
1552 
1553  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1554  }
1555 
1556  /* clean up and return the tuplestore */
1557  tuplestore_donestoring(tupstore);
1558 
1559  return (Datum) 0;
1560 }
1561 
1562 /*
1563  * pg_event_trigger_table_rewrite_oid
1564  *
1565  * Make the Oid of the table going to be rewritten available to the user
1566  * function run by the Event Trigger.
1567  */
1568 Datum
1570 {
1571  /*
1572  * Protect this function from being called out of context
1573  */
1574  if (!currentEventTriggerState ||
1575  currentEventTriggerState->table_rewrite_oid == InvalidOid)
1576  ereport(ERROR,
1577  (errcode(ERRCODE_E_R_I_E_EVENT_TRIGGER_PROTOCOL_VIOLATED),
1578  errmsg("%s can only be called in a table_rewrite event trigger function",
1579  "pg_event_trigger_table_rewrite_oid()")));
1580 
1581  PG_RETURN_OID(currentEventTriggerState->table_rewrite_oid);
1582 }
1583 
1584 /*
1585  * pg_event_trigger_table_rewrite_reason
1586  *
1587  * Make the rewrite reason available to the user.
1588  */
1589 Datum
1591 {
1592  /*
1593  * Protect this function from being called out of context
1594  */
1595  if (!currentEventTriggerState ||
1596  currentEventTriggerState->table_rewrite_reason == 0)
1597  ereport(ERROR,
1598  (errcode(ERRCODE_E_R_I_E_EVENT_TRIGGER_PROTOCOL_VIOLATED),
1599  errmsg("%s can only be called in a table_rewrite event trigger function",
1600  "pg_event_trigger_table_rewrite_reason()")));
1601 
1602  PG_RETURN_INT32(currentEventTriggerState->table_rewrite_reason);
1603 }
1604 
1605 /*-------------------------------------------------------------------------
1606  * Support for DDL command deparsing
1607  *
1608  * The routines below enable an event trigger function to obtain a list of
1609  * DDL commands as they are executed. There are three main pieces to this
1610  * feature:
1611  *
1612  * 1) Within ProcessUtilitySlow, or some sub-routine thereof, each DDL command
1613  * adds a struct CollectedCommand representation of itself to the command list,
1614  * using the routines below.
1615  *
1616  * 2) Some time after that, ddl_command_end fires and the command list is made
1617  * available to the event trigger function via pg_event_trigger_ddl_commands();
1618  * the complete command details are exposed as a column of type pg_ddl_command.
1619  *
1620  * 3) An extension can install a function capable of taking a value of type
1621  * pg_ddl_command and transform it into some external, user-visible and/or
1622  * -modifiable representation.
1623  *-------------------------------------------------------------------------
1624  */
1625 
1626 /*
1627  * Inhibit DDL command collection.
1628  */
1629 void
1631 {
1632  if (!currentEventTriggerState)
1633  return;
1634 
1635  currentEventTriggerState->commandCollectionInhibited = true;
1636 }
1637 
1638 /*
1639  * Re-establish DDL command collection.
1640  */
1641 void
1643 {
1644  if (!currentEventTriggerState)
1645  return;
1646 
1647  currentEventTriggerState->commandCollectionInhibited = false;
1648 }
1649 
1650 /*
1651  * EventTriggerCollectSimpleCommand
1652  * Save data about a simple DDL command that was just executed
1653  *
1654  * address identifies the object being operated on. secondaryObject is an
1655  * object address that was related in some way to the executed command; its
1656  * meaning is command-specific.
1657  *
1658  * For instance, for an ALTER obj SET SCHEMA command, objtype is the type of
1659  * object being moved, objectId is its OID, and secondaryOid is the OID of the
1660  * old schema. (The destination schema OID can be obtained by catalog lookup
1661  * of the object.)
1662  */
1663 void
1665  ObjectAddress secondaryObject,
1666  Node *parsetree)
1667 {
1668  MemoryContext oldcxt;
1669  CollectedCommand *command;
1670 
1671  /* ignore if event trigger context not set, or collection disabled */
1672  if (!currentEventTriggerState ||
1673  currentEventTriggerState->commandCollectionInhibited)
1674  return;
1675 
1676  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1677 
1678  command = palloc(sizeof(CollectedCommand));
1679 
1680  command->type = SCT_Simple;
1681  command->in_extension = creating_extension;
1682 
1683  command->d.simple.address = address;
1684  command->d.simple.secondaryObject = secondaryObject;
1685  command->parsetree = copyObject(parsetree);
1686 
1687  currentEventTriggerState->commandList = lappend(currentEventTriggerState->commandList,
1688  command);
1689 
1690  MemoryContextSwitchTo(oldcxt);
1691 }
1692 
1693 /*
1694  * EventTriggerAlterTableStart
1695  * Prepare to receive data on an ALTER TABLE command about to be executed
1696  *
1697  * Note we don't collect the command immediately; instead we keep it in
1698  * currentCommand, and only when we're done processing the subcommands we will
1699  * add it to the command list.
1700  */
1701 void
1703 {
1704  MemoryContext oldcxt;
1705  CollectedCommand *command;
1706 
1707  /* ignore if event trigger context not set, or collection disabled */
1708  if (!currentEventTriggerState ||
1709  currentEventTriggerState->commandCollectionInhibited)
1710  return;
1711 
1712  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1713 
1714  command = palloc(sizeof(CollectedCommand));
1715 
1716  command->type = SCT_AlterTable;
1717  command->in_extension = creating_extension;
1718 
1719  command->d.alterTable.classId = RelationRelationId;
1720  command->d.alterTable.objectId = InvalidOid;
1721  command->d.alterTable.subcmds = NIL;
1722  command->parsetree = copyObject(parsetree);
1723 
1724  command->parent = currentEventTriggerState->currentCommand;
1725  currentEventTriggerState->currentCommand = command;
1726 
1727  MemoryContextSwitchTo(oldcxt);
1728 }
1729 
1730 /*
1731  * Remember the OID of the object being affected by an ALTER TABLE.
1732  *
1733  * This is needed because in some cases we don't know the OID until later.
1734  */
1735 void
1737 {
1738  if (!currentEventTriggerState ||
1739  currentEventTriggerState->commandCollectionInhibited)
1740  return;
1741 
1742  currentEventTriggerState->currentCommand->d.alterTable.objectId = objectId;
1743 }
1744 
1745 /*
1746  * EventTriggerCollectAlterTableSubcmd
1747  * Save data about a single part of an ALTER TABLE.
1748  *
1749  * Several different commands go through this path, but apart from ALTER TABLE
1750  * itself, they are all concerned with AlterTableCmd nodes that are generated
1751  * internally, so that's all that this code needs to handle at the moment.
1752  */
1753 void
1755 {
1756  MemoryContext oldcxt;
1758 
1759  /* ignore if event trigger context not set, or collection disabled */
1760  if (!currentEventTriggerState ||
1761  currentEventTriggerState->commandCollectionInhibited)
1762  return;
1763 
1764  Assert(IsA(subcmd, AlterTableCmd));
1765  Assert(currentEventTriggerState->currentCommand != NULL);
1766  Assert(OidIsValid(currentEventTriggerState->currentCommand->d.alterTable.objectId));
1767 
1768  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1769 
1770  newsub = palloc(sizeof(CollectedATSubcmd));
1771  newsub->address = address;
1772  newsub->parsetree = copyObject(subcmd);
1773 
1774  currentEventTriggerState->currentCommand->d.alterTable.subcmds =
1775  lappend(currentEventTriggerState->currentCommand->d.alterTable.subcmds, newsub);
1776 
1777  MemoryContextSwitchTo(oldcxt);
1778 }
1779 
1780 /*
1781  * EventTriggerAlterTableEnd
1782  * Finish up saving an ALTER TABLE command, and add it to command list.
1783  *
1784  * FIXME this API isn't considering the possibility that an xact/subxact is
1785  * aborted partway through. Probably it's best to add an
1786  * AtEOSubXact_EventTriggers() to fix this.
1787  */
1788 void
1790 {
1791  CollectedCommand *parent;
1792 
1793  /* ignore if event trigger context not set, or collection disabled */
1794  if (!currentEventTriggerState ||
1795  currentEventTriggerState->commandCollectionInhibited)
1796  return;
1797 
1798  parent = currentEventTriggerState->currentCommand->parent;
1799 
1800  /* If no subcommands, don't collect */
1801  if (list_length(currentEventTriggerState->currentCommand->d.alterTable.subcmds) != 0)
1802  {
1803  currentEventTriggerState->commandList =
1804  lappend(currentEventTriggerState->commandList,
1805  currentEventTriggerState->currentCommand);
1806  }
1807  else
1808  pfree(currentEventTriggerState->currentCommand);
1809 
1810  currentEventTriggerState->currentCommand = parent;
1811 }
1812 
1813 /*
1814  * EventTriggerCollectGrant
1815  * Save data about a GRANT/REVOKE command being executed
1816  *
1817  * This function creates a copy of the InternalGrant, as the original might
1818  * not have the right lifetime.
1819  */
1820 void
1822 {
1823  MemoryContext oldcxt;
1824  CollectedCommand *command;
1825  InternalGrant *icopy;
1826  ListCell *cell;
1827 
1828  /* ignore if event trigger context not set, or collection disabled */
1829  if (!currentEventTriggerState ||
1830  currentEventTriggerState->commandCollectionInhibited)
1831  return;
1832 
1833  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1834 
1835  /*
1836  * This is tedious, but necessary.
1837  */
1838  icopy = palloc(sizeof(InternalGrant));
1839  memcpy(icopy, istmt, sizeof(InternalGrant));
1840  icopy->objects = list_copy(istmt->objects);
1841  icopy->grantees = list_copy(istmt->grantees);
1842  icopy->col_privs = NIL;
1843  foreach(cell, istmt->col_privs)
1844  icopy->col_privs = lappend(icopy->col_privs, copyObject(lfirst(cell)));
1845 
1846  /* Now collect it, using the copied InternalGrant */
1847  command = palloc(sizeof(CollectedCommand));
1848  command->type = SCT_Grant;
1849  command->in_extension = creating_extension;
1850  command->d.grant.istmt = icopy;
1851  command->parsetree = NULL;
1852 
1853  currentEventTriggerState->commandList =
1854  lappend(currentEventTriggerState->commandList, command);
1855 
1856  MemoryContextSwitchTo(oldcxt);
1857 }
1858 
1859 /*
1860  * EventTriggerCollectAlterOpFam
1861  * Save data about an ALTER OPERATOR FAMILY ADD/DROP command being
1862  * executed
1863  */
1864 void
1866  List *operators, List *procedures)
1867 {
1868  MemoryContext oldcxt;
1869  CollectedCommand *command;
1870 
1871  /* ignore if event trigger context not set, or collection disabled */
1872  if (!currentEventTriggerState ||
1873  currentEventTriggerState->commandCollectionInhibited)
1874  return;
1875 
1876  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1877 
1878  command = palloc(sizeof(CollectedCommand));
1879  command->type = SCT_AlterOpFamily;
1880  command->in_extension = creating_extension;
1881  ObjectAddressSet(command->d.opfam.address,
1882  OperatorFamilyRelationId, opfamoid);
1883  command->d.opfam.operators = operators;
1884  command->d.opfam.procedures = procedures;
1885  command->parsetree = (Node *) copyObject(stmt);
1886 
1887  currentEventTriggerState->commandList =
1888  lappend(currentEventTriggerState->commandList, command);
1889 
1890  MemoryContextSwitchTo(oldcxt);
1891 }
1892 
1893 /*
1894  * EventTriggerCollectCreateOpClass
1895  * Save data about a CREATE OPERATOR CLASS command being executed
1896  */
1897 void
1899  List *operators, List *procedures)
1900 {
1901  MemoryContext oldcxt;
1902  CollectedCommand *command;
1903 
1904  /* ignore if event trigger context not set, or collection disabled */
1905  if (!currentEventTriggerState ||
1906  currentEventTriggerState->commandCollectionInhibited)
1907  return;
1908 
1909  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1910 
1911  command = palloc0(sizeof(CollectedCommand));
1912  command->type = SCT_CreateOpClass;
1913  command->in_extension = creating_extension;
1914  ObjectAddressSet(command->d.createopc.address,
1915  OperatorClassRelationId, opcoid);
1916  command->d.createopc.operators = operators;
1917  command->d.createopc.procedures = procedures;
1918  command->parsetree = (Node *) copyObject(stmt);
1919 
1920  currentEventTriggerState->commandList =
1921  lappend(currentEventTriggerState->commandList, command);
1922 
1923  MemoryContextSwitchTo(oldcxt);
1924 }
1925 
1926 /*
1927  * EventTriggerCollectAlterTSConfig
1928  * Save data about an ALTER TEXT SEARCH CONFIGURATION command being
1929  * executed
1930  */
1931 void
1933  Oid *dictIds, int ndicts)
1934 {
1935  MemoryContext oldcxt;
1936  CollectedCommand *command;
1937 
1938  /* ignore if event trigger context not set, or collection disabled */
1939  if (!currentEventTriggerState ||
1940  currentEventTriggerState->commandCollectionInhibited)
1941  return;
1942 
1943  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1944 
1945  command = palloc0(sizeof(CollectedCommand));
1946  command->type = SCT_AlterTSConfig;
1947  command->in_extension = creating_extension;
1948  ObjectAddressSet(command->d.atscfg.address,
1949  TSConfigRelationId, cfgId);
1950  command->d.atscfg.dictIds = palloc(sizeof(Oid) * ndicts);
1951  memcpy(command->d.atscfg.dictIds, dictIds, sizeof(Oid) * ndicts);
1952  command->d.atscfg.ndicts = ndicts;
1953  command->parsetree = (Node *) copyObject(stmt);
1954 
1955  currentEventTriggerState->commandList =
1956  lappend(currentEventTriggerState->commandList, command);
1957 
1958  MemoryContextSwitchTo(oldcxt);
1959 }
1960 
1961 /*
1962  * EventTriggerCollectAlterDefPrivs
1963  * Save data about an ALTER DEFAULT PRIVILEGES command being
1964  * executed
1965  */
1966 void
1968 {
1969  MemoryContext oldcxt;
1970  CollectedCommand *command;
1971 
1972  /* ignore if event trigger context not set, or collection disabled */
1973  if (!currentEventTriggerState ||
1974  currentEventTriggerState->commandCollectionInhibited)
1975  return;
1976 
1977  oldcxt = MemoryContextSwitchTo(currentEventTriggerState->cxt);
1978 
1979  command = palloc0(sizeof(CollectedCommand));
1980  command->type = SCT_AlterDefaultPrivileges;
1981  command->d.defprivs.objtype = stmt->action->objtype;
1982  command->in_extension = creating_extension;
1983  command->parsetree = (Node *) copyObject(stmt);
1984 
1985  currentEventTriggerState->commandList =
1986  lappend(currentEventTriggerState->commandList, command);
1987  MemoryContextSwitchTo(oldcxt);
1988 }
1989 
1990 /*
1991  * In a ddl_command_end event trigger, this function reports the DDL commands
1992  * being run.
1993  */
1994 Datum
1996 {
1997  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1998  TupleDesc tupdesc;
1999  Tuplestorestate *tupstore;
2000  MemoryContext per_query_ctx;
2001  MemoryContext oldcontext;
2002  ListCell *lc;
2003 
2004  /*
2005  * Protect this function from being called out of context
2006  */
2007  if (!currentEventTriggerState)
2008  ereport(ERROR,
2009  (errcode(ERRCODE_E_R_I_E_EVENT_TRIGGER_PROTOCOL_VIOLATED),
2010  errmsg("%s can only be called in an event trigger function",
2011  "pg_event_trigger_ddl_commands()")));
2012 
2013  /* check to see if caller supports us returning a tuplestore */
2014  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
2015  ereport(ERROR,
2016  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2017  errmsg("set-valued function called in context that cannot accept a set")));
2018  if (!(rsinfo->allowedModes & SFRM_Materialize))
2019  ereport(ERROR,
2020  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2021  errmsg("materialize mode required, but it is not allowed in this context")));
2022 
2023  /* Build a tuple descriptor for our result type */
2024  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
2025  elog(ERROR, "return type must be a row type");
2026 
2027  /* Build tuplestore to hold the result rows */
2028  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
2029  oldcontext = MemoryContextSwitchTo(per_query_ctx);
2030 
2031  tupstore = tuplestore_begin_heap(true, false, work_mem);
2032  rsinfo->returnMode = SFRM_Materialize;
2033  rsinfo->setResult = tupstore;
2034  rsinfo->setDesc = tupdesc;
2035 
2036  MemoryContextSwitchTo(oldcontext);
2037 
2038  foreach(lc, currentEventTriggerState->commandList)
2039  {
2040  CollectedCommand *cmd = lfirst(lc);
2041  Datum values[9];
2042  bool nulls[9];
2043  ObjectAddress addr;
2044  int i = 0;
2045 
2046  /*
2047  * For IF NOT EXISTS commands that attempt to create an existing
2048  * object, the returned OID is Invalid. Don't return anything.
2049  *
2050  * One might think that a viable alternative would be to look up the
2051  * Oid of the existing object and run the deparse with that. But
2052  * since the parse tree might be different from the one that created
2053  * the object in the first place, we might not end up in a consistent
2054  * state anyway.
2055  */
2056  if (cmd->type == SCT_Simple &&
2057  !OidIsValid(cmd->d.simple.address.objectId))
2058  continue;
2059 
2060  MemSet(nulls, 0, sizeof(nulls));
2061 
2062  switch (cmd->type)
2063  {
2064  case SCT_Simple:
2065  case SCT_AlterTable:
2066  case SCT_AlterOpFamily:
2067  case SCT_CreateOpClass:
2068  case SCT_AlterTSConfig:
2069  {
2070  char *identity;
2071  char *type;
2072  char *schema = NULL;
2073 
2074  if (cmd->type == SCT_Simple)
2075  addr = cmd->d.simple.address;
2076  else if (cmd->type == SCT_AlterTable)
2077  ObjectAddressSet(addr,
2078  cmd->d.alterTable.classId,
2079  cmd->d.alterTable.objectId);
2080  else if (cmd->type == SCT_AlterOpFamily)
2081  addr = cmd->d.opfam.address;
2082  else if (cmd->type == SCT_CreateOpClass)
2083  addr = cmd->d.createopc.address;
2084  else if (cmd->type == SCT_AlterTSConfig)
2085  addr = cmd->d.atscfg.address;
2086 
2087  type = getObjectTypeDescription(&addr);
2088  identity = getObjectIdentity(&addr);
2089 
2090  /*
2091  * Obtain schema name, if any ("pg_temp" if a temp
2092  * object). If the object class is not in the supported
2093  * list here, we assume it's a schema-less object type,
2094  * and thus "schema" remains set to NULL.
2095  */
2097  {
2098  AttrNumber nspAttnum;
2099 
2100  nspAttnum = get_object_attnum_namespace(addr.classId);
2101  if (nspAttnum != InvalidAttrNumber)
2102  {
2103  Relation catalog;
2104  HeapTuple objtup;
2105  Oid schema_oid;
2106  bool isnull;
2107 
2108  catalog = table_open(addr.classId, AccessShareLock);
2109  objtup = get_catalog_object_by_oid(catalog,
2111  addr.objectId);
2112  if (!HeapTupleIsValid(objtup))
2113  elog(ERROR, "cache lookup failed for object %u/%u",
2114  addr.classId, addr.objectId);
2115  schema_oid =
2116  heap_getattr(objtup, nspAttnum,
2117  RelationGetDescr(catalog), &isnull);
2118  if (isnull)
2119  elog(ERROR,
2120  "invalid null namespace in object %u/%u/%d",
2121  addr.classId, addr.objectId, addr.objectSubId);
2122  /* XXX not quite get_namespace_name_or_temp */
2123  if (isAnyTempNamespace(schema_oid))
2124  schema = pstrdup("pg_temp");
2125  else
2126  schema = get_namespace_name(schema_oid);
2127 
2128  table_close(catalog, AccessShareLock);
2129  }
2130  }
2131 
2132  /* classid */
2133  values[i++] = ObjectIdGetDatum(addr.classId);
2134  /* objid */
2135  values[i++] = ObjectIdGetDatum(addr.objectId);
2136  /* objsubid */
2137  values[i++] = Int32GetDatum(addr.objectSubId);
2138  /* command tag */
2139  values[i++] = CStringGetTextDatum(CreateCommandTag(cmd->parsetree));
2140  /* object_type */
2141  values[i++] = CStringGetTextDatum(type);
2142  /* schema */
2143  if (schema == NULL)
2144  nulls[i++] = true;
2145  else
2146  values[i++] = CStringGetTextDatum(schema);
2147  /* identity */
2148  values[i++] = CStringGetTextDatum(identity);
2149  /* in_extension */
2150  values[i++] = BoolGetDatum(cmd->in_extension);
2151  /* command */
2152  values[i++] = PointerGetDatum(cmd);
2153  }
2154  break;
2155 
2157  /* classid */
2158  nulls[i++] = true;
2159  /* objid */
2160  nulls[i++] = true;
2161  /* objsubid */
2162  nulls[i++] = true;
2163  /* command tag */
2164  values[i++] = CStringGetTextDatum(CreateCommandTag(cmd->parsetree));
2165  /* object_type */
2167  cmd->d.defprivs.objtype));
2168  /* schema */
2169  nulls[i++] = true;
2170  /* identity */
2171  nulls[i++] = true;
2172  /* in_extension */
2173  values[i++] = BoolGetDatum(cmd->in_extension);
2174  /* command */
2175  values[i++] = PointerGetDatum(cmd);
2176  break;
2177 
2178  case SCT_Grant:
2179  /* classid */
2180  nulls[i++] = true;
2181  /* objid */
2182  nulls[i++] = true;
2183  /* objsubid */
2184  nulls[i++] = true;
2185  /* command tag */
2186  values[i++] = CStringGetTextDatum(cmd->d.grant.istmt->is_grant ?
2187  "GRANT" : "REVOKE");
2188  /* object_type */
2190  cmd->d.grant.istmt->objtype));
2191  /* schema */
2192  nulls[i++] = true;
2193  /* identity */
2194  nulls[i++] = true;
2195  /* in_extension */
2196  values[i++] = BoolGetDatum(cmd->in_extension);
2197  /* command */
2198  values[i++] = PointerGetDatum(cmd);
2199  break;
2200  }
2201 
2202  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
2203  }
2204 
2205  /* clean up and return the tuplestore */
2206  tuplestore_donestoring(tupstore);
2207 
2208  PG_RETURN_VOID();
2209 }
2210 
2211 /*
2212  * Return the ObjectType as a string, as it would appear in GRANT and
2213  * REVOKE commands.
2214  */
2215 static const char *
2217 {
2218  switch (objtype)
2219  {
2220  case OBJECT_COLUMN:
2221  return "COLUMN";
2222  case OBJECT_TABLE:
2223  return "TABLE";
2224  case OBJECT_SEQUENCE:
2225  return "SEQUENCE";
2226  case OBJECT_DATABASE:
2227  return "DATABASE";
2228  case OBJECT_DOMAIN:
2229  return "DOMAIN";
2230  case OBJECT_FDW:
2231  return "FOREIGN DATA WRAPPER";
2232  case OBJECT_FOREIGN_SERVER:
2233  return "FOREIGN SERVER";
2234  case OBJECT_FUNCTION:
2235  return "FUNCTION";
2236  case OBJECT_LANGUAGE:
2237  return "LANGUAGE";
2238  case OBJECT_LARGEOBJECT:
2239  return "LARGE OBJECT";
2240  case OBJECT_SCHEMA:
2241  return "SCHEMA";
2242  case OBJECT_PROCEDURE:
2243  return "PROCEDURE";
2244  case OBJECT_ROUTINE:
2245  return "ROUTINE";
2246  case OBJECT_TABLESPACE:
2247  return "TABLESPACE";
2248  case OBJECT_TYPE:
2249  return "TYPE";
2250  /* these currently aren't used */
2251  case OBJECT_ACCESS_METHOD:
2252  case OBJECT_AGGREGATE:
2253  case OBJECT_AMOP:
2254  case OBJECT_AMPROC:
2255  case OBJECT_ATTRIBUTE:
2256  case OBJECT_CAST:
2257  case OBJECT_COLLATION:
2258  case OBJECT_CONVERSION:
2259  case OBJECT_DEFAULT:
2260  case OBJECT_DEFACL:
2261  case OBJECT_DOMCONSTRAINT:
2262  case OBJECT_EVENT_TRIGGER:
2263  case OBJECT_EXTENSION:
2264  case OBJECT_FOREIGN_TABLE:
2265  case OBJECT_INDEX:
2266  case OBJECT_MATVIEW:
2267  case OBJECT_OPCLASS:
2268  case OBJECT_OPERATOR:
2269  case OBJECT_OPFAMILY:
2270  case OBJECT_POLICY:
2271  case OBJECT_PUBLICATION:
2273  case OBJECT_ROLE:
2274  case OBJECT_RULE:
2275  case OBJECT_STATISTIC_EXT:
2276  case OBJECT_SUBSCRIPTION:
2277  case OBJECT_TABCONSTRAINT:
2278  case OBJECT_TRANSFORM:
2279  case OBJECT_TRIGGER:
2281  case OBJECT_TSDICTIONARY:
2282  case OBJECT_TSPARSER:
2283  case OBJECT_TSTEMPLATE:
2284  case OBJECT_USER_MAPPING:
2285  case OBJECT_VIEW:
2286  elog(ERROR, "unsupported object type: %d", (int) objtype);
2287  }
2288 
2289  return "???"; /* keep compiler quiet */
2290 }
2291 
2292 /*
2293  * Return the ObjectType as a string; as above, but use the spelling
2294  * in ALTER DEFAULT PRIVILEGES commands instead. Generally this is just
2295  * the plural.
2296  */
2297 static const char *
2299 {
2300  switch (objtype)
2301  {
2302  case OBJECT_COLUMN:
2303  return "COLUMNS";
2304  case OBJECT_TABLE:
2305  return "TABLES";
2306  case OBJECT_SEQUENCE:
2307  return "SEQUENCES";
2308  case OBJECT_DATABASE:
2309  return "DATABASES";
2310  case OBJECT_DOMAIN:
2311  return "DOMAINS";
2312  case OBJECT_FDW:
2313  return "FOREIGN DATA WRAPPERS";
2314  case OBJECT_FOREIGN_SERVER:
2315  return "FOREIGN SERVERS";
2316  case OBJECT_FUNCTION:
2317  return "FUNCTIONS";
2318  case OBJECT_LANGUAGE:
2319  return "LANGUAGES";
2320  case OBJECT_LARGEOBJECT:
2321  return "LARGE OBJECTS";
2322  case OBJECT_SCHEMA:
2323  return "SCHEMAS";
2324  case OBJECT_PROCEDURE:
2325  return "PROCEDURES";
2326  case OBJECT_ROUTINE:
2327  return "ROUTINES";
2328  case OBJECT_TABLESPACE:
2329  return "TABLESPACES";
2330  case OBJECT_TYPE:
2331  return "TYPES";
2332  /* these currently aren't used */
2333  case OBJECT_ACCESS_METHOD:
2334  case OBJECT_AGGREGATE:
2335  case OBJECT_AMOP:
2336  case OBJECT_AMPROC:
2337  case OBJECT_ATTRIBUTE:
2338  case OBJECT_CAST:
2339  case OBJECT_COLLATION:
2340  case OBJECT_CONVERSION:
2341  case OBJECT_DEFAULT:
2342  case OBJECT_DEFACL:
2343  case OBJECT_DOMCONSTRAINT:
2344  case OBJECT_EVENT_TRIGGER:
2345  case OBJECT_EXTENSION:
2346  case OBJECT_FOREIGN_TABLE:
2347  case OBJECT_INDEX:
2348  case OBJECT_MATVIEW:
2349  case OBJECT_OPCLASS:
2350  case OBJECT_OPERATOR:
2351  case OBJECT_OPFAMILY:
2352  case OBJECT_POLICY:
2353  case OBJECT_PUBLICATION:
2355  case OBJECT_ROLE:
2356  case OBJECT_RULE:
2357  case OBJECT_STATISTIC_EXT:
2358  case OBJECT_SUBSCRIPTION:
2359  case OBJECT_TABCONSTRAINT:
2360  case OBJECT_TRANSFORM:
2361  case OBJECT_TRIGGER:
2363  case OBJECT_TSDICTIONARY:
2364  case OBJECT_TSPARSER:
2365  case OBJECT_TSTEMPLATE:
2366  case OBJECT_USER_MAPPING:
2367  case OBJECT_VIEW:
2368  elog(ERROR, "unsupported object type: %d", (int) objtype);
2369  }
2370 
2371  return "???"; /* keep compiler quiet */
2372 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
bool get_object_namensp_unique(Oid class_id)
#define NIL
Definition: pg_list.h:65
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:322
slist_node next
Definition: fmgr.h:56
static void validate_ddl_tags(const char *filtervar, List *taglist)
union CollectedCommand::@111 d
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define NameGetDatum(X)
Definition: postgres.h:595
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
#define DEBUG1
Definition: elog.h:25
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:196
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
int errhint(const char *fmt,...)
Definition: elog.c:1069
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
Datum pg_event_trigger_dropped_objects(PG_FUNCTION_ARGS)
static int32 next
Definition: blutils.c:213
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
ObjectAddress address
char * getObjectTypeDescription(const ObjectAddress *object)
static const event_trigger_support_data event_trigger_support[]
Definition: event_trigger.c:89
AttrNumber get_object_attnum_oid(Oid class_id)
#define RelationGetDescr(relation)
Definition: rel.h:448
Oid GetUserId(void)
Definition: miscinit.c:380
Datum pg_event_trigger_table_rewrite_reason(PG_FUNCTION_ARGS)
bool trackDroppedObjectsNeeded(void)
#define PointerGetDatum(X)
Definition: postgres.h:556
static void EventTriggerInvoke(List *fn_oid_list, EventTriggerData *trigdata)
#define GetSysCacheOid1(cacheId, oidcol, key1)
Definition: syscache.h:192
const char * objname
#define DatumGetObjectId(X)
Definition: postgres.h:500
char * pstrdup(const char *in)
Definition: mcxt.c:1186
char * getObjectIdentityParts(const ObjectAddress *object, List **objname, List **objargs)
Datum pg_event_trigger_table_rewrite_oid(PG_FUNCTION_ARGS)
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define PG_RETURN_INT32(x)
Definition: fmgr.h:344
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3291
#define AccessShareLock
Definition: lockdefs.h:36
void EventTriggerDDLCommandEnd(Node *parsetree)
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:574
static struct @145 value
List * list_copy(const List *oldlist)
Definition: list.c:1404
Definition: nodes.h:525
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:608
bool superuser(void)
Definition: superuser.c:46
#define MemSet(start, val, len)
Definition: c.h:962
struct CollectedCommand::@111::@114 grant
unsigned char pg_ascii_toupper(unsigned char ch)
Definition: pgstrcasecmp.c:135
const char * tag
Definition: event_trigger.h:28
void EventTriggerInhibitCommandCollection(void)
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:269
void recordDependencyOn(const ObjectAddress *depender, const ObjectAddress *referenced, DependencyType behavior)
Definition: pg_depend.c:43
AttrNumber get_object_attnum_namespace(Oid class_id)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
struct CollectedCommand::@111::@112 simple
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
CollectedCommandType type
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
const char * objidentity
Oid get_event_trigger_oid(const char *trigname, bool missing_ok)
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3410
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
int namestrcpy(Name name, const char *str)
Definition: name.c:250
List * lappend_oid(List *list, Oid datum)
Definition: list.c:358
ObjectClass getObjectClass(const ObjectAddress *object)
Definition: dependency.c:2712
#define OidIsValid(objectId)
Definition: c.h:645
#define TRIGGER_FIRES_ON_ORIGIN
Definition: trigger.h:155
static event_trigger_command_tag_check_result check_ddl_tag(const char *tag)
int SessionReplicationRole
Definition: trigger.c:67
const char * objecttype
static EventTriggerQueryState * currentEventTriggerState
Definition: event_trigger.c:73
static void AlterEventTriggerOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
Oid get_func_rettype(Oid funcid)
Definition: lsyscache.c:1457
EventTriggerEvent
Definition: evtcache.h:19
ObjectAddress AlterEventTriggerOwner(const char *name, Oid newOwnerId)
struct CollectedCommand::@111::@116 createopc
void EventTriggerAlterTableStart(Node *parsetree)
struct CollectedCommand::@111::@118 defprivs
#define DatumGetName(X)
Definition: postgres.h:585
int pg_strncasecmp(const char *s1, const char *s2, size_t n)
Definition: pgstrcasecmp.c:69
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:309
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3352
void pfree(void *pointer)
Definition: mcxt.c:1056
static void slist_init(slist_head *head)
Definition: ilist.h:554
static bool filter_event_trigger(const char **tag, EventTriggerCacheItem *item)
struct CollectedCommand::@111::@117 atscfg
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
static void validate_table_rewrite_tags(const char *filtervar, List *taglist)
void pgstat_init_function_usage(FunctionCallInfo fcinfo, PgStat_FunctionCallUsage *fcu)
Definition: pgstat.c:1620
bool pg_event_trigger_ownercheck(Oid et_oid, Oid roleid)
Definition: aclchk.c:5144
static Datum filter_list_to_array(List *filterlist)
char * getObjectIdentity(const ObjectAddress *object)
static event_trigger_command_tag_check_result check_table_rewrite_ddl_tag(const char *tag)
void EventTriggerDDLCommandStart(Node *parsetree)
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:124
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
Definition: parse_func.c:2101
const char * event
Definition: event_trigger.h:26
ItemPointerData t_self
Definition: htup.h:65
void EventTriggerSQLDrop(Node *parsetree)
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
Definition: c.h:610
static void error_duplicate_filter_variable(const char *defname)
Datum pg_event_trigger_ddl_commands(PG_FUNCTION_ARGS)
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define FunctionCallInvoke(fcinfo)
Definition: fmgr.h:167
static List * EventTriggerCommonSetup(Node *parsetree, EventTriggerEvent event, const char *eventstr, EventTriggerData *trigdata)
void check_stack_depth(void)
Definition: postgres.c:3302
CollectedCommand * currentCommand
Definition: event_trigger.c:67
bool IsUnderPostmaster
Definition: globals.c:109
ObjectClass
Definition: dependency.h:89
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:578
bool isTempNamespace(Oid namespaceId)
Definition: namespace.c:3149
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void EventTriggerCollectAlterTSConfig(AlterTSConfigurationStmt *stmt, Oid cfgId, Oid *dictIds, int ndicts)
void RemoveEventTriggerById(Oid trigOid)
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
struct EventTriggerQueryState * previous
Definition: event_trigger.c:70
MemoryContext TopMemoryContext
Definition: mcxt.c:44
const char * CreateCommandTag(Node *parsetree)
Definition: utility.c:2093
struct CollectedCommand * parent
void EventTriggerCollectAlterOpFam(AlterOpFamilyStmt *stmt, Oid opfamoid, List *operators, List *procedures)
Oid AlterEventTrigger(AlterEventTrigStmt *stmt)
Node * arg
Definition: parsenodes.h:731
ObjectType
Definition: parsenodes.h:1669
bool EventTriggerSupportsObjectClass(ObjectClass objclass)
List * lappend(List *list, void *datum)
Definition: list.c:322
const char * schemaname
static bool slist_is_empty(slist_head *head)
Definition: ilist.h:563
void EventTriggerEndCompleteQuery(void)
event_trigger_command_tag_check_result
Definition: event_trigger.c:81
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:762
struct EventTriggerQueryState EventTriggerQueryState
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
char * NameListToString(List *names)
Definition: namespace.c:3094
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
#define PG_FINALLY()
Definition: elog.h:339
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
AttrNumber get_object_attnum_name(Oid class_id)
static Oid insert_event_trigger_tuple(const char *trigname, const char *eventname, Oid evtOwner, Oid funcoid, List *tags)
void * palloc0(Size size)
Definition: mcxt.c:980
void EventTriggerCollectAlterTableSubcmd(Node *subcmd, ObjectAddress address)
HeapTuple get_catalog_object_by_oid(Relation catalog, AttrNumber oidcol, Oid objectId)
void EventTriggerUndoInhibitCommandCollection(void)
uintptr_t Datum
Definition: postgres.h:367
#define SESSION_REPLICATION_ROLE_REPLICA
Definition: trigger.h:147
void CommandCounterIncrement(void)
Definition: xact.c:1005
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid CreateEventTrigger(CreateEventTrigStmt *stmt)
int work_mem
Definition: globals.c:121
static const char * stringify_adefprivs_objtype(ObjectType objtype)
void EventTriggerCollectAlterDefPrivs(AlterDefaultPrivilegesStmt *stmt)
TupleDesc rd_att
Definition: rel.h:84
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
bool creating_extension
Definition: extension.c:70
int16 attnum
Definition: pg_attribute.h:79
void AlterEventTriggerOwner_oid(Oid trigOid, Oid newOwnerId)
bool EventTriggerSupportsObjectType(ObjectType obtype)
int allowedModes
Definition: execnodes.h:302
#define PG_RETURN_VOID()
Definition: fmgr.h:339
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
SetFunctionReturnMode returnMode
Definition: execnodes.h:304
text * cstring_to_text(const char *s)
Definition: varlena.c:171
FormData_pg_event_trigger * Form_pg_event_trigger
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
Definition: regguts.h:298
void recordDependencyOnCurrentExtension(const ObjectAddress *object, bool isReplace)
Definition: pg_depend.c:138
#define EventTriggerOidIndexId
Definition: indexing.h:263
struct CollectedCommand::@111::@115 opfam
void EventTriggerCollectCreateOpClass(CreateOpClassStmt *stmt, Oid opcoid, List *operators, List *procedures)
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:224
#define InitFunctionCallInfoData(Fcinfo, Flinfo, Nargs, Collation, Context, Resultinfo)
Definition: fmgr.h:150
static int list_length(const List *l)
Definition: pg_list.h:169
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
struct CollectedCommand::@111::@113 alterTable
int pg_qsort_strcmp(const void *a, const void *b)
Definition: qsort.c:232
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:230
const char * name
Definition: encode.c:521
#define InvalidAttrNumber
Definition: attnum.h:23
void EventTriggerAlterTableRelid(Oid objectId)
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define CharGetDatum(X)
Definition: postgres.h:416
Tuplestorestate * setResult
Definition: execnodes.h:307
#define TRIGGER_FIRES_ON_REPLICA
Definition: trigger.h:157
void pgstat_end_function_usage(PgStat_FunctionCallUsage *fcu, bool finalize)
Definition: pgstat.c:1692
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
ExprContext * econtext
Definition: execnodes.h:300
void EventTriggerTableRewrite(Node *parsetree, Oid tableOid, int reason)
#define slist_foreach(iter, lhead)
Definition: ilist.h:700
#define Int32GetDatum(X)
Definition: postgres.h:479
struct SQLDropObject SQLDropObject
TupleDesc setDesc
Definition: execnodes.h:308
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
void list_free(List *list)
Definition: list.c:1377
#define elog(elevel,...)
Definition: elog.h:228
int i
List * EventCacheLookup(EventTriggerEvent event)
Definition: evtcache.c:64
ObjectType objtype
Definition: parsenodes.h:1906
#define NameStr(name)
Definition: c.h:616
#define CStringGetTextDatum(s)
Definition: builtins.h:83
bool isAnyTempNamespace(Oid namespaceId)
Definition: namespace.c:3187
#define PG_FUNCTION_ARGS
Definition: fmgr.h:188
void EventTriggerCollectGrant(InternalGrant *istmt)
char * defname
Definition: parsenodes.h:730
ArrayType * strlist_to_textarray(List *list)
void EventTriggerCollectSimpleCommand(ObjectAddress address, ObjectAddress secondaryObject, Node *parsetree)
#define copyObject(obj)
Definition: nodes.h:641
bool is_objectclass_supported(Oid class_id)
#define PG_TRY()
Definition: elog.h:322
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static color newsub(struct colormap *cm, color co)
Definition: regc_color.c:389
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31
Definition: pg_list.h:50
#define PG_RETURN_OID(x)
Definition: fmgr.h:350
static const char * stringify_grant_objtype(ObjectType objtype)
int16 AttrNumber
Definition: attnum.h:21
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:183
#define PG_END_TRY()
Definition: elog.h:347
#define lfirst_oid(lc)
Definition: pg_list.h:192
ObjectAddress address
bool EventTriggerBeginCompleteQuery(void)
void EventTriggerAlterTableEnd(void)