LCOV - code coverage report
Current view: top level - src/backend/utils/cache - evtcache.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 72 75 96.0 %
Date: 2020-06-03 11:07:14 Functions: 4 4 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * evtcache.c
       4             :  *    Special-purpose cache for event trigger data.
       5             :  *
       6             :  * Portions Copyright (c) 1996-2020, 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"
      19             : #include "catalog/indexing.h"
      20             : #include "catalog/pg_event_trigger.h"
      21             : #include "catalog/pg_type.h"
      22             : #include "commands/trigger.h"
      23             : #include "tcop/cmdtag.h"
      24             : #include "utils/array.h"
      25             : #include "utils/builtins.h"
      26             : #include "utils/catcache.h"
      27             : #include "utils/evtcache.h"
      28             : #include "utils/hsearch.h"
      29             : #include "utils/inval.h"
      30             : #include "utils/memutils.h"
      31             : #include "utils/rel.h"
      32             : #include "utils/snapmgr.h"
      33             : #include "utils/syscache.h"
      34             : 
      35             : typedef enum
      36             : {
      37             :     ETCS_NEEDS_REBUILD,
      38             :     ETCS_REBUILD_STARTED,
      39             :     ETCS_VALID
      40             : } EventTriggerCacheStateType;
      41             : 
      42             : typedef struct
      43             : {
      44             :     EventTriggerEvent event;
      45             :     List       *triggerlist;
      46             : } EventTriggerCacheEntry;
      47             : 
      48             : static HTAB *EventTriggerCache;
      49             : static MemoryContext EventTriggerCacheContext;
      50             : static EventTriggerCacheStateType EventTriggerCacheState = ETCS_NEEDS_REBUILD;
      51             : 
      52             : static void BuildEventTriggerCache(void);
      53             : static void InvalidateEventCacheCallback(Datum arg,
      54             :                                          int cacheid, uint32 hashvalue);
      55             : static Bitmapset *DecodeTextArrayToBitmapset(Datum array);
      56             : 
      57             : /*
      58             :  * Search the event cache by trigger event.
      59             :  *
      60             :  * Note that the caller had better copy any data it wants to keep around
      61             :  * across any operation that might touch a system catalog into some other
      62             :  * memory context, since a cache reset could blow the return value away.
      63             :  */
      64             : List *
      65      846644 : EventCacheLookup(EventTriggerEvent event)
      66             : {
      67             :     EventTriggerCacheEntry *entry;
      68             : 
      69      846644 :     if (EventTriggerCacheState != ETCS_VALID)
      70        3252 :         BuildEventTriggerCache();
      71      846644 :     entry = hash_search(EventTriggerCache, &event, HASH_FIND, NULL);
      72      846644 :     return entry != NULL ? entry->triggerlist : NIL;
      73             : }
      74             : 
      75             : /*
      76             :  * Rebuild the event trigger cache.
      77             :  */
      78             : static void
      79        3252 : BuildEventTriggerCache(void)
      80             : {
      81             :     HASHCTL     ctl;
      82             :     HTAB       *cache;
      83             :     MemoryContext oldcontext;
      84             :     Relation    rel;
      85             :     Relation    irel;
      86             :     SysScanDesc scan;
      87             : 
      88        3252 :     if (EventTriggerCacheContext != NULL)
      89             :     {
      90             :         /*
      91             :          * Free up any memory already allocated in EventTriggerCacheContext.
      92             :          * This can happen either because a previous rebuild failed, or
      93             :          * because an invalidation happened before the rebuild was complete.
      94             :          */
      95         428 :         MemoryContextResetAndDeleteChildren(EventTriggerCacheContext);
      96             :     }
      97             :     else
      98             :     {
      99             :         /*
     100             :          * This is our first time attempting to build the cache, so we need to
     101             :          * set up the memory context and register a syscache callback to
     102             :          * capture future invalidation events.
     103             :          */
     104        2824 :         if (CacheMemoryContext == NULL)
     105           0 :             CreateCacheMemoryContext();
     106        2824 :         EventTriggerCacheContext =
     107        2824 :             AllocSetContextCreate(CacheMemoryContext,
     108             :                                   "EventTriggerCache",
     109             :                                   ALLOCSET_DEFAULT_SIZES);
     110        2824 :         CacheRegisterSyscacheCallback(EVENTTRIGGEROID,
     111             :                                       InvalidateEventCacheCallback,
     112             :                                       (Datum) 0);
     113             :     }
     114             : 
     115             :     /* Switch to correct memory context. */
     116        3252 :     oldcontext = MemoryContextSwitchTo(EventTriggerCacheContext);
     117             : 
     118             :     /* Prevent the memory context from being nuked while we're rebuilding. */
     119        3252 :     EventTriggerCacheState = ETCS_REBUILD_STARTED;
     120             : 
     121             :     /* Create new hash table. */
     122       45528 :     MemSet(&ctl, 0, sizeof(ctl));
     123        3252 :     ctl.keysize = sizeof(EventTriggerEvent);
     124        3252 :     ctl.entrysize = sizeof(EventTriggerCacheEntry);
     125        3252 :     ctl.hcxt = EventTriggerCacheContext;
     126        3252 :     cache = hash_create("Event Trigger Cache", 32, &ctl,
     127             :                         HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     128             : 
     129             :     /*
     130             :      * Prepare to scan pg_event_trigger in name order.
     131             :      */
     132        3252 :     rel = relation_open(EventTriggerRelationId, AccessShareLock);
     133        3252 :     irel = index_open(EventTriggerNameIndexId, AccessShareLock);
     134        3252 :     scan = systable_beginscan_ordered(rel, irel, NULL, 0, NULL);
     135             : 
     136             :     /*
     137             :      * Build a cache item for each pg_event_trigger tuple, and append each one
     138             :      * to the appropriate cache entry.
     139             :      */
     140             :     for (;;)
     141         198 :     {
     142             :         HeapTuple   tup;
     143             :         Form_pg_event_trigger form;
     144             :         char       *evtevent;
     145             :         EventTriggerEvent event;
     146             :         EventTriggerCacheItem *item;
     147             :         Datum       evttags;
     148             :         bool        evttags_isnull;
     149             :         EventTriggerCacheEntry *entry;
     150             :         bool        found;
     151             : 
     152             :         /* Get next tuple. */
     153        3450 :         tup = systable_getnext_ordered(scan, ForwardScanDirection);
     154        3450 :         if (!HeapTupleIsValid(tup))
     155        3252 :             break;
     156             : 
     157             :         /* Skip trigger if disabled. */
     158         198 :         form = (Form_pg_event_trigger) GETSTRUCT(tup);
     159         198 :         if (form->evtenabled == TRIGGER_DISABLED)
     160          16 :             continue;
     161             : 
     162             :         /* Decode event name. */
     163         182 :         evtevent = NameStr(form->evtevent);
     164         182 :         if (strcmp(evtevent, "ddl_command_start") == 0)
     165          48 :             event = EVT_DDLCommandStart;
     166         134 :         else if (strcmp(evtevent, "ddl_command_end") == 0)
     167          90 :             event = EVT_DDLCommandEnd;
     168          44 :         else if (strcmp(evtevent, "sql_drop") == 0)
     169          34 :             event = EVT_SQLDrop;
     170          10 :         else if (strcmp(evtevent, "table_rewrite") == 0)
     171          10 :             event = EVT_TableRewrite;
     172             :         else
     173           0 :             continue;
     174             : 
     175             :         /* Allocate new cache item. */
     176         182 :         item = palloc0(sizeof(EventTriggerCacheItem));
     177         182 :         item->fnoid = form->evtfoid;
     178         182 :         item->enabled = form->evtenabled;
     179             : 
     180             :         /* Decode and sort tags array. */
     181         182 :         evttags = heap_getattr(tup, Anum_pg_event_trigger_evttags,
     182             :                                RelationGetDescr(rel), &evttags_isnull);
     183         182 :         if (!evttags_isnull)
     184          52 :             item->tagset = DecodeTextArrayToBitmapset(evttags);
     185             : 
     186             :         /* Add to cache entry. */
     187         182 :         entry = hash_search(cache, &event, HASH_ENTER, &found);
     188         182 :         if (found)
     189          16 :             entry->triggerlist = lappend(entry->triggerlist, item);
     190             :         else
     191         166 :             entry->triggerlist = list_make1(item);
     192             :     }
     193             : 
     194             :     /* Done with pg_event_trigger scan. */
     195        3252 :     systable_endscan_ordered(scan);
     196        3252 :     index_close(irel, AccessShareLock);
     197        3252 :     relation_close(rel, AccessShareLock);
     198             : 
     199             :     /* Restore previous memory context. */
     200        3252 :     MemoryContextSwitchTo(oldcontext);
     201             : 
     202             :     /* Install new cache. */
     203        3252 :     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             :      */
     211        3252 :     if (EventTriggerCacheState == ETCS_REBUILD_STARTED)
     212        3252 :         EventTriggerCacheState = ETCS_VALID;
     213        3252 : }
     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 *
     223          52 : DecodeTextArrayToBitmapset(Datum array)
     224             : {
     225          52 :     ArrayType  *arr = DatumGetArrayTypeP(array);
     226             :     Datum      *elems;
     227             :     Bitmapset  *bms;
     228             :     int         i;
     229             :     int         nelems;
     230             : 
     231          52 :     if (ARR_NDIM(arr) != 1 || ARR_HASNULL(arr) || ARR_ELEMTYPE(arr) != TEXTOID)
     232           0 :         elog(ERROR, "expected 1-D text array");
     233          52 :     deconstruct_array(arr, TEXTOID, -1, false, TYPALIGN_INT,
     234             :                       &elems, NULL, &nelems);
     235             : 
     236         172 :     for (bms = NULL, i = 0; i < nelems; ++i)
     237             :     {
     238         120 :         char       *str = TextDatumGetCString(elems[i]);
     239             : 
     240         120 :         bms = bms_add_member(bms, GetCommandTagEnum(str));
     241         120 :         pfree(str);
     242             :     }
     243             : 
     244          52 :     pfree(elems);
     245             : 
     246          52 :     return bms;
     247             : }
     248             : 
     249             : /*
     250             :  * Flush all cache entries when pg_event_trigger is updated.
     251             :  *
     252             :  * This should be rare enough that we don't need to be very granular about
     253             :  * it, so we just blow away everything, which also avoids the possibility of
     254             :  * memory leaks.
     255             :  */
     256             : static void
     257         950 : InvalidateEventCacheCallback(Datum arg, int cacheid, uint32 hashvalue)
     258             : {
     259             :     /*
     260             :      * If the cache isn't valid, then there might be a rebuild in progress, so
     261             :      * we can't immediately blow it away.  But it's advantageous to do this
     262             :      * when possible, so as to immediately free memory.
     263             :      */
     264         950 :     if (EventTriggerCacheState == ETCS_VALID)
     265             :     {
     266         464 :         MemoryContextResetAndDeleteChildren(EventTriggerCacheContext);
     267         464 :         EventTriggerCache = NULL;
     268             :     }
     269             : 
     270             :     /* Mark cache for rebuild. */
     271         950 :     EventTriggerCacheState = ETCS_NEEDS_REBUILD;
     272         950 : }

Generated by: LCOV version 1.13