PostgreSQL Source Code  git master
evtcache.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * evtcache.c
4  * Special-purpose cache for event trigger data.
5  *
6  * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/backend/utils/cache/evtcache.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"
20 #include "catalog/pg_type.h"
21 #include "commands/trigger.h"
22 #include "tcop/cmdtag.h"
23 #include "utils/array.h"
24 #include "utils/builtins.h"
25 #include "utils/catcache.h"
26 #include "utils/evtcache.h"
27 #include "utils/hsearch.h"
28 #include "utils/inval.h"
29 #include "utils/memutils.h"
30 #include "utils/rel.h"
31 #include "utils/snapmgr.h"
32 #include "utils/syscache.h"
33 
34 typedef enum
35 {
40 
41 typedef struct
42 {
46 
50 
51 static void BuildEventTriggerCache(void);
53  int cacheid, uint32 hashvalue);
55 
56 /*
57  * Search the event cache by trigger event.
58  *
59  * Note that the caller had better copy any data it wants to keep around
60  * across any operation that might touch a system catalog into some other
61  * memory context, since a cache reset could blow the return value away.
62  */
63 List *
65 {
67 
70  entry = hash_search(EventTriggerCache, &event, HASH_FIND, NULL);
71  return entry != NULL ? entry->triggerlist : NIL;
72 }
73 
74 /*
75  * Rebuild the event trigger cache.
76  */
77 static void
79 {
80  HASHCTL ctl;
81  HTAB *cache;
82  MemoryContext oldcontext;
83  Relation rel;
84  Relation irel;
85  SysScanDesc scan;
86 
87  if (EventTriggerCacheContext != NULL)
88  {
89  /*
90  * Free up any memory already allocated in EventTriggerCacheContext.
91  * This can happen either because a previous rebuild failed, or
92  * because an invalidation happened before the rebuild was complete.
93  */
95  }
96  else
97  {
98  /*
99  * This is our first time attempting to build the cache, so we need to
100  * set up the memory context and register a syscache callback to
101  * capture future invalidation events.
102  */
103  if (CacheMemoryContext == NULL)
107  "EventTriggerCache",
111  (Datum) 0);
112  }
113 
114  /* Switch to correct memory context. */
116 
117  /* Prevent the memory context from being nuked while we're rebuilding. */
119 
120  /* Create new hash table. */
121  ctl.keysize = sizeof(EventTriggerEvent);
122  ctl.entrysize = sizeof(EventTriggerCacheEntry);
124  cache = hash_create("EventTriggerCacheHash", 32, &ctl,
126 
127  /*
128  * Prepare to scan pg_event_trigger in name order.
129  */
130  rel = relation_open(EventTriggerRelationId, AccessShareLock);
131  irel = index_open(EventTriggerNameIndexId, AccessShareLock);
132  scan = systable_beginscan_ordered(rel, irel, NULL, 0, NULL);
133 
134  /*
135  * Build a cache item for each pg_event_trigger tuple, and append each one
136  * to the appropriate cache entry.
137  */
138  for (;;)
139  {
140  HeapTuple tup;
142  char *evtevent;
143  EventTriggerEvent event;
144  EventTriggerCacheItem *item;
145  Datum evttags;
146  bool evttags_isnull;
147  EventTriggerCacheEntry *entry;
148  bool found;
149 
150  /* Get next tuple. */
152  if (!HeapTupleIsValid(tup))
153  break;
154 
155  /* Skip trigger if disabled. */
156  form = (Form_pg_event_trigger) GETSTRUCT(tup);
157  if (form->evtenabled == TRIGGER_DISABLED)
158  continue;
159 
160  /* Decode event name. */
161  evtevent = NameStr(form->evtevent);
162  if (strcmp(evtevent, "ddl_command_start") == 0)
163  event = EVT_DDLCommandStart;
164  else if (strcmp(evtevent, "ddl_command_end") == 0)
165  event = EVT_DDLCommandEnd;
166  else if (strcmp(evtevent, "sql_drop") == 0)
167  event = EVT_SQLDrop;
168  else if (strcmp(evtevent, "table_rewrite") == 0)
169  event = EVT_TableRewrite;
170  else if (strcmp(evtevent, "login") == 0)
171  event = EVT_Login;
172  else
173  continue;
174 
175  /* Allocate new cache item. */
176  item = palloc0(sizeof(EventTriggerCacheItem));
177  item->fnoid = form->evtfoid;
178  item->enabled = form->evtenabled;
179 
180  /* Decode and sort tags array. */
181  evttags = heap_getattr(tup, Anum_pg_event_trigger_evttags,
182  RelationGetDescr(rel), &evttags_isnull);
183  if (!evttags_isnull)
184  item->tagset = DecodeTextArrayToBitmapset(evttags);
185 
186  /* Add to cache entry. */
187  entry = hash_search(cache, &event, HASH_ENTER, &found);
188  if (found)
189  entry->triggerlist = lappend(entry->triggerlist, item);
190  else
191  entry->triggerlist = list_make1(item);
192  }
193 
194  /* Done with pg_event_trigger scan. */
198 
199  /* Restore previous memory context. */
200  MemoryContextSwitchTo(oldcontext);
201 
202  /* Install new cache. */
203  EventTriggerCache = cache;
204 
205  /*
206  * If the cache has been invalidated since we entered this routine, we
207  * still use and return the cache we just finished constructing, to avoid
208  * infinite loops, but we leave the cache marked stale so that we'll
209  * rebuild it again on next access. Otherwise, we mark the cache valid.
210  */
213 }
214 
215 /*
216  * Decode text[] to a Bitmapset of CommandTags.
217  *
218  * We could avoid a bit of overhead here if we were willing to duplicate some
219  * of the logic from deconstruct_array, but it doesn't seem worth the code
220  * complexity.
221  */
222 static Bitmapset *
224 {
225  ArrayType *arr = DatumGetArrayTypeP(array);
226  Datum *elems;
227  Bitmapset *bms;
228  int i;
229  int nelems;
230 
231  if (ARR_NDIM(arr) != 1 || ARR_HASNULL(arr) || ARR_ELEMTYPE(arr) != TEXTOID)
232  elog(ERROR, "expected 1-D text array");
233  deconstruct_array_builtin(arr, TEXTOID, &elems, NULL, &nelems);
234 
235  for (bms = NULL, i = 0; i < nelems; ++i)
236  {
237  char *str = TextDatumGetCString(elems[i]);
238 
239  bms = bms_add_member(bms, GetCommandTagEnum(str));
240  pfree(str);
241  }
242 
243  pfree(elems);
244 
245  return bms;
246 }
247 
248 /*
249  * Flush all cache entries when pg_event_trigger is updated.
250  *
251  * This should be rare enough that we don't need to be very granular about
252  * it, so we just blow away everything, which also avoids the possibility of
253  * memory leaks.
254  */
255 static void
257 {
258  /*
259  * If the cache isn't valid, then there might be a rebuild in progress, so
260  * we can't immediately blow it away. But it's advantageous to do this
261  * when possible, so as to immediately free memory.
262  */
264  {
266  EventTriggerCache = NULL;
267  }
268 
269  /* Mark cache for rebuild. */
271 }
#define ARR_NDIM(a)
Definition: array.h:290
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_HASNULL(a)
Definition: array.h:291
void deconstruct_array_builtin(ArrayType *array, Oid elmtype, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3679
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:753
#define TextDatumGetCString(d)
Definition: builtins.h:95
#define NameStr(name)
Definition: c.h:735
unsigned int uint32
Definition: c.h:495
void CreateCacheMemoryContext(void)
Definition: catcache.c:667
CommandTag GetCommandTagEnum(const char *commandname)
Definition: cmdtag.c:84
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
#define ERROR
Definition: elog.h:39
static void BuildEventTriggerCache(void)
Definition: evtcache.c:78
static void InvalidateEventCacheCallback(Datum arg, int cacheid, uint32 hashvalue)
Definition: evtcache.c:256
static MemoryContext EventTriggerCacheContext
Definition: evtcache.c:48
EventTriggerCacheStateType
Definition: evtcache.c:35
@ ETCS_REBUILD_STARTED
Definition: evtcache.c:37
@ ETCS_NEEDS_REBUILD
Definition: evtcache.c:36
@ ETCS_VALID
Definition: evtcache.c:38
static Bitmapset * DecodeTextArrayToBitmapset(Datum array)
Definition: evtcache.c:223
List * EventCacheLookup(EventTriggerEvent event)
Definition: evtcache.c:64
static HTAB * EventTriggerCache
Definition: evtcache.c:47
static EventTriggerCacheStateType EventTriggerCacheState
Definition: evtcache.c:49
EventTriggerEvent
Definition: evtcache.h:21
@ EVT_SQLDrop
Definition: evtcache.h:24
@ EVT_Login
Definition: evtcache.h:26
@ EVT_DDLCommandEnd
Definition: evtcache.h:23
@ EVT_DDLCommandStart
Definition: evtcache.h:22
@ EVT_TableRewrite
Definition: evtcache.h:25
SysScanDesc systable_beginscan_ordered(Relation heapRelation, Relation indexRelation, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:646
void systable_endscan_ordered(SysScanDesc sysscan)
Definition: genam.c:736
HeapTuple systable_getnext_ordered(SysScanDesc sysscan, ScanDirection direction)
Definition: genam.c:711
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1518
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:338
#define AccessShareLock
Definition: lockdefs.h:36
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:330
void pfree(void *pointer)
Definition: mcxt.c:1456
void * palloc0(Size size)
Definition: mcxt.c:1257
MemoryContext CacheMemoryContext
Definition: mcxt.c:144
#define AllocSetContextCreate
Definition: memutils.h:126
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:150
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
void * arg
FormData_pg_event_trigger * Form_pg_event_trigger
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
uintptr_t Datum
Definition: postgres.h:64
#define RelationGetDescr(relation)
Definition: rel.h:530
@ ForwardScanDirection
Definition: sdir.h:28
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:48
EventTriggerEvent event
Definition: evtcache.c:43
Bitmapset * tagset
Definition: evtcache.h:33
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
Definition: dynahash.c:220
Definition: pg_list.h:54
@ EVENTTRIGGEROID
Definition: syscache.h:60
#define TRIGGER_DISABLED
Definition: trigger.h:152