OSDN Git Service

72695fe197dcd0ef63be7e5373b4aa8f1d86ff13
[pg-rex/syncrep.git] / src / backend / utils / fmgr / README
1 src/backend/utils/fmgr/README
2
3 Function Manager
4 ================
5
6 Proposal For Function-Manager Redesign                  19-Nov-2000
7 --------------------------------------
8
9 We know that the existing mechanism for calling Postgres functions needs
10 to be redesigned.  It has portability problems because it makes
11 assumptions about parameter passing that violate ANSI C; it fails to
12 handle NULL arguments and results cleanly; and "function handlers" that
13 support a class of functions (such as fmgr_pl) can only be done via a
14 really ugly, non-reentrant kluge.  (Global variable set during every
15 function call, forsooth.)  Here is a proposal for fixing these problems.
16
17 In the past, the major objections to redoing the function-manager
18 interface have been (a) it'll be quite tedious to implement, since every
19 built-in function and everyplace that calls such functions will need to
20 be touched; (b) such wide-ranging changes will be difficult to make in
21 parallel with other development work; (c) it will break existing
22 user-written loadable modules that define "C language" functions.  While
23 I have no solution to the "tedium" aspect, I believe I see an answer to
24 the other problems: by use of function handlers, we can support both old
25 and new interfaces in parallel for both callers and callees, at some
26 small efficiency cost for the old styles.  That way, most of the changes
27 can be done on an incremental file-by-file basis --- we won't need a
28 "big bang" where everything changes at once.  Support for callees
29 written in the old style can be left in place indefinitely, to provide
30 backward compatibility for user-written C functions.
31
32
33 Changes In pg_proc (System Data About a Function)
34 -------------------------------------------------
35
36 A new column "proisstrict" will be added to the system pg_proc table.
37 This is a boolean value which will be TRUE if the function is "strict",
38 that is it always returns NULL when any of its inputs are NULL.  The
39 function manager will check this field and skip calling the function when
40 it's TRUE and there are NULL inputs.  This allows us to remove explicit
41 NULL-value tests from many functions that currently need them (not to
42 mention fixing many more that need them but don't have them).  A function
43 that is not marked "strict" is responsible for checking whether its inputs
44 are NULL or not.  Most builtin functions will be marked "strict".
45
46 An optional WITH parameter will be added to CREATE FUNCTION to allow
47 specification of whether user-defined functions are strict or not.  I am
48 inclined to make the default be "not strict", since that seems to be the
49 more useful case for functions expressed in SQL or a PL language, but
50 am open to arguments for the other choice.
51
52
53 The New Function-Manager Interface
54 ----------------------------------
55
56 The core of the new design is revised data structures for representing
57 the result of a function lookup and for representing the parameters
58 passed to a specific function invocation.  (We want to keep function
59 lookup separate from function call, since many parts of the system apply
60 the same function over and over; the lookup overhead should be paid once
61 per query, not once per tuple.)
62
63
64 When a function is looked up in pg_proc, the result is represented as
65
66 typedef struct
67 {
68     PGFunction  fn_addr;    /* pointer to function or handler to be called */
69     Oid         fn_oid;     /* OID of function (NOT of handler, if any) */
70     short       fn_nargs;   /* 0..FUNC_MAX_ARGS, or -1 if variable arg count */
71     bool        fn_strict;  /* function is "strict" (NULL in => NULL out) */
72     bool        fn_retset;  /* function returns a set (over multiple calls) */
73     unsigned char fn_stats; /* collect stats if track_functions > this */
74     void       *fn_extra;   /* extra space for use by handler */
75     MemoryContext fn_mcxt;  /* memory context to store fn_extra in */
76     Node       *fn_expr;    /* expression parse tree for call, or NULL */
77 } FmgrInfo;
78
79 For an ordinary built-in function, fn_addr is just the address of the C
80 routine that implements the function.  Otherwise it is the address of a
81 handler for the class of functions that includes the target function.
82 The handler can use the function OID and perhaps also the fn_extra slot
83 to find the specific code to execute.  (fn_oid = InvalidOid can be used
84 to denote a not-yet-initialized FmgrInfo struct.  fn_extra will always
85 be NULL when an FmgrInfo is first filled by the function lookup code, but
86 a function handler could set it to avoid making repeated lookups of its
87 own when the same FmgrInfo is used repeatedly during a query.)  fn_nargs
88 is the number of arguments expected by the function, fn_strict is its
89 strictness flag, and fn_retset shows whether it returns a set; all of
90 these values come from the function's pg_proc entry.  fn_stats is also
91 set up to control whether or not to track runtime statistics for calling
92 this function.  If the function is being called as part of a SQL expression,
93 fn_expr will point to the expression parse tree for the function call; this
94 can be used to extract parse-time knowledge about the actual arguments.
95
96 FmgrInfo already exists in the current code, but has fewer fields.  This
97 change should be transparent at the source-code level.
98
99
100 During a call of a function, the following data structure is created
101 and passed to the function:
102
103 typedef struct
104 {
105     FmgrInfo   *flinfo;         /* ptr to lookup info used for this call */
106     Node       *context;        /* pass info about context of call */
107     Node       *resultinfo;     /* pass or return extra info about result */
108     bool        isnull;         /* function must set true if result is NULL */
109     short       nargs;          /* # arguments actually passed */
110     Datum       arg[FUNC_MAX_ARGS];  /* Arguments passed to function */
111     bool        argnull[FUNC_MAX_ARGS];  /* T if arg[i] is actually NULL */
112 } FunctionCallInfoData;
113 typedef FunctionCallInfoData* FunctionCallInfo;
114
115 flinfo points to the lookup info used to make the call.  Ordinary functions
116 will probably ignore this field, but function class handlers will need it
117 to find out the OID of the specific function being called.
118
119 context is NULL for an "ordinary" function call, but may point to additional
120 info when the function is called in certain contexts.  (For example, the
121 trigger manager will pass information about the current trigger event here.)
122 If context is used, it should point to some subtype of Node; the particular
123 kind of context is indicated by the node type field.  (A callee should
124 always check the node type before assuming it knows what kind of context is
125 being passed.)  fmgr itself puts no other restrictions on the use of this
126 field.
127
128 resultinfo is NULL when calling any function from which a simple Datum
129 result is expected.  It may point to some subtype of Node if the function
130 returns more than a Datum.  (For example, resultinfo is used when calling a
131 function that returns a set, as discussed below.)  Like the context field,
132 resultinfo is a hook for expansion; fmgr itself doesn't constrain the use
133 of the field.
134
135 nargs, arg[], and argnull[] hold the arguments being passed to the function.
136 Notice that all the arguments passed to a function (as well as its result
137 value) will now uniformly be of type Datum.  As discussed below, callers
138 and callees should apply the standard Datum-to-and-from-whatever macros
139 to convert to the actual argument types of a particular function.  The
140 value in arg[i] is unspecified when argnull[i] is true.
141
142 It is generally the responsibility of the caller to ensure that the
143 number of arguments passed matches what the callee is expecting; except
144 for callees that take a variable number of arguments, the callee will
145 typically ignore the nargs field and just grab values from arg[].
146
147 The isnull field will be initialized to "false" before the call.  On
148 return from the function, isnull is the null flag for the function result:
149 if it is true the function's result is NULL, regardless of the actual
150 function return value.  Note that simple "strict" functions can ignore
151 both isnull and argnull[], since they won't even get called when there
152 are any TRUE values in argnull[].
153
154 FunctionCallInfo replaces FmgrValues plus a bunch of ad-hoc parameter
155 conventions, global variables (fmgr_pl_finfo and CurrentTriggerData at
156 least), and other uglinesses.
157
158
159 Callees, whether they be individual functions or function handlers,
160 shall always have this signature:
161
162 Datum function (FunctionCallInfo fcinfo);
163
164 which is represented by the typedef
165
166 typedef Datum (*PGFunction) (FunctionCallInfo fcinfo);
167
168 The function is responsible for setting fcinfo->isnull appropriately
169 as well as returning a result represented as a Datum.  Note that since
170 all callees will now have exactly the same signature, and will be called
171 through a function pointer declared with exactly that signature, we
172 should have no portability or optimization problems.
173
174
175 Function Coding Conventions
176 ---------------------------
177
178 As an example, int4 addition goes from old-style
179
180 int32
181 int4pl(int32 arg1, int32 arg2)
182 {
183     return arg1 + arg2;
184 }
185
186 to new-style
187
188 Datum
189 int4pl(FunctionCallInfo fcinfo)
190 {
191     /* we assume the function is marked "strict", so we can ignore
192      * NULL-value handling */
193
194     return Int32GetDatum(DatumGetInt32(fcinfo->arg[0]) +
195                          DatumGetInt32(fcinfo->arg[1]));
196 }
197
198 This is, of course, much uglier than the old-style code, but we can
199 improve matters with some well-chosen macros for the boilerplate parts.
200 I propose below macros that would make the code look like
201
202 Datum
203 int4pl(PG_FUNCTION_ARGS)
204 {
205     int32   arg1 = PG_GETARG_INT32(0);
206     int32   arg2 = PG_GETARG_INT32(1);
207
208     PG_RETURN_INT32( arg1 + arg2 );
209 }
210
211 This is still more code than before, but it's fairly readable, and it's
212 also amenable to machine processing --- for example, we could probably
213 write a script that scans code like this and extracts argument and result
214 type info for comparison to the pg_proc table.
215
216 For the standard data types float4, float8, and int8, these macros should hide
217 whether the types are pass-by-value or pass-by reference, by incorporating
218 indirection and space allocation if needed.  This will offer a considerable
219 gain in readability, and it also opens up the opportunity to make these types
220 be pass-by-value on machines where it's feasible to do so.
221
222 Here are the proposed macros and coding conventions:
223
224 The definition of an fmgr-callable function will always look like
225
226 Datum
227 function_name(PG_FUNCTION_ARGS)
228 {
229         ...
230 }
231
232 "PG_FUNCTION_ARGS" just expands to "FunctionCallInfo fcinfo".  The main
233 reason for using this macro is to make it easy for scripts to spot function
234 definitions.  However, if we ever decide to change the calling convention
235 again, it might come in handy to have this macro in place.
236
237 A nonstrict function is responsible for checking whether each individual
238 argument is null or not, which it can do with PG_ARGISNULL(n) (which is
239 just "fcinfo->argnull[n]").  It should avoid trying to fetch the value
240 of any argument that is null.
241
242 Both strict and nonstrict functions can return NULL, if needed, with
243         PG_RETURN_NULL();
244 which expands to
245         { fcinfo->isnull = true; return (Datum) 0; }
246
247 Argument values are ordinarily fetched using code like
248         int32   name = PG_GETARG_INT32(number);
249
250 For float4, float8, and int8, the PG_GETARG macros will hide whether the
251 types are pass-by-value or pass-by-reference.  For example, if float8 is
252 pass-by-reference then PG_GETARG_FLOAT8 expands to
253         (* (float8 *) DatumGetPointer(fcinfo->arg[number]))
254 and would typically be called like this:
255         float8  arg = PG_GETARG_FLOAT8(0);
256 For what are now historical reasons, the float-related typedefs and macros
257 express the type width in bytes (4 or 8), whereas we prefer to label the
258 widths of integer types in bits.
259
260 Non-null values are returned with a PG_RETURN_XXX macro of the appropriate
261 type.  For example, PG_RETURN_INT32 expands to
262         return Int32GetDatum(x)
263 PG_RETURN_FLOAT4, PG_RETURN_FLOAT8, and PG_RETURN_INT64 hide whether their
264 data types are pass-by-value or pass-by-reference, by doing a palloc if
265 needed.
266
267 fmgr.h will provide PG_GETARG and PG_RETURN macros for all the basic data
268 types.  Modules or header files that define specialized SQL datatypes
269 (eg, timestamp) should define appropriate macros for those types, so that
270 functions manipulating the types can be coded in the standard style.
271
272 For non-primitive data types (particularly variable-length types) it won't
273 be very practical to hide the pass-by-reference nature of the data type,
274 so the PG_GETARG and PG_RETURN macros for those types won't do much more
275 than DatumGetPointer/PointerGetDatum plus the appropriate typecast (but see
276 TOAST discussion, below).  Functions returning such types will need to
277 palloc() their result space explicitly.  I recommend naming the GETARG and
278 RETURN macros for such types to end in "_P", as a reminder that they
279 produce or take a pointer.  For example, PG_GETARG_TEXT_P yields "text *".
280
281 When a function needs to access fcinfo->flinfo or one of the other auxiliary
282 fields of FunctionCallInfo, it should just do it.  I doubt that providing
283 syntactic-sugar macros for these cases is useful.
284
285
286 Call-Site Coding Conventions
287 ----------------------------
288
289 There are many places in the system that call either a specific function
290 (for example, the parser invokes "textin" by name in places) or a
291 particular group of functions that have a common argument list (for
292 example, the optimizer invokes selectivity estimation functions with
293 a fixed argument list).  These places will need to change, but we should
294 try to avoid making them significantly uglier than before.
295
296 Places that invoke an arbitrary function with an arbitrary argument list
297 can simply be changed to fill a FunctionCallInfoData structure directly;
298 that'll be no worse and possibly cleaner than what they do now.
299
300 When invoking a specific built-in function by name, we have generally
301 just written something like
302         result = textin ( ... args ... )
303 which will not work after textin() is converted to the new call style.
304 I suggest that code like this be converted to use "helper" functions
305 that will create and fill in a FunctionCallInfoData struct.  For
306 example, if textin is being called with one argument, it'd look
307 something like
308         result = DirectFunctionCall1(textin, PointerGetDatum(argument));
309 These helper routines will have declarations like
310         Datum DirectFunctionCall2(PGFunction func, Datum arg1, Datum arg2);
311 Note it will be the caller's responsibility to convert to and from
312 Datum; appropriate conversion macros should be used.
313
314 The DirectFunctionCallN routines will not bother to fill in
315 fcinfo->flinfo (indeed cannot, since they have no idea about an OID for
316 the target function); they will just set it NULL.  This is unlikely to
317 bother any built-in function that could be called this way.  Note also
318 that this style of coding cannot pass a NULL input value nor cope with
319 a NULL result (it couldn't before, either!).  We can make the helper
320 routines ereport an error if they see that the function returns a NULL.
321
322 When invoking a function that has a known argument signature, we have
323 usually written either
324         result = fmgr(targetfuncOid, ... args ... );
325 or
326         result = fmgr_ptr(FmgrInfo *finfo, ... args ... );
327 depending on whether an FmgrInfo lookup has been done yet or not.
328 This kind of code can be recast using helper routines, in the same
329 style as above:
330         result = OidFunctionCall1(funcOid, PointerGetDatum(argument));
331         result = FunctionCall2(funcCallInfo,
332                                PointerGetDatum(argument),
333                                Int32GetDatum(argument));
334 Again, this style of coding does not allow for expressing NULL inputs
335 or receiving a NULL result.
336
337 As with the callee-side situation, I propose adding argument conversion
338 macros that hide whether int8, float4, and float8 are pass-by-value or
339 pass-by-reference.
340
341 The existing helper functions fmgr(), fmgr_c(), etc will be left in
342 place until all uses of them are gone.  Of course their internals will
343 have to change in the first step of implementation, but they can
344 continue to support the same external appearance.
345
346
347 Support for TOAST-Able Data Types
348 ---------------------------------
349
350 For TOAST-able data types, the PG_GETARG macro will deliver a de-TOASTed
351 data value.  There might be a few cases where the still-toasted value is
352 wanted, but the vast majority of cases want the de-toasted result, so
353 that will be the default.  To get the argument value without causing
354 de-toasting, use PG_GETARG_RAW_VARLENA_P(n).
355
356 Some functions require a modifiable copy of their input values.  In these
357 cases, it's silly to do an extra copy step if we copied the data anyway
358 to de-TOAST it.  Therefore, each toastable datatype has an additional
359 fetch macro, for example PG_GETARG_TEXT_P_COPY(n), which delivers a
360 guaranteed-fresh copy, combining this with the detoasting step if possible.
361
362 There is also a PG_FREE_IF_COPY(ptr,n) macro, which pfree's the given
363 pointer if and only if it is different from the original value of the n'th
364 argument.  This can be used to free the de-toasted value of the n'th
365 argument, if it was actually de-toasted.  Currently, doing this is not
366 necessary for the majority of functions because the core backend code
367 releases temporary space periodically, so that memory leaked in function
368 execution isn't a big problem.  However, as of 7.1 memory leaks in
369 functions that are called by index searches will not be cleaned up until
370 end of transaction.  Therefore, functions that are listed in pg_amop or
371 pg_amproc should be careful not to leak detoasted copies, and so these
372 functions do need to use PG_FREE_IF_COPY() for toastable inputs.
373
374 A function should never try to re-TOAST its result value; it should just
375 deliver an untoasted result that's been palloc'd in the current memory
376 context.  When and if the value is actually stored into a tuple, the
377 tuple toaster will decide whether toasting is needed.
378
379
380 Functions Accepting or Returning Sets
381 -------------------------------------
382
383 [ this section revised 29-Aug-2002 for 7.3 ]
384
385 If a function is marked in pg_proc as returning a set, then it is called
386 with fcinfo->resultinfo pointing to a node of type ReturnSetInfo.  A
387 function that desires to return a set should raise an error "called in
388 context that does not accept a set result" if resultinfo is NULL or does
389 not point to a ReturnSetInfo node.
390
391 There are currently two modes in which a function can return a set result:
392 value-per-call, or materialize.  In value-per-call mode, the function returns
393 one value each time it is called, and finally reports "done" when it has no
394 more values to return.  In materialize mode, the function's output set is
395 instantiated in a Tuplestore object; all the values are returned in one call.
396 Additional modes might be added in future.
397
398 ReturnSetInfo contains a field "allowedModes" which is set (by the caller)
399 to a bitmask that's the OR of the modes the caller can support.  The actual
400 mode used by the function is returned in another field "returnMode".  For
401 backwards-compatibility reasons, returnMode is initialized to value-per-call
402 and need only be changed if the function wants to use a different mode.
403 The function should ereport() if it cannot use any of the modes the caller is
404 willing to support.
405
406 Value-per-call mode works like this: ReturnSetInfo contains a field
407 "isDone", which should be set to one of these values:
408
409     ExprSingleResult             /* expression does not return a set */
410     ExprMultipleResult           /* this result is an element of a set */
411     ExprEndResult                /* there are no more elements in the set */
412
413 (the caller will initialize it to ExprSingleResult).  If the function simply
414 returns a Datum without touching ReturnSetInfo, then the call is over and a
415 single-item set has been returned.  To return a set, the function must set
416 isDone to ExprMultipleResult for each set element.  After all elements have
417 been returned, the next call should set isDone to ExprEndResult and return a
418 null result.  (Note it is possible to return an empty set by doing this on
419 the first call.)
420
421 The ReturnSetInfo node also contains a link to the ExprContext within which
422 the function is being evaluated.  This is useful for value-per-call functions
423 that need to close down internal state when they are not run to completion:
424 they can register a shutdown callback function in the ExprContext.
425
426 Materialize mode works like this: the function creates a Tuplestore holding
427 the (possibly empty) result set, and returns it.  There are no multiple calls.
428 The function must also return a TupleDesc that indicates the tuple structure.
429 The Tuplestore and TupleDesc should be created in the context
430 econtext->ecxt_per_query_memory (note this will *not* be the context the
431 function is called in).  The function stores pointers to the Tuplestore and
432 TupleDesc into ReturnSetInfo, sets returnMode to indicate materialize mode,
433 and returns null.  isDone is not used and should be left at ExprSingleResult.
434
435 The Tuplestore must be created with randomAccess = true if
436 SFRM_Materialize_Random is set in allowedModes, but it can (and preferably
437 should) be created with randomAccess = false if not.  Callers that can support
438 both ValuePerCall and Materialize mode will set SFRM_Materialize_Preferred,
439 or not, depending on which mode they prefer.
440
441 If available, the expected tuple descriptor is passed in ReturnSetInfo;
442 in other contexts the expectedDesc field will be NULL.  The function need
443 not pay attention to expectedDesc, but it may be useful in special cases.
444
445 There is no support for functions accepting sets; instead, the function will
446 be called multiple times, once for each element of the input set.
447
448
449 Notes About Function Handlers
450 -----------------------------
451
452 Handlers for classes of functions should find life much easier and
453 cleaner in this design.  The OID of the called function is directly
454 reachable from the passed parameters; we don't need the global variable
455 fmgr_pl_finfo anymore.  Also, by modifying fcinfo->flinfo->fn_extra,
456 the handler can cache lookup info to avoid repeat lookups when the same
457 function is invoked many times.  (fn_extra can only be used as a hint,
458 since callers are not required to re-use an FmgrInfo struct.
459 But in performance-critical paths they normally will do so.)
460
461 If the handler wants to allocate memory to hold fn_extra data, it should
462 NOT do so in CurrentMemoryContext, since the current context may well be
463 much shorter-lived than the context where the FmgrInfo is.  Instead,
464 allocate the memory in context flinfo->fn_mcxt, or in a long-lived cache
465 context.  fn_mcxt normally points at the context that was
466 CurrentMemoryContext at the time the FmgrInfo structure was created;
467 in any case it is required to be a context at least as long-lived as the
468 FmgrInfo itself.
469
470
471 Telling the Difference Between Old- and New-Style Functions
472 -----------------------------------------------------------
473
474 During the conversion process, we carried two different pg_language
475 entries, "internal" and "newinternal", for internal functions.  The
476 function manager used the language code to distinguish which calling
477 convention to use.  (Old-style internal functions were supported via
478 a function handler.)  As of Nov. 2000, no old-style internal functions
479 remain, so we can drop support for them.  We will remove the old "internal"
480 pg_language entry and rename "newinternal" to "internal".
481
482 The interim solution for dynamically-loaded compiled functions has been
483 similar: two pg_language entries "C" and "newC".  This naming convention
484 is not desirable for the long run, and yet we cannot stop supporting
485 old-style user functions.  Instead, it seems better to use just one
486 pg_language entry "C", and require the dynamically-loaded library to
487 provide additional information that identifies new-style functions.
488 This avoids compatibility problems --- for example, existing dump
489 scripts will identify PL language handlers as being in language "C",
490 which would be wrong under the "newC" convention.  Also, this approach
491 should generalize more conveniently for future extensions to the function
492 interface specification.
493
494 Given a dynamically loaded function named "foo" (note that the name being
495 considered here is the link-symbol name, not the SQL-level function name),
496 the function manager will look for another function in the same dynamically
497 loaded library named "pg_finfo_foo".  If this second function does not
498 exist, then foo is assumed to be called old-style, thus ensuring backwards
499 compatibility with existing libraries.  If the info function does exist,
500 it is expected to have the signature
501
502         Pg_finfo_record * pg_finfo_foo (void);
503
504 The info function will be called by the fmgr, and must return a pointer
505 to a Pg_finfo_record struct.  (The returned struct will typically be a
506 statically allocated constant in the dynamic-link library.)  The current
507 definition of the struct is just
508
509         typedef struct {
510                 int     api_version;
511         } Pg_finfo_record;
512
513 where api_version is 0 to indicate old-style or 1 to indicate new-style
514 calling convention.  In future releases, additional fields may be defined
515 after api_version, but these additional fields will only be used if
516 api_version is greater than 1.
517
518 These details will be hidden from the author of a dynamically loaded
519 function by using a macro.  To define a new-style dynamically loaded
520 function named foo, write
521
522         PG_FUNCTION_INFO_V1(foo);
523
524         Datum
525         foo(PG_FUNCTION_ARGS)
526         {
527                 ...
528         }
529
530 The function itself is written using the same conventions as for new-style
531 internal functions; you just need to add the PG_FUNCTION_INFO_V1() macro.
532 Note that old-style and new-style functions can be intermixed in the same
533 library, depending on whether or not you write a PG_FUNCTION_INFO_V1() for
534 each one.
535
536 The SQL declaration for a dynamically-loaded function is CREATE FUNCTION
537 foo ... LANGUAGE C regardless of whether it is old- or new-style.
538
539 New-style dynamic functions will be invoked directly by fmgr, and will
540 therefore have the same performance as internal functions after the initial
541 pg_proc lookup overhead.  Old-style dynamic functions will be invoked via
542 a handler, and will therefore have a small performance penalty.
543
544 To allow old-style dynamic functions to work safely on toastable datatypes,
545 the handler for old-style functions will automatically detoast toastable
546 arguments before passing them to the old-style function.  A new-style
547 function is expected to take care of toasted arguments by using the
548 standard argument access macros defined above.