Debian Codegraph @

src/backend/utils/cache/funccache.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * funccache.c
4 * Function cache management.
5 *
6 * funccache.c manages a cache of function execution data. The cache
7 * is used by SQL-language and PL/pgSQL functions, and could be used by
8 * other function languages. Each cache entry is specific to the execution
9 * of a particular function (identified by OID) with specific input data
10 * types; so a polymorphic function could have many associated cache entries.
11 * Trigger functions similarly have a cache entry per trigger. These rules
12 * allow the cached data to be specific to the particular data types the
13 * function call will be dealing with.
14 *
15 *
16 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
17 * Portions Copyright (c) 1994, Regents of the University of California
18 *
19 * IDENTIFICATION
20 * src/backend/utils/cache/funccache.c
21 *
22 *-------------------------------------------------------------------------
23 */
24 #include "postgres.h"
25
26 #include "catalog/pg_proc.h"
27 #include "commands/event_trigger.h"
28 #include "commands/trigger.h"
29 #include "common/hashfn.h"
30 #include "funcapi.h"
31 #include "utils/funccache.h"
32 #include "utils/hsearch.h"
33 #include "utils/syscache.h"
34
35
36 /*
37 * Hash table for cached functions
38 */
39 static HTAB *cfunc_hashtable = NULL;
40
41 typedef struct CachedFunctionHashEntry
42 {
43 CachedFunctionHashKey key; /* hash key, must be first */
44 CachedFunction *function; /* points to data of language-specific size */
45 } CachedFunctionHashEntry;
46
47 #define FUNCS_PER_USER 128 /* initial table size */
48
49 static uint32 cfunc_hash(const void *key, Size keysize);
50 static int cfunc_match(const void *key1, const void *key2, Size keysize);
51
52
53 /*
54 * Initialize the hash table on first use.
55 *
56 * The hash table will be in TopMemoryContext regardless of caller's context.
57 */
58 static void
59 cfunc_hashtable_init(void)
60 {
61 HASHCTL ctl;
62
63 /* don't allow double-initialization */
64 Assert(cfunc_hashtable == NULL);
65
66 ctl.keysize = sizeof(CachedFunctionHashKey);
67 ctl.entrysize = sizeof(CachedFunctionHashEntry);
68 ctl.hash = cfunc_hash;
69 ctl.match = cfunc_match;
70 cfunc_hashtable = hash_create("Cached function hash",
71 FUNCS_PER_USER,
72 &ctl,
73 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
74 }
75
76 /*
77 * cfunc_hash: hash function for cfunc hash table
78 *
79 * We need special hash and match functions to deal with the optional
80 * presence of a TupleDesc in the hash keys. As long as we have to do
81 * that, we might as well also be smart about not comparing unused
82 * elements of the argtypes arrays.
83 */
84 static uint32
85 cfunc_hash(const void *key, Size keysize)
86 {
87 const CachedFunctionHashKey *k = (const CachedFunctionHashKey *) key;
88 uint32 h;
89
90 Assert(keysize == sizeof(CachedFunctionHashKey));
91 /* Hash all the fixed fields except callResultType */
92 h = DatumGetUInt32(hash_any((const unsigned char *) k,
93 offsetof(CachedFunctionHashKey, callResultType)));
94 /* Incorporate input argument types */
95 if (k->nargs > 0)
96 h = hash_combine(h,
97 DatumGetUInt32(hash_any((const unsigned char *) k->argtypes,
98 k->nargs * sizeof(Oid))));
99 /* Incorporate callResultType if present */
100 if (k->callResultType)
101 h = hash_combine(h, hashRowType(k->callResultType));
102 return h;
103 }
104
105 /*
106 * cfunc_match: match function to use with cfunc_hash
107 */
108 static int
109 cfunc_match(const void *key1, const void *key2, Size keysize)
110 {
111 const CachedFunctionHashKey *k1 = (const CachedFunctionHashKey *) key1;
112 const CachedFunctionHashKey *k2 = (const CachedFunctionHashKey *) key2;
113
114 Assert(keysize == sizeof(CachedFunctionHashKey));
115 /* Compare all the fixed fields except callResultType */
116 if (memcmp(k1, k2, offsetof(CachedFunctionHashKey, callResultType)) != 0)
117 return 1; /* not equal */
118 /* Compare input argument types (we just verified that nargs matches) */
119 if (k1->nargs > 0 &&
120 memcmp(k1->argtypes, k2->argtypes, k1->nargs * sizeof(Oid)) != 0)
121 return 1; /* not equal */
122 /* Compare callResultType */
123 if (k1->callResultType)
124 {
125 if (k2->callResultType)
126 {
127 if (!equalRowTypes(k1->callResultType, k2->callResultType))
128 return 1; /* not equal */
129 }
130 else
131 return 1; /* not equal */
132 }
133 else
134 {
135 if (k2->callResultType)
136 return 1; /* not equal */
137 }
138 return 0; /* equal */
139 }
140
141 /*
142 * Look up the CachedFunction for the given hash key.
143 * Returns NULL if not present.
144 */
145 static CachedFunction *
146 cfunc_hashtable_lookup(CachedFunctionHashKey *func_key)
147 {
148 CachedFunctionHashEntry *hentry;
149
150 if (cfunc_hashtable == NULL)
151 return NULL;
152
153 hentry = (CachedFunctionHashEntry *) hash_search(cfunc_hashtable,
154 func_key,
155 HASH_FIND,
156 NULL);
157 if (hentry)
158 return hentry->function;
159 else
160 return NULL;
161 }
162
163 /*
164 * Insert a hash table entry.
165 */
166 static void
167 cfunc_hashtable_insert(CachedFunction *function,
168 CachedFunctionHashKey *func_key)
169 {
170 CachedFunctionHashEntry *hentry;
171 bool found;
172
173 if (cfunc_hashtable == NULL)
174 cfunc_hashtable_init();
175
176 hentry = (CachedFunctionHashEntry *) hash_search(cfunc_hashtable,
177 func_key,
178 HASH_ENTER,
179 &found);
180 if (found)
181 elog(WARNING, "trying to insert a function that already exists");
182
183 /*
184 * If there's a callResultType, copy it into TopMemoryContext. If we're
185 * unlucky enough for that to fail, leave the entry with null
186 * callResultType, which will probably never match anything.
187 */
188 if (func_key->callResultType)
189 {
190 MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
191
192 hentry->key.callResultType = NULL;
193 hentry->key.callResultType = CreateTupleDescCopy(func_key->callResultType);
194 MemoryContextSwitchTo(oldcontext);
195 }
196
197 hentry->function = function;
198
199 /* Set back-link from function to hashtable key */
200 function->fn_hashkey = &hentry->key;
201 }
202
203 /*
204 * Delete a hash table entry.
205 */
206 static void
207 cfunc_hashtable_delete(CachedFunction *function)
208 {
209 CachedFunctionHashEntry *hentry;
210 TupleDesc tupdesc;
211
212 /* do nothing if not in table */
213 if (function->fn_hashkey == NULL)
214 return;
215
216 /*
217 * We need to free the callResultType if present, which is slightly tricky
218 * because it has to be valid during the hashtable search. Fortunately,
219 * because we have the hashkey back-link, we can grab that pointer before
220 * deleting the hashtable entry.
221 */
222 tupdesc = function->fn_hashkey->callResultType;
223
224 hentry = (CachedFunctionHashEntry *) hash_search(cfunc_hashtable,
225 function->fn_hashkey,
226 HASH_REMOVE,
227 NULL);
228 if (hentry == NULL)
229 elog(WARNING, "trying to delete function that does not exist");
230
231 /* Remove back link, which no longer points to allocated storage */
232 function->fn_hashkey = NULL;
233
234 /* Release the callResultType if present */
235 if (tupdesc)
236 FreeTupleDesc(tupdesc);
237 }
238
239 /*
240 * Compute the hashkey for a given function invocation
241 *
242 * The hashkey is returned into the caller-provided storage at *hashkey.
243 * Note however that if a callResultType is incorporated, we've not done
244 * anything about copying that.
245 */
246 static void
247 compute_function_hashkey(FunctionCallInfo fcinfo,
248 Form_pg_proc procStruct,
249 CachedFunctionHashKey *hashkey,
250 Size cacheEntrySize,
251 bool includeResultType,
252 bool forValidator)
253 {
254 /* Make sure pad bytes within fixed part of the struct are zero */
255 memset(hashkey, 0, offsetof(CachedFunctionHashKey, argtypes));
256
257 /* get function OID */
258 hashkey->funcOid = fcinfo->flinfo->fn_oid;
259
260 /* get call context */
261 hashkey->isTrigger = CALLED_AS_TRIGGER(fcinfo);
262 hashkey->isEventTrigger = CALLED_AS_EVENT_TRIGGER(fcinfo);
263
264 /* record cacheEntrySize so multiple languages can share hash table */
265 hashkey->cacheEntrySize = cacheEntrySize;
266
267 /*
268 * If DML trigger, include trigger's OID in the hash, so that each trigger
269 * usage gets a different hash entry, allowing for e.g. different relation
270 * rowtypes or transition table names. In validation mode we do not know
271 * what relation or transition table names are intended to be used, so we
272 * leave trigOid zero; the hash entry built in this case will never be
273 * used for any actual calls.
274 *
275 * We don't currently need to distinguish different event trigger usages
276 * in the same way, since the special parameter variables don't vary in
277 * type in that case.
278 */
279 if (hashkey->isTrigger && !forValidator)
280 {
281 TriggerData *trigdata = (TriggerData *) fcinfo->context;
282
283 hashkey->trigOid = trigdata->tg_trigger->tgoid;
284 }
285
286 /* get input collation, if known */
287 hashkey->inputCollation = fcinfo->fncollation;
288
289 /*
290 * We include only input arguments in the hash key, since output argument
291 * types can be deduced from those, and it would require extra cycles to
292 * include the output arguments. But we have to resolve any polymorphic
293 * argument types to the real types for the call.
294 */
295 if (procStruct->pronargs > 0)
296 {
297 /*
298 * Protect against overrun of fixed-size hashkey->argtypes array. This
299 * also protects later code in places such as PL/pgSQL. Ordinarily the
300 * parser would have checked this long since, but it's possible that
301 * we are looking at a pg_proc entry that was made by a server
302 * executable with a different value of FUNC_MAX_ARGS.
303 */
304 if (procStruct->pronargs > FUNC_MAX_ARGS)
305 ereport(ERROR,
306 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
307 errmsg_plural("cannot pass more than %d argument to a function",
308 "cannot pass more than %d arguments to a function",
309 FUNC_MAX_ARGS,
310 FUNC_MAX_ARGS)));
311 hashkey->nargs = procStruct->pronargs;
312 memcpy(hashkey->argtypes, procStruct->proargtypes.values,
313 procStruct->pronargs * sizeof(Oid));
314 cfunc_resolve_polymorphic_argtypes(procStruct->pronargs,
315 hashkey->argtypes,
316 NULL, /* all args are inputs */
317 fcinfo->flinfo->fn_expr,
318 forValidator,
319 NameStr(procStruct->proname));
320 }
321
322 /*
323 * While regular OUT arguments are sufficiently represented by the
324 * resolved input arguments, a function returning composite has additional
325 * variability: ALTER TABLE/ALTER TYPE could affect what it returns. Also,
326 * a function returning RECORD may depend on a column definition list to
327 * determine its output rowtype. If the caller needs the exact result
328 * type to be part of the hash lookup key, we must run
329 * get_call_result_type() to find that out.
330 */
331 if (includeResultType)
332 {
333 Oid resultTypeId;
334 TupleDesc tupdesc;
335
336 switch (get_call_result_type(fcinfo, &resultTypeId, &tupdesc))
337 {
338 case TYPEFUNC_COMPOSITE:
339 case TYPEFUNC_COMPOSITE_DOMAIN:
340 hashkey->callResultType = tupdesc;
341 break;
342 default:
343 /* scalar result, or indeterminate rowtype */
344 break;
345 }
346 }
347 }
348
349 /*
350 * This is the same as the standard resolve_polymorphic_argtypes() function,
351 * except that:
352 * 1. We go ahead and report the error if we can't resolve the types.
353 * 2. We treat RECORD-type input arguments (not output arguments) as if
354 * they were polymorphic, replacing their types with the actual input
355 * types if we can determine those. This allows us to create a separate
356 * function cache entry for each named composite type passed to such an
357 * argument.
358 * 3. In validation mode, we have no inputs to look at, so assume that
359 * polymorphic arguments are integer, integer-array or integer-range.
360 */
361 void
362 cfunc_resolve_polymorphic_argtypes(int numargs,
363 Oid *argtypes, char *argmodes,
364 Node *call_expr, bool forValidator,
365 const char *proname)
366 {
367 int i;
368
369 if (!forValidator)
370 {
371 int inargno;
372
373 /* normal case, pass to standard routine */
374 if (!resolve_polymorphic_argtypes(numargs, argtypes, argmodes,
375 call_expr))
376 ereport(ERROR,
377 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
378 errmsg("could not determine actual argument "
379 "type for polymorphic function \"%s\"",
380 proname)));
381 /* also, treat RECORD inputs (but not outputs) as polymorphic */
382 inargno = 0;
383 for (i = 0; i < numargs; i++)
384 {
385 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
386
387 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
388 continue;
389 if (argtypes[i] == RECORDOID || argtypes[i] == RECORDARRAYOID)
390 {
391 Oid resolvedtype = get_call_expr_argtype(call_expr,
392 inargno);
393
394 if (OidIsValid(resolvedtype))
395 argtypes[i] = resolvedtype;
396 }
397 inargno++;
398 }
399 }
400 else
401 {
402 /* special validation case (no need to do anything for RECORD) */
403 for (i = 0; i < numargs; i++)
404 {
405 switch (argtypes[i])
406 {
407 case ANYELEMENTOID:
408 case ANYNONARRAYOID:
409 case ANYENUMOID: /* XXX dubious */
410 case ANYCOMPATIBLEOID:
411 case ANYCOMPATIBLENONARRAYOID:
412 argtypes[i] = INT4OID;
413 break;
414 case ANYARRAYOID:
415 case ANYCOMPATIBLEARRAYOID:
416 argtypes[i] = INT4ARRAYOID;
417 break;
418 case ANYRANGEOID:
419 case ANYCOMPATIBLERANGEOID:
420 argtypes[i] = INT4RANGEOID;
421 break;
422 case ANYMULTIRANGEOID:
423 argtypes[i] = INT4MULTIRANGEOID;
424 break;
425 default:
426 break;
427 }
428 }
429 }
430 }
431
432 /*
433 * delete_function - clean up as much as possible of a stale function cache
434 *
435 * We can't release the CachedFunction struct itself, because of the
436 * possibility that there are fn_extra pointers to it. We can release
437 * the subsidiary storage, but only if there are no active evaluations
438 * in progress. Otherwise we'll just leak that storage. Since the
439 * case would only occur if a pg_proc update is detected during a nested
440 * recursive call on the function, a leak seems acceptable.
441 *
442 * Note that this can be called more than once if there are multiple fn_extra
443 * pointers to the same function cache. Hence be careful not to do things
444 * twice.
445 */
446 static void
447 delete_function(CachedFunction *func)
448 {
449 /* remove function from hash table (might be done already) */
450 cfunc_hashtable_delete(func);
451
452 /* release the function's storage if safe and not done already */
453 if (func->use_count == 0 &&
454 func->dcallback != NULL)
455 {
456 func->dcallback(func);
457 func->dcallback = NULL;
458 }
459 }
460
461 /*
462 * Compile a cached function, if no existing cache entry is suitable.
463 *
464 * fcinfo is the current call information.
465 *
466 * function should be NULL or the result of a previous call of
467 * cached_function_compile() for the same fcinfo. The caller will
468 * typically save the result in fcinfo->flinfo->fn_extra, or in a
469 * field of a struct pointed to by fn_extra, to re-use in later
470 * calls within the same query.
471 *
472 * ccallback and dcallback are function-language-specific callbacks to
473 * compile and delete a cached function entry. dcallback can be NULL
474 * if there's nothing for it to do.
475 *
476 * cacheEntrySize is the function-language-specific size of the cache entry
477 * (which embeds a CachedFunction struct and typically has many more fields
478 * after that).
479 *
480 * If includeResultType is true and the function returns composite,
481 * include the actual result descriptor in the cache lookup key.
482 *
483 * If forValidator is true, we're only compiling for validation purposes,
484 * and so some checks are skipped.
485 *
486 * Note: it's important for this to fall through quickly if the function
487 * has already been compiled.
488 *
489 * Note: this function leaves the "use_count" field as zero. The caller
490 * is expected to increment the use_count and decrement it when done with
491 * the cache entry.
492 */
493 CachedFunction *
494 cached_function_compile(FunctionCallInfo fcinfo,
495 CachedFunction *function,
496 CachedFunctionCompileCallback ccallback,
497 CachedFunctionDeleteCallback dcallback,
498 Size cacheEntrySize,
499 bool includeResultType,
500 bool forValidator)
501 {
502 Oid funcOid = fcinfo->flinfo->fn_oid;
503 HeapTuple procTup;
504 Form_pg_proc procStruct;
505 CachedFunctionHashKey hashkey;
506 bool function_valid = false;
507 bool hashkey_valid = false;
508 bool new_function = false;
509
510 /*
511 * Lookup the pg_proc tuple by Oid; we'll need it in any case
512 */
513 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcOid));
514 if (!HeapTupleIsValid(procTup))
515 elog(ERROR, "cache lookup failed for function %u", funcOid);
516 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
517
518 /*
519 * Do we already have a cache entry for the current FmgrInfo? If not, try
520 * to find one in the hash table.
521 */
522 recheck:
523 if (!function)
524 {
525 /* Compute hashkey using function signature and actual arg types */
526 compute_function_hashkey(fcinfo, procStruct, &hashkey,
527 cacheEntrySize, includeResultType,
528 forValidator);
529 hashkey_valid = true;
530
531 /* And do the lookup */
532 function = cfunc_hashtable_lookup(&hashkey);
533 }
534
535 if (function)
536 {
537 /* We have a compiled function, but is it still valid? */
538 if (function->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
539 ItemPointerEquals(&function->fn_tid, &procTup->t_self))
540 function_valid = true;
541 else
542 {
543 /*
544 * Nope, so remove it from hashtable and try to drop associated
545 * storage (if not done already).
546 */
547 delete_function(function);
548
549 /*
550 * If the function isn't in active use then we can overwrite the
551 * func struct with new data, allowing any other existing fn_extra
552 * pointers to make use of the new definition on their next use.
553 * If it is in use then just leave it alone and make a new one.
554 * (The active invocations will run to completion using the
555 * previous definition, and then the cache entry will just be
556 * leaked; doesn't seem worth adding code to clean it up, given
557 * what a corner case this is.)
558 *
559 * If we found the function struct via fn_extra then it's possible
560 * a replacement has already been made, so go back and recheck the
561 * hashtable.
562 */
563 if (function->use_count != 0)
564 {
565 function = NULL;
566 if (!hashkey_valid)
567 goto recheck;
568 }
569 }
570 }
571
572 /*
573 * If the function wasn't found or was out-of-date, we have to compile it.
574 */
575 if (!function_valid)
576 {
577 /*
578 * Calculate hashkey if we didn't already; we'll need it to store the
579 * completed function.
580 */
581 if (!hashkey_valid)
582 compute_function_hashkey(fcinfo, procStruct, &hashkey,
583 cacheEntrySize, includeResultType,
584 forValidator);
585
586 /*
587 * Create the new function struct, if not done already. The function
588 * cache entry will be kept for the life of the backend, so put it in
589 * TopMemoryContext.
590 */
591 Assert(cacheEntrySize >= sizeof(CachedFunction));
592 if (function == NULL)
593 {
594 function = (CachedFunction *)
595 MemoryContextAllocZero(TopMemoryContext, cacheEntrySize);
596 new_function = true;
597 }
598 else
599 {
600 /* re-using a previously existing struct, so clear it out */
601 memset(function, 0, cacheEntrySize);
602 }
603
604 /*
605 * However, if function compilation fails, we'd like not to leak the
606 * function struct, so use a PG_TRY block to prevent that. (It's up
607 * to the compile callback function to avoid its own internal leakage
608 * in such cases.) Unfortunately, freeing the struct is only safe if
609 * we just allocated it: otherwise there are probably fn_extra
610 * pointers to it.
611 */
612 PG_TRY();
613 {
614 /*
615 * Do the hard, language-specific part.
616 */
617 ccallback(fcinfo, procTup, &hashkey, function, forValidator);
618 }
619 PG_CATCH();
620 {
621 if (new_function)
622 pfree(function);
623 PG_RE_THROW();
624 }
625 PG_END_TRY();
626
627 /*
628 * Fill in the CachedFunction part. (We do this last to prevent the
629 * function from looking valid before it's fully built.) fn_hashkey
630 * will be set by cfunc_hashtable_insert; use_count remains zero.
631 */
632 function->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
633 function->fn_tid = procTup->t_self;
634 function->dcallback = dcallback;
635
636 /*
637 * Add the completed struct to the hash table.
638 */
639 cfunc_hashtable_insert(function, &hashkey);
640 }
641
642 ReleaseSysCache(procTup);
643
644 /*
645 * Finally return the compiled function
646 */
647 return function;
648 }