LCOV - code coverage report
Current view: top level - src/backend/utils/cache - evtcache.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 73 76 96.1 %
Date: 2023-12-05 09:10:49 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-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"
      19             : #include "catalog/pg_event_trigger.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             : {
      36             :     ETCS_NEEDS_REBUILD,
      37             :     ETCS_REBUILD_STARTED,
      38             :     ETCS_VALID,
      39             : } EventTriggerCacheStateType;
      40             : 
      41             : typedef struct
      42             : {
      43             :     EventTriggerEvent event;
      44             :     List       *triggerlist;
      45             : } EventTriggerCacheEntry;
      46             : 
      47             : static HTAB *EventTriggerCache;
      48             : static MemoryContext EventTriggerCacheContext;
      49             : static EventTriggerCacheStateType EventTriggerCacheState = ETCS_NEEDS_REBUILD;
      50             : 
      51             : static void BuildEventTriggerCache(void);
      52             : static void InvalidateEventCacheCallback(Datum arg,
      53             :                                          int cacheid, uint32 hashvalue);
      54             : static Bitmapset *DecodeTextArrayToBitmapset(Datum array);
      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 *
      64      708572 : EventCacheLookup(EventTriggerEvent event)
      65             : {
      66             :     EventTriggerCacheEntry *entry;
      67             : 
      68      708572 :     if (EventTriggerCacheState != ETCS_VALID)
      69        5914 :         BuildEventTriggerCache();
      70      708572 :     entry = hash_search(EventTriggerCache, &event, HASH_FIND, NULL);
      71      708572 :     return entry != NULL ? entry->triggerlist : NIL;
      72             : }
      73             : 
      74             : /*
      75             :  * Rebuild the event trigger cache.
      76             :  */
      77             : static void
      78        5914 : BuildEventTriggerCache(void)
      79             : {
      80             :     HASHCTL     ctl;
      81             :     HTAB       *cache;
      82             :     MemoryContext oldcontext;
      83             :     Relation    rel;
      84             :     Relation    irel;
      85             :     SysScanDesc scan;
      86             : 
      87        5914 :     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             :          */
      94         734 :         MemoryContextReset(EventTriggerCacheContext);
      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        5180 :         if (CacheMemoryContext == NULL)
     104           0 :             CreateCacheMemoryContext();
     105        5180 :         EventTriggerCacheContext =
     106        5180 :             AllocSetContextCreate(CacheMemoryContext,
     107             :                                   "EventTriggerCache",
     108             :                                   ALLOCSET_DEFAULT_SIZES);
     109        5180 :         CacheRegisterSyscacheCallback(EVENTTRIGGEROID,
     110             :                                       InvalidateEventCacheCallback,
     111             :                                       (Datum) 0);
     112             :     }
     113             : 
     114             :     /* Switch to correct memory context. */
     115        5914 :     oldcontext = MemoryContextSwitchTo(EventTriggerCacheContext);
     116             : 
     117             :     /* Prevent the memory context from being nuked while we're rebuilding. */
     118        5914 :     EventTriggerCacheState = ETCS_REBUILD_STARTED;
     119             : 
     120             :     /* Create new hash table. */
     121        5914 :     ctl.keysize = sizeof(EventTriggerEvent);
     122        5914 :     ctl.entrysize = sizeof(EventTriggerCacheEntry);
     123        5914 :     ctl.hcxt = EventTriggerCacheContext;
     124        5914 :     cache = hash_create("EventTriggerCacheHash", 32, &ctl,
     125             :                         HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     126             : 
     127             :     /*
     128             :      * Prepare to scan pg_event_trigger in name order.
     129             :      */
     130        5914 :     rel = relation_open(EventTriggerRelationId, AccessShareLock);
     131        5914 :     irel = index_open(EventTriggerNameIndexId, AccessShareLock);
     132        5914 :     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         636 :     {
     140             :         HeapTuple   tup;
     141             :         Form_pg_event_trigger form;
     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. */
     151        6550 :         tup = systable_getnext_ordered(scan, ForwardScanDirection);
     152        6550 :         if (!HeapTupleIsValid(tup))
     153        5914 :             break;
     154             : 
     155             :         /* Skip trigger if disabled. */
     156         636 :         form = (Form_pg_event_trigger) GETSTRUCT(tup);
     157         636 :         if (form->evtenabled == TRIGGER_DISABLED)
     158          34 :             continue;
     159             : 
     160             :         /* Decode event name. */
     161         602 :         evtevent = NameStr(form->evtevent);
     162         602 :         if (strcmp(evtevent, "ddl_command_start") == 0)
     163          80 :             event = EVT_DDLCommandStart;
     164         522 :         else if (strcmp(evtevent, "ddl_command_end") == 0)
     165         140 :             event = EVT_DDLCommandEnd;
     166         382 :         else if (strcmp(evtevent, "sql_drop") == 0)
     167         116 :             event = EVT_SQLDrop;
     168         266 :         else if (strcmp(evtevent, "table_rewrite") == 0)
     169          16 :             event = EVT_TableRewrite;
     170         250 :         else if (strcmp(evtevent, "login") == 0)
     171         250 :             event = EVT_Login;
     172             :         else
     173           0 :             continue;
     174             : 
     175             :         /* Allocate new cache item. */
     176         602 :         item = palloc0(sizeof(EventTriggerCacheItem));
     177         602 :         item->fnoid = form->evtfoid;
     178         602 :         item->enabled = form->evtenabled;
     179             : 
     180             :         /* Decode and sort tags array. */
     181         602 :         evttags = heap_getattr(tup, Anum_pg_event_trigger_evttags,
     182             :                                RelationGetDescr(rel), &evttags_isnull);
     183         602 :         if (!evttags_isnull)
     184         168 :             item->tagset = DecodeTextArrayToBitmapset(evttags);
     185             : 
     186             :         /* Add to cache entry. */
     187         602 :         entry = hash_search(cache, &event, HASH_ENTER, &found);
     188         602 :         if (found)
     189          24 :             entry->triggerlist = lappend(entry->triggerlist, item);
     190             :         else
     191         578 :             entry->triggerlist = list_make1(item);
     192             :     }
     193             : 
     194             :     /* Done with pg_event_trigger scan. */
     195        5914 :     systable_endscan_ordered(scan);
     196        5914 :     index_close(irel, AccessShareLock);
     197        5914 :     relation_close(rel, AccessShareLock);
     198             : 
     199             :     /* Restore previous memory context. */
     200        5914 :     MemoryContextSwitchTo(oldcontext);
     201             : 
     202             :     /* Install new cache. */
     203        5914 :     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        5914 :     if (EventTriggerCacheState == ETCS_REBUILD_STARTED)
     212        5914 :         EventTriggerCacheState = ETCS_VALID;
     213        5914 : }
     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         168 : DecodeTextArrayToBitmapset(Datum array)
     224             : {
     225         168 :     ArrayType  *arr = DatumGetArrayTypeP(array);
     226             :     Datum      *elems;
     227             :     Bitmapset  *bms;
     228             :     int         i;
     229             :     int         nelems;
     230             : 
     231         168 :     if (ARR_NDIM(arr) != 1 || ARR_HASNULL(arr) || ARR_ELEMTYPE(arr) != TEXTOID)
     232           0 :         elog(ERROR, "expected 1-D text array");
     233         168 :     deconstruct_array_builtin(arr, TEXTOID, &elems, NULL, &nelems);
     234             : 
     235         438 :     for (bms = NULL, i = 0; i < nelems; ++i)
     236             :     {
     237         270 :         char       *str = TextDatumGetCString(elems[i]);
     238             : 
     239         270 :         bms = bms_add_member(bms, GetCommandTagEnum(str));
     240         270 :         pfree(str);
     241             :     }
     242             : 
     243         168 :     pfree(elems);
     244             : 
     245         168 :     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
     256        1580 : InvalidateEventCacheCallback(Datum arg, int cacheid, uint32 hashvalue)
     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             :      */
     263        1580 :     if (EventTriggerCacheState == ETCS_VALID)
     264             :     {
     265         784 :         MemoryContextReset(EventTriggerCacheContext);
     266         784 :         EventTriggerCache = NULL;
     267             :     }
     268             : 
     269             :     /* Mark cache for rebuild. */
     270        1580 :     EventTriggerCacheState = ETCS_NEEDS_REBUILD;
     271        1580 : }

Generated by: LCOV version 1.14