3030#include "postgres.h"
3131
3232#include "catalog/pg_type.h"
33+ #include "common/hashfn.h"
3334#include "funcapi.h"
35+ #include "lib/ilist.h"
3436#include "regex/regex.h"
3537#include "utils/array.h"
3638#include "utils/builtins.h"
@@ -67,18 +69,18 @@ typedef struct regexp_matches_ctx
6769} regexp_matches_ctx ;
6870
6971/*
70- * We cache precompiled regular expressions using a "self organizing list"
71- * structure, in which recently-used items tend to be near the front.
72- * Whenever we use an entry, it's moved up to the front of the list.
73- * Over time, an item's average position corresponds to its frequency of use.
72+ * We cache precompiled regular expressions in a hash table keyed by the
73+ * pattern string, compile flags and collation. The cached entries are also
74+ * kept in a list ordered by recency of use: whenever we use an entry, it's
75+ * moved to the front of the list, and when the cache is full we discard the
76+ * entry at the end of the list to make room for a new one.
7477 *
75- * When we first create an entry, it's inserted at the front of
76- * the array, dropping the entry at the end of the array if necessary to
77- * make room. (This might seem to be weighting the new entry too heavily,
78- * but if we insert new entries further back, we'll be unable to adjust to
79- * a sudden shift in the query mix where we are presented with MAX_CACHED_RES
80- * never-before-seen items used circularly. We ought to be able to handle
81- * that case, so we have to insert at the front.)
78+ * A new entry is likewise inserted at the front of the list. (This might
79+ * seem to be weighting the new entry too heavily, but if we insert new
80+ * entries further back, we'll be unable to adjust to a sudden shift in the
81+ * query mix where we are presented with MAX_CACHED_RES never-before-seen
82+ * items used circularly. We ought to be able to handle that case, so we have
83+ * to insert at the front.)
8284 *
8385 * Knuth mentions a variant strategy in which a used item is moved up just
8486 * one place in the list. Although he says this uses fewer comparisons on
@@ -88,6 +90,11 @@ typedef struct regexp_matches_ctx
8890 * patterns are seen will "fail to keep up" and will drop off the end of the
8991 * cache. With move-to-front, a reusable pattern is guaranteed to stay in
9092 * the cache as long as it's used at least once in every MAX_CACHED_RES uses.
93+ *
94+ * Each compiled regexp lives in its own memory context, together with its
95+ * cached_re_str, so the regex_t returned by RE_compile_and_cache() stays put
96+ * until the entry is discarded. The hash table only stores pointers to the
97+ * cached_re_str structs.
9198 */
9299
93100/* this is the maximum number of cached regular expressions */
@@ -107,13 +114,70 @@ typedef struct cached_re_str
107114 int cre_flags ; /* compile flags: extended,icase etc */
108115 Oid cre_collation ; /* collation to use */
109116 regex_t cre_re ; /* the compiled regular expression */
117+ dlist_node cre_lru_node ; /* link in re_lru_list */
110118} cached_re_str ;
111119
112- static int num_res = 0 ; /* # of cached re's */
113- static cached_re_str re_array [MAX_CACHED_RES ]; /* cached re's */
120+ /* hash key for the regexp cache */
121+ typedef struct RegexpCacheKey
122+ {
123+ const char * pat ; /* RE (not null terminated!) */
124+ int pat_len ; /* length of RE, in bytes */
125+ int flags ; /* compile flags */
126+ Oid collation ; /* collation to use */
127+ } RegexpCacheKey ;
128+
129+ /* hash table entry for the regexp cache */
130+ typedef struct RegexpCacheEntry
131+ {
132+ RegexpCacheKey key ; /* key.pat points to cre->cre_pat */
133+ cached_re_str * cre ; /* the cached regexp */
134+ uint32 hash ; /* hash value of key */
135+ char status ; /* hash status */
136+ } RegexpCacheEntry ;
137+
138+ static inline uint32
139+ regexp_cache_key_hash (RegexpCacheKey key )
140+ {
141+ uint32 h ;
142+
143+ h = hash_bytes ((const unsigned char * ) key .pat , key .pat_len );
144+ h = hash_combine (h , murmurhash32 ((uint32 ) key .flags ));
145+ h = hash_combine (h , murmurhash32 ((uint32 ) key .collation ));
146+
147+ return h ;
148+ }
149+
150+ static inline bool
151+ regexp_cache_key_equal (RegexpCacheKey a , RegexpCacheKey b )
152+ {
153+ return a .pat_len == b .pat_len &&
154+ a .flags == b .flags &&
155+ a .collation == b .collation &&
156+ memcmp (a .pat , b .pat , a .pat_len ) == 0 ;
157+ }
158+
159+ #define SH_PREFIX recache
160+ #define SH_ELEMENT_TYPE RegexpCacheEntry
161+ #define SH_KEY_TYPE RegexpCacheKey
162+ #define SH_KEY key
163+ #define SH_HASH_KEY (tb , key ) regexp_cache_key_hash(key)
164+ #define SH_EQUAL (tb , a , b ) regexp_cache_key_equal(a, b)
165+ #define SH_STORE_HASH
166+ #define SH_GET_HASH (tb , a ) a->hash
167+ #define SH_SCOPE static inline
168+ #define SH_DECLARE
169+ #define SH_DEFINE
170+ #include "lib/simplehash.h"
171+
172+ /* cached re's, by key */
173+ static recache_hash * re_hash = NULL ;
174+
175+ /* cached re's, most recently used first */
176+ static dlist_head re_lru_list = DLIST_STATIC_INIT (re_lru_list );
114177
115178
116179/* Local functions */
180+ static void RE_cache_discard_lru (void );
117181static regexp_matches_ctx * setup_regexp_matches (text * orig_str , text * pattern ,
118182 pg_re_flags * re_flags ,
119183 int start_search ,
@@ -144,49 +208,59 @@ RE_compile_and_cache(text *text_re, int cflags, Oid collation)
144208 char * text_re_val = VARDATA_ANY (text_re );
145209 pg_wchar * pattern ;
146210 int pattern_len ;
147- int i ;
148211 int regcomp_result ;
149- cached_re_str re_temp ;
212+ RegexpCacheKey key ;
213+ uint32 hash ;
214+ RegexpCacheEntry * entry ;
215+ cached_re_str * cre ;
216+ MemoryContext cre_context ;
150217 char errMsg [100 ];
151218 MemoryContext oldcontext ;
219+ bool found ;
220+
221+ /* Set up the cache on first go through. */
222+ if (unlikely (re_hash == NULL ))
223+ {
224+ if (RegexpCacheMemoryContext == NULL )
225+ RegexpCacheMemoryContext =
226+ AllocSetContextCreate (TopMemoryContext ,
227+ "RegexpCacheMemoryContext" ,
228+ ALLOCSET_SMALL_SIZES );
229+ re_hash = recache_create (RegexpCacheMemoryContext , MAX_CACHED_RES ,
230+ NULL );
231+ }
152232
153233 /*
154- * Look for a match among previously compiled REs. Since the data
155- * structure is self-organizing with most-used entries at the front, our
156- * search strategy can just be to scan from the front.
234+ * Check the most recently used RE first. Using the same pattern over and
235+ * over is the common case, and this saves us computing the hash.
157236 */
158- for ( i = 0 ; i < num_res ; i ++ )
237+ if (! dlist_is_empty ( & re_lru_list ) )
159238 {
160- if (re_array [i ].cre_pat_len == text_re_len &&
161- re_array [i ].cre_flags == cflags &&
162- re_array [i ].cre_collation == collation &&
163- memcmp (re_array [i ].cre_pat , text_re_val , text_re_len ) == 0 )
164- {
165- /*
166- * Found a match; move it to front if not there already.
167- */
168- if (i > 0 )
169- {
170- re_temp = re_array [i ];
171- memmove (& re_array [1 ], & re_array [0 ], i * sizeof (cached_re_str ));
172- re_array [0 ] = re_temp ;
173- }
174-
175- return & re_array [0 ].cre_re ;
176- }
239+ cre = dlist_head_element (cached_re_str , cre_lru_node , & re_lru_list );
240+ if (cre -> cre_pat_len == text_re_len &&
241+ cre -> cre_flags == cflags &&
242+ cre -> cre_collation == collation &&
243+ memcmp (cre -> cre_pat , text_re_val , text_re_len ) == 0 )
244+ return & cre -> cre_re ;
177245 }
178246
179- /* Set up the cache memory on first go through . */
180- if ( unlikely ( RegexpCacheMemoryContext == NULL ))
181- RegexpCacheMemoryContext =
182- AllocSetContextCreate ( TopMemoryContext ,
183- "RegexpCacheMemoryContext" ,
184- ALLOCSET_SMALL_SIZES );
247+ /* Look for a match among previously compiled REs . */
248+ key . pat = text_re_val ;
249+ key . pat_len = text_re_len ;
250+ key . flags = cflags ;
251+ key . collation = collation ;
252+ hash = regexp_cache_key_hash ( key );
185253
186- /*
187- * Couldn't find it, so try to compile the new RE. To avoid leaking
188- * resources on failure, we build into the re_temp local.
189- */
254+ entry = recache_lookup_hash (re_hash , key , hash );
255+ if (entry != NULL )
256+ {
257+ /* Found a match; move it to front if not there already. */
258+ cre = entry -> cre ;
259+ dlist_move_head (& re_lru_list , & cre -> cre_lru_node );
260+ return & cre -> cre_re ;
261+ }
262+
263+ /* Couldn't find it, so try to compile the new RE. */
190264
191265 /* Convert pattern string to wide characters */
192266 pattern = palloc_array (pg_wchar , text_re_len + 1 );
@@ -201,12 +275,15 @@ RE_compile_and_cache(text *text_re, int cflags, Oid collation)
201275 * re-parent it under the longer lived cache context if we make it to the
202276 * bottom of this function.
203277 */
204- re_temp .cre_context = AllocSetContextCreate (CurrentMemoryContext ,
205- "RegexpMemoryContext" ,
206- ALLOCSET_SMALL_SIZES );
207- oldcontext = MemoryContextSwitchTo (re_temp .cre_context );
278+ cre_context = AllocSetContextCreate (CurrentMemoryContext ,
279+ "RegexpMemoryContext" ,
280+ ALLOCSET_SMALL_SIZES );
281+ oldcontext = MemoryContextSwitchTo (cre_context );
282+
283+ cre = palloc_object (cached_re_str );
284+ cre -> cre_context = cre_context ;
208285
209- regcomp_result = pg_regcomp (& re_temp . cre_re ,
286+ regcomp_result = pg_regcomp (& cre -> cre_re ,
210287 pattern ,
211288 pattern_len ,
212289 cflags ,
@@ -217,51 +294,79 @@ RE_compile_and_cache(text *text_re, int cflags, Oid collation)
217294 if (regcomp_result != REG_OKAY )
218295 {
219296 /* re didn't compile (no need for pg_regfree, if so) */
220- pg_regerror (regcomp_result , & re_temp . cre_re , errMsg , sizeof (errMsg ));
297+ pg_regerror (regcomp_result , & cre -> cre_re , errMsg , sizeof (errMsg ));
221298 ereport (ERROR ,
222299 (errcode (ERRCODE_INVALID_REGULAR_EXPRESSION ),
223300 errmsg ("invalid regular expression: %s" , errMsg )));
224301 }
225302
226303 /* Copy the pattern into the per-regexp memory context. */
227- re_temp . cre_pat = palloc (text_re_len + 1 );
228- memcpy (re_temp . cre_pat , text_re_val , text_re_len );
304+ cre -> cre_pat = palloc (text_re_len + 1 );
305+ memcpy (cre -> cre_pat , text_re_val , text_re_len );
229306
230307 /*
231308 * NUL-terminate it only for the benefit of the identifier used for the
232309 * memory context, visible in the pg_backend_memory_contexts view.
233310 */
234- re_temp . cre_pat [text_re_len ] = 0 ;
235- MemoryContextSetIdentifier (re_temp . cre_context , re_temp . cre_pat );
311+ cre -> cre_pat [text_re_len ] = 0 ;
312+ MemoryContextSetIdentifier (cre_context , cre -> cre_pat );
236313
237- re_temp .cre_pat_len = text_re_len ;
238- re_temp .cre_flags = cflags ;
239- re_temp .cre_collation = collation ;
314+ cre -> cre_pat_len = text_re_len ;
315+ cre -> cre_flags = cflags ;
316+ cre -> cre_collation = collation ;
317+
318+ MemoryContextSwitchTo (oldcontext );
240319
241320 /*
242- * Okay, we have a valid new item in re_temp ; insert it into the storage
243- * array. Discard last entry if needed.
321+ * Okay, we have a valid new item in cre ; insert it into the cache.
322+ * Discard the least recently used entry first, if needed.
244323 */
245- if (num_res >= MAX_CACHED_RES )
246- {
247- -- num_res ;
248- Assert (num_res < MAX_CACHED_RES );
249- /* Delete the memory context holding the regexp and pattern. */
250- MemoryContextDelete (re_array [num_res ].cre_context );
251- }
324+ if (re_hash -> members >= MAX_CACHED_RES )
325+ RE_cache_discard_lru ();
326+
327+ /*
328+ * The hash key must point to our own copy of the pattern. Inserting can
329+ * fail with out-of-memory if the hash table needs to grow, so do it
330+ * before anything that would have to be undone.
331+ */
332+ key .pat = cre -> cre_pat ;
333+ entry = recache_insert_hash (re_hash , key , hash , & found );
334+ Assert (!found );
335+ entry -> cre = cre ;
252336
253337 /* Re-parent the memory context to our long-lived cache context. */
254- MemoryContextSetParent (re_temp . cre_context , RegexpCacheMemoryContext );
338+ MemoryContextSetParent (cre_context , RegexpCacheMemoryContext );
255339
256- if (num_res > 0 )
257- memmove (& re_array [1 ], & re_array [0 ], num_res * sizeof (cached_re_str ));
340+ dlist_push_head (& re_lru_list , & cre -> cre_lru_node );
258341
259- re_array [ 0 ] = re_temp ;
260- num_res ++ ;
342+ return & cre -> cre_re ;
343+ }
261344
262- MemoryContextSwitchTo (oldcontext );
345+ /*
346+ * RE_cache_discard_lru - discard the least recently used cached RE
347+ */
348+ static void
349+ RE_cache_discard_lru (void )
350+ {
351+ cached_re_str * cre ;
352+ RegexpCacheKey key ;
353+ bool deleted PG_USED_FOR_ASSERTS_ONLY ;
354+
355+ Assert (!dlist_is_empty (& re_lru_list ));
356+
357+ cre = dlist_tail_element (cached_re_str , cre_lru_node , & re_lru_list );
358+
359+ key .pat = cre -> cre_pat ;
360+ key .pat_len = cre -> cre_pat_len ;
361+ key .flags = cre -> cre_flags ;
362+ key .collation = cre -> cre_collation ;
363+ deleted = recache_delete (re_hash , key );
364+ Assert (deleted );
365+
366+ dlist_delete (& cre -> cre_lru_node );
263367
264- return & re_array [0 ].cre_re ;
368+ /* Delete the memory context holding the regexp, pattern and cre. */
369+ MemoryContextDelete (cre -> cre_context );
265370}
266371
267372/*
0 commit comments